2025-08-05 07:08:07 +00:00
|
|
|
|
// Package main is the main package for the WeKnora server
|
|
|
|
|
|
// It contains the main function and the entry point for the server
|
2025-12-16 08:40:13 +00:00
|
|
|
|
//
|
|
|
|
|
|
// @title WeKnora API
|
|
|
|
|
|
// @version 1.0
|
|
|
|
|
|
// @description WeKnora 知识库管理系统 API 文档
|
|
|
|
|
|
// @termsOfService http://swagger.io/terms/
|
|
|
|
|
|
//
|
|
|
|
|
|
// @contact.name WeKnora Github
|
|
|
|
|
|
// @contact.url https://github.com/Tencent/WeKnora
|
|
|
|
|
|
//
|
|
|
|
|
|
// @BasePath /api/v1
|
|
|
|
|
|
//
|
|
|
|
|
|
// @securityDefinitions.apikey Bearer
|
|
|
|
|
|
// @in header
|
|
|
|
|
|
// @name Authorization
|
2025-12-22 06:36:29 +00:00
|
|
|
|
// @description 用户登录认证:输入 Bearer {token} 格式的 JWT 令牌
|
|
|
|
|
|
|
|
|
|
|
|
// @securityDefinitions.apikey ApiKeyAuth
|
|
|
|
|
|
// @in header
|
|
|
|
|
|
// @name X-API-Key
|
2026-07-21 07:05:57 +00:00
|
|
|
|
// @description API Key 认证:空间 Key 固定访问所属空间;平台 Key 调用空间接口时需同时传 X-Tenant-ID
|
2025-08-05 07:08:07 +00:00
|
|
|
|
package main
|
|
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
|
"context"
|
|
|
|
|
|
"fmt"
|
|
|
|
|
|
"net/http"
|
|
|
|
|
|
"os"
|
|
|
|
|
|
"os/signal"
|
|
|
|
|
|
"time"
|
|
|
|
|
|
|
|
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
|
|
|
feat(models): add system admin model catalog console (#3662)
* feat(models): add system admin model catalog console
System administrators can now maintain the model catalog from
Settings → System administration → Model catalog instead of editing
models.json on every replica. Administrator changes are stored as a
versioned overlay in the database (new model_catalog_config table),
layered between the deployment file and explicit per-model settings,
and synchronised to other instances within about 5 seconds.
Backend
- GET/POST preview/PUT /system/admin/model-catalog with optimistic
version + deployment baseline checks (409 on conflict), 20-version
history and audit logging.
- Console overlays reject credentials, headers, env interpolation and
non-inline icons; those stay deployment-owned.
- Catalog views include each chat model's resolved thinking levels and
the vendor defaults, so the console never re-implements level
inheritance.
Frontend
- Model list in the shared data-table style with provider/type filters,
"modified only" filter and source tags (built-in / deployment / admin).
- Edit drawer saves and applies immediately: display name, context
window, max output, input modalities, reasoning, thinking levels,
embedding dimension and picker visibility, each with its inherited
default and a layer comparison table.
- Add-model drawer, JSON editor with server-side change check before
publishing, and version history with one-step restore.
- Model settings gets a system-admin shortcut to the catalog; model
editor reloads providers when opened so published catalogs apply.
* fix(models): harden the admin model catalog console
- Reject console base_url, base_urls, url_patterns and auth: moving a
vendor's default URL would send its deployment api_key (and keys of rows
without their own base URL) to another host. With every interpolated
field now deployment-owned, '$' in names and descriptions is plain text.
- Drop deployment base URLs from catalog views; they may carry
interpolated tokens.
- Remember a stored version this replica cannot compile and skip it until
the version changes, instead of re-reading and recompiling every poll.
- Resolve vendor default thinking levels with reasoning forced on, like
per-model levels.
- Compute builtin/deployment views once; preview returns only the
candidate catalog and normalized overlay.
- Share deployment file lookup via runtime.ReadDeploymentOverlay.
- The model editor force-refreshes its own type instead of resetting the
provider store for every type; the refreshed list wins in the id index.
2026-09-24 08:31:45 +00:00
|
|
|
|
"github.com/Tencent/WeKnora/internal/application/service"
|
2025-08-05 07:08:07 +00:00
|
|
|
|
"github.com/Tencent/WeKnora/internal/config"
|
|
|
|
|
|
"github.com/Tencent/WeKnora/internal/container"
|
2026-02-06 06:16:25 +00:00
|
|
|
|
"github.com/Tencent/WeKnora/internal/logger"
|
2025-08-05 07:08:07 +00:00
|
|
|
|
"github.com/Tencent/WeKnora/internal/runtime"
|
|
|
|
|
|
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
func main() {
|
|
|
|
|
|
// Set Gin mode
|
|
|
|
|
|
if os.Getenv("GIN_MODE") == "release" {
|
|
|
|
|
|
gin.SetMode(gin.ReleaseMode)
|
|
|
|
|
|
} else {
|
|
|
|
|
|
gin.SetMode(gin.DebugMode)
|
|
|
|
|
|
}
|
2026-05-17 06:42:24 +00:00
|
|
|
|
// Mute Gin's per-route registration spam (one line per route × ~150
|
|
|
|
|
|
// routes) — replaced by a single summary printed after router build.
|
|
|
|
|
|
runtime.SilenceGinRouteSpam()
|
|
|
|
|
|
// Print the env banner before container build so operators see what
|
|
|
|
|
|
// config landed even when DB / storage init fails.
|
|
|
|
|
|
runtime.LogStartupEnv(context.Background())
|
2026-06-03 12:51:03 +00:00
|
|
|
|
runtime.MarkServerStarted()
|
2025-08-05 07:08:07 +00:00
|
|
|
|
|
|
|
|
|
|
// Build dependency injection container
|
|
|
|
|
|
c := container.BuildContainer(runtime.GetContainer())
|
|
|
|
|
|
|
2026-05-24 13:38:05 +00:00
|
|
|
|
// One-shot bootstrap hooks (e.g. promote env-named user to system
|
|
|
|
|
|
// admin). Best-effort: never aborts startup — see bootstrap.go.
|
|
|
|
|
|
runStartupBootstrap(c)
|
|
|
|
|
|
|
2025-08-05 07:08:07 +00:00
|
|
|
|
// Run application
|
|
|
|
|
|
err := c.Invoke(func(
|
|
|
|
|
|
cfg *config.Config,
|
|
|
|
|
|
router *gin.Engine,
|
|
|
|
|
|
resourceCleaner interfaces.ResourceCleaner,
|
2026-05-24 13:38:05 +00:00
|
|
|
|
systemSettingSvc interfaces.SystemSettingService,
|
feat(models): add system admin model catalog console (#3662)
* feat(models): add system admin model catalog console
System administrators can now maintain the model catalog from
Settings → System administration → Model catalog instead of editing
models.json on every replica. Administrator changes are stored as a
versioned overlay in the database (new model_catalog_config table),
layered between the deployment file and explicit per-model settings,
and synchronised to other instances within about 5 seconds.
Backend
- GET/POST preview/PUT /system/admin/model-catalog with optimistic
version + deployment baseline checks (409 on conflict), 20-version
history and audit logging.
- Console overlays reject credentials, headers, env interpolation and
non-inline icons; those stay deployment-owned.
- Catalog views include each chat model's resolved thinking levels and
the vendor defaults, so the console never re-implements level
inheritance.
Frontend
- Model list in the shared data-table style with provider/type filters,
"modified only" filter and source tags (built-in / deployment / admin).
- Edit drawer saves and applies immediately: display name, context
window, max output, input modalities, reasoning, thinking levels,
embedding dimension and picker visibility, each with its inherited
default and a layer comparison table.
- Add-model drawer, JSON editor with server-side change check before
publishing, and version history with one-step restore.
- Model settings gets a system-admin shortcut to the catalog; model
editor reloads providers when opened so published catalogs apply.
* fix(models): harden the admin model catalog console
- Reject console base_url, base_urls, url_patterns and auth: moving a
vendor's default URL would send its deployment api_key (and keys of rows
without their own base URL) to another host. With every interpolated
field now deployment-owned, '$' in names and descriptions is plain text.
- Drop deployment base URLs from catalog views; they may carry
interpolated tokens.
- Remember a stored version this replica cannot compile and skip it until
the version changes, instead of re-reading and recompiling every poll.
- Resolve vendor default thinking levels with reasoning forced on, like
per-model levels.
- Compute builtin/deployment views once; preview returns only the
candidate catalog and normalized overlay.
- Share deployment file lookup via runtime.ReadDeploymentOverlay.
- The model editor force-refreshes its own type instead of resetting the
provider store for every type; the refreshed list wins in the id index.
2026-09-24 08:31:45 +00:00
|
|
|
|
modelCatalogSvc *service.ModelCatalogService,
|
2025-08-05 07:08:07 +00:00
|
|
|
|
) error {
|
|
|
|
|
|
// Create HTTP server
|
|
|
|
|
|
server := &http.Server{
|
|
|
|
|
|
Handler: router,
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-03-23 07:14:18 +00:00
|
|
|
|
addr := fmt.Sprintf("%s:%d", cfg.Server.Host, cfg.Server.Port)
|
|
|
|
|
|
listener, err := listenWithRetry(addr, 10, 300*time.Millisecond)
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
return fmt.Errorf("failed to start server: %v", err)
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-08-05 07:08:07 +00:00
|
|
|
|
ctx, done := context.WithCancel(context.Background())
|
feat(models): add system admin model catalog console (#3662)
* feat(models): add system admin model catalog console
System administrators can now maintain the model catalog from
Settings → System administration → Model catalog instead of editing
models.json on every replica. Administrator changes are stored as a
versioned overlay in the database (new model_catalog_config table),
layered between the deployment file and explicit per-model settings,
and synchronised to other instances within about 5 seconds.
Backend
- GET/POST preview/PUT /system/admin/model-catalog with optimistic
version + deployment baseline checks (409 on conflict), 20-version
history and audit logging.
- Console overlays reject credentials, headers, env interpolation and
non-inline icons; those stay deployment-owned.
- Catalog views include each chat model's resolved thinking levels and
the vendor defaults, so the console never re-implements level
inheritance.
Frontend
- Model list in the shared data-table style with provider/type filters,
"modified only" filter and source tags (built-in / deployment / admin).
- Edit drawer saves and applies immediately: display name, context
window, max output, input modalities, reasoning, thinking levels,
embedding dimension and picker visibility, each with its inherited
default and a layer comparison table.
- Add-model drawer, JSON editor with server-side change check before
publishing, and version history with one-step restore.
- Model settings gets a system-admin shortcut to the catalog; model
editor reloads providers when opened so published catalogs apply.
* fix(models): harden the admin model catalog console
- Reject console base_url, base_urls, url_patterns and auth: moving a
vendor's default URL would send its deployment api_key (and keys of rows
without their own base URL) to another host. With every interpolated
field now deployment-owned, '$' in names and descriptions is plain text.
- Drop deployment base URLs from catalog views; they may carry
interpolated tokens.
- Remember a stored version this replica cannot compile and skip it until
the version changes, instead of re-reading and recompiling every poll.
- Resolve vendor default thinking levels with reasoning forced on, like
per-model levels.
- Compute builtin/deployment views once; preview returns only the
candidate catalog and normalized overlay.
- Share deployment file lookup via runtime.ReadDeploymentOverlay.
- The model editor force-refreshes its own type instead of resetting the
provider store for every type; the refreshed list wins in the id index.
2026-09-24 08:31:45 +00:00
|
|
|
|
modelCatalogSvc.Start(ctx)
|
2026-03-23 07:14:18 +00:00
|
|
|
|
|
2026-05-24 13:38:05 +00:00
|
|
|
|
// Start the system_settings pubsub subscriber. Runs in its own
|
|
|
|
|
|
// goroutine and exits when ctx is cancelled at shutdown. Best-
|
|
|
|
|
|
// effort: an error here only warns (Redis may legitimately be
|
|
|
|
|
|
// disabled in lite-mode deployments — the service no-ops in
|
|
|
|
|
|
// that case anyway).
|
|
|
|
|
|
if err := systemSettingSvc.SubscribeRedis(ctx); err != nil {
|
|
|
|
|
|
logger.Warnf(ctx, "[system_settings] subscribe failed: %v", err)
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-08-05 07:08:07 +00:00
|
|
|
|
signals := make(chan os.Signal, 1)
|
2026-04-10 22:13:16 +00:00
|
|
|
|
signal.Notify(signals, shutdownSignals...)
|
2025-08-05 07:08:07 +00:00
|
|
|
|
go func() {
|
|
|
|
|
|
sig := <-signals
|
2026-02-06 06:16:25 +00:00
|
|
|
|
logger.Infof(context.Background(), "Received signal: %v, starting server shutdown...", sig)
|
2025-08-05 07:08:07 +00:00
|
|
|
|
|
fix(server): run ResourceCleaner on signal shutdown instead of racing Fatalf exit (#3804)
* fix(server): signal shutdown raced Fatalf exit before ResourceCleaner ran
The signal goroutine closed the listener before calling server.Shutdown,
so Serve returned the raw accept error ('use of closed network connection')
instead of ErrServerClosed. The invoke error path then hit logger.Fatalf
(os.Exit(1)) in the same millisecond, killing the process before the
shutdown goroutine reached resourceCleaner.Cleanup. Every registered
cleaner — BrowserSkill daemon, sandbox reapers, IMService, AntsPool,
Langfuse — was skipped on every SIGTERM/SIGINT, leaking the shared bsk
daemon process and its temp home on each restart.
Two changes:
- Drop the manual listener.Close(): Shutdown closes all listeners as its
first step, releasing the port just as fast without racing Serve.
- Give resourceCleaner.Cleanup its own fresh timeout context so a slow
connection drain cannot leave Cleanup with an already-expired context,
which made it skip every entry without running any.
* fix(server): keep signal cleanup inside one grace period
Desktop quit still closed the listener before Shutdown and returned
before ResourceCleaner finished, so Fatalf could skip every hook.
Share ShutdownTimeout between drain and cleanup, run BrowserSkill
first, and do not drop later hooks when the deadline expires.
* fix(server): satisfy errcheck and line-length lint
---------
Co-authored-by: vicfei <vicfei@users.noreply.github.com>
Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-28 15:37:36 +00:00
|
|
|
|
drainBudget, cleanupBudget := runtime.ShutdownBudgets(cfg.Server.ShutdownTimeout)
|
|
|
|
|
|
shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), drainBudget)
|
2025-08-05 07:08:07 +00:00
|
|
|
|
defer shutdownCancel()
|
|
|
|
|
|
|
fix(server): run ResourceCleaner on signal shutdown instead of racing Fatalf exit (#3804)
* fix(server): signal shutdown raced Fatalf exit before ResourceCleaner ran
The signal goroutine closed the listener before calling server.Shutdown,
so Serve returned the raw accept error ('use of closed network connection')
instead of ErrServerClosed. The invoke error path then hit logger.Fatalf
(os.Exit(1)) in the same millisecond, killing the process before the
shutdown goroutine reached resourceCleaner.Cleanup. Every registered
cleaner — BrowserSkill daemon, sandbox reapers, IMService, AntsPool,
Langfuse — was skipped on every SIGTERM/SIGINT, leaking the shared bsk
daemon process and its temp home on each restart.
Two changes:
- Drop the manual listener.Close(): Shutdown closes all listeners as its
first step, releasing the port just as fast without racing Serve.
- Give resourceCleaner.Cleanup its own fresh timeout context so a slow
connection drain cannot leave Cleanup with an already-expired context,
which made it skip every entry without running any.
* fix(server): keep signal cleanup inside one grace period
Desktop quit still closed the listener before Shutdown and returned
before ResourceCleaner finished, so Fatalf could skip every hook.
Share ShutdownTimeout between drain and cleanup, run BrowserSkill
first, and do not drop later hooks when the deadline expires.
* fix(server): satisfy errcheck and line-length lint
---------
Co-authored-by: vicfei <vicfei@users.noreply.github.com>
Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-28 15:37:36 +00:00
|
|
|
|
// Second signal → force close all connections immediately.
|
2026-03-23 07:14:18 +00:00
|
|
|
|
go func() {
|
|
|
|
|
|
sig := <-signals
|
|
|
|
|
|
logger.Warnf(context.Background(), "Received second signal: %v, forcing shutdown...", sig)
|
|
|
|
|
|
server.Close()
|
|
|
|
|
|
}()
|
|
|
|
|
|
|
fix(server): run ResourceCleaner on signal shutdown instead of racing Fatalf exit (#3804)
* fix(server): signal shutdown raced Fatalf exit before ResourceCleaner ran
The signal goroutine closed the listener before calling server.Shutdown,
so Serve returned the raw accept error ('use of closed network connection')
instead of ErrServerClosed. The invoke error path then hit logger.Fatalf
(os.Exit(1)) in the same millisecond, killing the process before the
shutdown goroutine reached resourceCleaner.Cleanup. Every registered
cleaner — BrowserSkill daemon, sandbox reapers, IMService, AntsPool,
Langfuse — was skipped on every SIGTERM/SIGINT, leaking the shared bsk
daemon process and its temp home on each restart.
Two changes:
- Drop the manual listener.Close(): Shutdown closes all listeners as its
first step, releasing the port just as fast without racing Serve.
- Give resourceCleaner.Cleanup its own fresh timeout context so a slow
connection drain cannot leave Cleanup with an already-expired context,
which made it skip every entry without running any.
* fix(server): keep signal cleanup inside one grace period
Desktop quit still closed the listener before Shutdown and returned
before ResourceCleaner finished, so Fatalf could skip every hook.
Share ShutdownTimeout between drain and cleanup, run BrowserSkill
first, and do not drop later hooks when the deadline expires.
* fix(server): satisfy errcheck and line-length lint
---------
Co-authored-by: vicfei <vicfei@users.noreply.github.com>
Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-28 15:37:36 +00:00
|
|
|
|
// Do NOT close the listener manually before Shutdown. Serve would
|
|
|
|
|
|
// return the raw accept error ("use of closed network connection")
|
|
|
|
|
|
// instead of ErrServerClosed, and logger.Fatalf → os.Exit(1) would
|
|
|
|
|
|
// kill the process before ResourceCleaner runs. Shutdown closes
|
|
|
|
|
|
// listeners first, so the port is released before the drain.
|
2025-08-05 07:08:07 +00:00
|
|
|
|
if err := server.Shutdown(shutdownCtx); err != nil {
|
2026-03-23 07:14:18 +00:00
|
|
|
|
logger.Errorf(context.Background(), "Server forced to shutdown: %v", err)
|
|
|
|
|
|
server.Close()
|
2025-08-05 07:08:07 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
2026-02-06 06:16:25 +00:00
|
|
|
|
logger.Info(context.Background(), "Cleaning up resources...")
|
fix(server): run ResourceCleaner on signal shutdown instead of racing Fatalf exit (#3804)
* fix(server): signal shutdown raced Fatalf exit before ResourceCleaner ran
The signal goroutine closed the listener before calling server.Shutdown,
so Serve returned the raw accept error ('use of closed network connection')
instead of ErrServerClosed. The invoke error path then hit logger.Fatalf
(os.Exit(1)) in the same millisecond, killing the process before the
shutdown goroutine reached resourceCleaner.Cleanup. Every registered
cleaner — BrowserSkill daemon, sandbox reapers, IMService, AntsPool,
Langfuse — was skipped on every SIGTERM/SIGINT, leaking the shared bsk
daemon process and its temp home on each restart.
Two changes:
- Drop the manual listener.Close(): Shutdown closes all listeners as its
first step, releasing the port just as fast without racing Serve.
- Give resourceCleaner.Cleanup its own fresh timeout context so a slow
connection drain cannot leave Cleanup with an already-expired context,
which made it skip every entry without running any.
* fix(server): keep signal cleanup inside one grace period
Desktop quit still closed the listener before Shutdown and returned
before ResourceCleaner finished, so Fatalf could skip every hook.
Share ShutdownTimeout between drain and cleanup, run BrowserSkill
first, and do not drop later hooks when the deadline expires.
* fix(server): satisfy errcheck and line-length lint
---------
Co-authored-by: vicfei <vicfei@users.noreply.github.com>
Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-28 15:37:36 +00:00
|
|
|
|
// Fresh context sized from the reserved slice of ShutdownTimeout.
|
|
|
|
|
|
// Drain must not hand cleanup an already-expired context, and the
|
|
|
|
|
|
// two slices must still add up to one supervisor grace period.
|
|
|
|
|
|
cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), cleanupBudget)
|
|
|
|
|
|
defer cleanupCancel()
|
|
|
|
|
|
errs := resourceCleaner.Cleanup(cleanupCtx)
|
2025-08-05 07:08:07 +00:00
|
|
|
|
if len(errs) > 0 {
|
2026-02-06 06:16:25 +00:00
|
|
|
|
logger.Errorf(context.Background(), "Errors occurred during resource cleanup: %v", errs)
|
2025-08-05 07:08:07 +00:00
|
|
|
|
}
|
2026-02-06 06:16:25 +00:00
|
|
|
|
logger.Info(context.Background(), "Server has exited")
|
2025-08-05 07:08:07 +00:00
|
|
|
|
done()
|
|
|
|
|
|
}()
|
|
|
|
|
|
|
2026-05-17 06:42:24 +00:00
|
|
|
|
runtime.LogGinRouteCount(context.Background())
|
2026-03-22 17:35:09 +00:00
|
|
|
|
logger.Infof(context.Background(), "Server is running at %s", addr)
|
|
|
|
|
|
if err := server.Serve(listener); err != nil && err != http.ErrServerClosed {
|
|
|
|
|
|
return fmt.Errorf("server error: %v", err)
|
|
|
|
|
|
}
|
2025-08-05 07:08:07 +00:00
|
|
|
|
|
|
|
|
|
|
<-ctx.Done()
|
|
|
|
|
|
return nil
|
|
|
|
|
|
})
|
|
|
|
|
|
if err != nil {
|
2026-02-06 06:16:25 +00:00
|
|
|
|
logger.Fatalf(context.Background(), "Failed to run application: %v", err)
|
2025-08-05 07:08:07 +00:00
|
|
|
|
}
|
|
|
|
|
|
}
|