chore: 初始化仓库,导入项目基线代码
Academy v0.8.3 完整代码基线:Go 后端(internal/cmd/cli/mcp-server/docreader)、 Vue 前端(frontend)、数据库迁移(migrations)、部署编排(docker/helm/deploy)与文档。 今日开发的培训推送管理改动随后单独提交。
This commit is contained in:
commit
7ec21f35b0
5767 files changed
+1436788
No files matched your search
@@ -0,0 +1,23 @@
|
||||
// Package runtime 提供应用程序运行时的依赖注入容器
|
||||
// 该包使用 uber 的 dig 库来管理依赖项注入
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"go.uber.org/dig"
|
||||
)
|
||||
|
||||
// container 是应用程序的全局依赖注入容器
|
||||
// 所有服务和组件都通过它进行注册和解析
|
||||
var container *dig.Container
|
||||
|
||||
// init 初始化依赖注入容器
|
||||
// 在程序启动时自动调用
|
||||
func init() {
|
||||
container = dig.New()
|
||||
}
|
||||
|
||||
// GetContainer 返回全局依赖注入容器的引用
|
||||
// 供其他包使用以注册或获取服务
|
||||
func GetContainer() *dig.Container {
|
||||
return container
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package runtime
|
||||
|
||||
import "time"
|
||||
|
||||
// serverStartedAt is set once at process boot (see MarkServerStarted).
|
||||
var serverStartedAt time.Time
|
||||
|
||||
// MarkServerStarted records the instant the Academy server process started.
|
||||
// Call once from main() before heavy init so uptime reflects the full process
|
||||
// lifetime, not merely when the HTTP listener binds.
|
||||
func MarkServerStarted() {
|
||||
serverStartedAt = time.Now().UTC()
|
||||
}
|
||||
|
||||
// ServerStartedAt returns the boot instant in UTC. Zero when MarkServerStarted
|
||||
// was not called (e.g. some tests); callers should treat zero as unknown.
|
||||
func ServerStartedAt() time.Time {
|
||||
return serverStartedAt
|
||||
}
|
||||
|
||||
// ServerUptime returns elapsed time since MarkServerStarted. Zero when unset.
|
||||
func ServerUptime() time.Duration {
|
||||
if serverStartedAt.IsZero() {
|
||||
return 0
|
||||
}
|
||||
return time.Since(serverStartedAt)
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestMarkServerStartedAndUptime(t *testing.T) {
|
||||
MarkServerStarted()
|
||||
boot := ServerStartedAt()
|
||||
if boot.IsZero() {
|
||||
t.Fatal("ServerStartedAt should be set after MarkServerStarted")
|
||||
}
|
||||
time.Sleep(2 * time.Millisecond)
|
||||
if got := ServerUptime(); got <= 0 {
|
||||
t.Fatalf("ServerUptime() = %v, want > 0", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package runtime
|
||||
|
||||
import "time"
|
||||
|
||||
// DefaultShutdownTimeout is used when server.shutdown_timeout is unset.
|
||||
const DefaultShutdownTimeout = 30 * time.Second
|
||||
|
||||
// CleanupBudget is reserved from the configured shutdown timeout so connection
|
||||
// drain cannot consume the whole grace period before process cleanup runs.
|
||||
// Supervisors often use the same number for termination grace (Kubernetes
|
||||
// defaults to 30s), so drain and cleanup share one budget instead of stacking.
|
||||
const CleanupBudget = 5 * time.Second
|
||||
|
||||
// ShutdownBudgets splits total into an HTTP drain budget and a cleanup budget.
|
||||
// Their sum equals total. total <= 0 uses DefaultShutdownTimeout. When total
|
||||
// is too small to reserve CleanupBudget, the two halves are equal.
|
||||
func ShutdownBudgets(total time.Duration) (drain, cleanup time.Duration) {
|
||||
if total <= 0 {
|
||||
total = DefaultShutdownTimeout
|
||||
}
|
||||
cleanup = CleanupBudget
|
||||
if cleanup >= total {
|
||||
cleanup = total / 2
|
||||
if cleanup <= 0 {
|
||||
cleanup = total
|
||||
}
|
||||
}
|
||||
drain = total - cleanup
|
||||
if drain <= 0 {
|
||||
drain = total
|
||||
}
|
||||
return drain, cleanup
|
||||
}
|
||||
|
||||
// WaitFor reports whether ch was received before timeout. timeout <= 0 waits
|
||||
// until ch is received. The boolean is false only when the timeout wins.
|
||||
func WaitFor(ch <-chan struct{}, timeout time.Duration) bool {
|
||||
if timeout <= 0 {
|
||||
<-ch
|
||||
return true
|
||||
}
|
||||
timer := time.NewTimer(timeout)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case <-ch:
|
||||
return true
|
||||
case <-timer.C:
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestShutdownBudgetsShareOneDeadline(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
total time.Duration
|
||||
wantDrain time.Duration
|
||||
wantCleanup time.Duration
|
||||
}{
|
||||
{name: "unset", total: 0, wantDrain: 25 * time.Second, wantCleanup: 5 * time.Second},
|
||||
{name: "default", total: 30 * time.Second, wantDrain: 25 * time.Second, wantCleanup: 5 * time.Second},
|
||||
{name: "fits reserve", total: 10 * time.Second, wantDrain: 5 * time.Second, wantCleanup: 5 * time.Second},
|
||||
{name: "split small", total: 4 * time.Second, wantDrain: 2 * time.Second, wantCleanup: 2 * time.Second},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
drain, cleanup := ShutdownBudgets(tt.total)
|
||||
if drain != tt.wantDrain || cleanup != tt.wantCleanup {
|
||||
t.Fatalf("ShutdownBudgets(%s) = %s drain + %s cleanup, want %s + %s",
|
||||
tt.total, drain, cleanup, tt.wantDrain, tt.wantCleanup)
|
||||
}
|
||||
total := tt.total
|
||||
if total <= 0 {
|
||||
total = DefaultShutdownTimeout
|
||||
}
|
||||
if drain+cleanup != total {
|
||||
t.Fatalf("budgets sum to %s, want %s", drain+cleanup, total)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestWaitFor(t *testing.T) {
|
||||
closed := make(chan struct{})
|
||||
close(closed)
|
||||
if !WaitFor(closed, time.Millisecond) {
|
||||
t.Fatal("closed channel should be received")
|
||||
}
|
||||
|
||||
never := make(chan struct{})
|
||||
start := time.Now()
|
||||
if WaitFor(never, 20*time.Millisecond) {
|
||||
t.Fatal("timeout should lose")
|
||||
}
|
||||
if elapsed := time.Since(start); elapsed > 500*time.Millisecond {
|
||||
t.Fatalf("timeout waited %s", elapsed)
|
||||
}
|
||||
|
||||
later := make(chan struct{})
|
||||
go func() {
|
||||
time.Sleep(15 * time.Millisecond)
|
||||
close(later)
|
||||
}()
|
||||
if !WaitFor(later, 0) {
|
||||
t.Fatal("non-positive timeout should wait for the channel")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"academy/internal/logger"
|
||||
"academy/internal/utils"
|
||||
)
|
||||
|
||||
// SilenceGinRouteSpam mutes Gin's per-route "[GIN-debug] METHOD path -->
|
||||
// handler" lines that flood the startup log with one entry per registered
|
||||
// route (we have ~150 of them). DebugMode features (panic recovery
|
||||
// stacktraces, runtime warnings) are preserved.
|
||||
//
|
||||
// In place of the per-route spam, prints a single summary line at the
|
||||
// end of router build with the route count.
|
||||
//
|
||||
// Call once at the start of main(), before container.BuildContainer.
|
||||
func SilenceGinRouteSpam() {
|
||||
var count int64
|
||||
gin.DebugPrintRouteFunc = func(httpMethod, absolutePath, handlerName string, nuHandlers int) {
|
||||
atomic.AddInt64(&count, 1)
|
||||
}
|
||||
// gin.DebugPrintFunc handles non-route debug lines (e.g. "Listening
|
||||
// and serving HTTP"). Route them through the structured logger so
|
||||
// they share the same format as the rest of startup.
|
||||
gin.DebugPrintFunc = func(format string, values ...interface{}) {
|
||||
msg := strings.TrimRight(fmt.Sprintf(format, values...), "\n")
|
||||
// Drop the redundant "Creating an Engine instance with the Logger
|
||||
// and Recovery middleware already attached" — purely informational.
|
||||
if strings.Contains(msg, "Creating an Engine instance") {
|
||||
return
|
||||
}
|
||||
logger.Info(context.Background(), "[gin] "+msg)
|
||||
}
|
||||
// Expose a way to print the suppressed count once routes are wired up.
|
||||
ginRouteCount = &count
|
||||
}
|
||||
|
||||
// ginRouteCount is set by SilenceGinRouteSpam and read by LogGinRouteCount
|
||||
// so callers can print a one-line summary after router build.
|
||||
var ginRouteCount *int64
|
||||
|
||||
// LogGinRouteCount writes a single summary line for the number of routes
|
||||
// Gin registered. Safe to call even if SilenceGinRouteSpam wasn't called
|
||||
// (it just becomes a no-op).
|
||||
func LogGinRouteCount(ctx context.Context) {
|
||||
if ginRouteCount == nil {
|
||||
return
|
||||
}
|
||||
logger.Infof(ctx, "[gin] registered %d routes", atomic.LoadInt64(ginRouteCount))
|
||||
}
|
||||
|
||||
// envVarSpec describes one env var to surface in the startup banner.
|
||||
type envVarSpec struct {
|
||||
name string
|
||||
sensitive bool // if true, only presence/length is printed, never value
|
||||
}
|
||||
|
||||
// startupEnvVars lists the env vars whose presence is most worth
|
||||
// surfacing at boot — primarily security-sensitive ones whose silent
|
||||
// absence has caused real incidents (SYSTEM_AES_KEY rotation, JWT secret
|
||||
// drift) plus the basic DB / storage selectors that change behaviour
|
||||
// significantly.
|
||||
//
|
||||
// Keep the list short — this banner exists to answer "is the config I
|
||||
// expect actually loaded?" at a glance, not to dump the entire env.
|
||||
var startupEnvVars = []envVarSpec{
|
||||
// Security
|
||||
{name: "SYSTEM_AES_KEY", sensitive: true},
|
||||
{name: "SYSTEM_SIGNING_KEY", sensitive: true},
|
||||
{name: "JWT_SECRET", sensitive: true},
|
||||
// Runtime
|
||||
{name: "GIN_MODE"},
|
||||
{name: "AUTO_MIGRATE"},
|
||||
// Database
|
||||
{name: "DB_DRIVER"},
|
||||
{name: "DB_HOST"},
|
||||
{name: "DB_PORT"},
|
||||
{name: "DB_USER"},
|
||||
{name: "DB_NAME"},
|
||||
{name: "DB_PATH"}, // sqlite
|
||||
{name: "DB_PASSWORD", sensitive: true},
|
||||
// Cache / queue
|
||||
{name: "REDIS_ADDR"},
|
||||
{name: "REDIS_PASSWORD", sensitive: true},
|
||||
{name: "REDIS_USE_TLS"},
|
||||
{name: "REDIS_TLS_SERVER_NAME"},
|
||||
// Object storage
|
||||
{name: "STORAGE_TYPE"},
|
||||
{name: "MINIO_ENDPOINT"},
|
||||
{name: "MINIO_BUCKET_NAME"},
|
||||
{name: "MINIO_SECRET_ACCESS_KEY", sensitive: true},
|
||||
{name: "TOS_ENDPOINT"},
|
||||
{name: "TOS_BUCKET_NAME"},
|
||||
{name: "TOS_SECRET_KEY", sensitive: true},
|
||||
// External services
|
||||
{name: "DOCREADER_ADDR"},
|
||||
{name: "RETRIEVE_DRIVER"},
|
||||
}
|
||||
|
||||
// LogStartupEnv prints a single banner block summarising the curated set
|
||||
// of env vars in startupEnvVars. Sensitive values are reported as
|
||||
// "set (N chars)" — the goal is to give the operator confidence the
|
||||
// config they expected actually landed, without echoing secrets to logs.
|
||||
//
|
||||
// Output format (one line per var to stay grep-able):
|
||||
//
|
||||
// [startup-env] SYSTEM_AES_KEY=set (32 chars)
|
||||
// [startup-env] JWT_SECRET=<unset>
|
||||
// [startup-env] DB_DRIVER=postgres
|
||||
//
|
||||
// Special call-outs are printed afterwards for misconfigurations that
|
||||
// would silently degrade behaviour (e.g. SYSTEM_AES_KEY set but wrong
|
||||
// length is treated as unset by crypto.GetAESKey — easy to miss without
|
||||
// a loud warning).
|
||||
func LogStartupEnv(ctx context.Context) {
|
||||
// Sort by name for deterministic output.
|
||||
specs := make([]envVarSpec, len(startupEnvVars))
|
||||
copy(specs, startupEnvVars)
|
||||
sort.Slice(specs, func(i, j int) bool { return specs[i].name < specs[j].name })
|
||||
|
||||
logger.Info(ctx, "[startup-env] resolved environment:")
|
||||
for _, s := range specs {
|
||||
val := os.Getenv(s.name)
|
||||
logger.Infof(ctx, "[startup-env] %s=%s", s.name, formatEnvValue(s, val))
|
||||
}
|
||||
|
||||
// Targeted warnings for footguns. SYSTEM_AES_KEY set to wrong length
|
||||
// is the most common one — utils.GetAESKey() silently falls back to
|
||||
// nil (== "no encryption") when len != 32.
|
||||
if k := os.Getenv("SYSTEM_AES_KEY"); k != "" && len(k) != 32 {
|
||||
logger.Warnf(ctx,
|
||||
"[startup-env] SYSTEM_AES_KEY is set but %d bytes long; AES-256 requires exactly 32 bytes — encryption is DISABLED",
|
||||
len(k))
|
||||
}
|
||||
// Upgrades from example configs keep the published example AES key,
|
||||
// which SystemHMACKey rejects — embed sessions and presigned links then
|
||||
// fail at request time with no hint at boot.
|
||||
if len(utils.SystemHMACKey()) == 0 {
|
||||
logger.Warn(ctx,
|
||||
"[startup-env] no usable signing key: set SYSTEM_SIGNING_KEY (e.g. `openssl rand -hex 32`) — "+
|
||||
"embed sessions and presigned file links are DISABLED. SYSTEM_AES_KEY is only used as a fallback "+
|
||||
"when it is at least 16 chars and not an example value; do not change it to fix this")
|
||||
}
|
||||
if strings.EqualFold(strings.TrimSpace(os.Getenv("REDIS_TLS_INSECURE_SKIP_VERIFY")), "true") {
|
||||
logger.Warn(ctx,
|
||||
"[startup-env] REDIS_TLS_INSECURE_SKIP_VERIFY=true — Redis TLS certificate verification is DISABLED; do not use in production")
|
||||
}
|
||||
}
|
||||
|
||||
func formatEnvValue(s envVarSpec, val string) string {
|
||||
if val == "" {
|
||||
return "<unset>"
|
||||
}
|
||||
if s.sensitive {
|
||||
return fmt.Sprintf("set (%d chars)", len(val))
|
||||
}
|
||||
return val
|
||||
}
|
||||
Reference in new issue
Block a user