mirror of
https://github.com/Rain-kl/OpenFlare.git
synced 2026-10-01 06:36:38 +08:00
dbaa3bf140
docs(changelog): 修正表述笔误
refactor(cordis): 磁盘缓存改用上上游能力并清理本地副本
按上游/下游归属规约:类型断言守卫已回流 Wavelet(f3d85d5,附回归用例),
本仓库删除 OpenFlare/plugins/server/pkg/cache 整包并改 import 到
Wavelet/pkg/cache/disk,同步后与上游零漂移。
验证:go build 通过;go test ./... exit 0(137 包 ok);256 条路由对拍与
232 条 swagger 操作均零差异;make build-all 四进制;前端零改动。
docs(cordis): 记录 T1 清理结果与五个复用阻塞点
refactor(cordis): server 复用上游 pkg 能力并删除等价本地副本
按上游/下游归属规约清理重复实现,删除 7 个与上游等价的本地包并改 import:
shared/response→pkg/response、pkg/{logger,mail,trace,httppool,cache/ram}→
上游同名包、infra/persistence/batchwriter→pkg/batchwriter。逐项核过差异:
httppool 逐字节相同;logger 的 Config 字段完全一致;response 的 7 个 Abort*
一致;cache/ram 换过去顺带把裸 go 变回带 panic 恢复的 util.Go。
两处非等价差异按语义处理:
- batchwriter.Stats 与 status DTO 原为类型别名,改为消费侧逐字段转换,
避免 model 反向依赖基础设施类型;
- 上游 pkg/idgen 要求显式 Init(本地副本为懒加载自动初始化),本次保留本地
副本,待与 infra 初始化一并迁移(已登记在清理计划)。
验证:go build 通过;go test ./... exit 0(138 包 ok);256 条路由对拍零差异;
make swagger 232 条操作零增减,且归一化后与旧文档深度相等——差异仅为
response.Any / logger.LogEntry 两个定义名随包路径改名,接口形状未变。
chore(cordis): 回流内核与 pkg/util 通用能力并清理 vendoring 污染
按新增的上游/下游归属规约:HandleRaw/BasePath 与版本比较、网络、格式化助手
属通用能力,已提交到 Wavelet 分支 feat/cordis-router-raw-routes,本仓库改为
纯同步获取(pkg/util 已零漂移),补丁登记保留至上游合并。
同时修掉我此前 git add -A 造成的污染:首次 vendoring 把上游工作区里被
gitignore 的运行期产物一起提交进来(upload 的 diskcache 缓存块 650 个与
driver_http/dist 前端构建物 380 个,共 12872 行/1030 文件)。sync-upstream.sh
现显式排除 uploads/dist/data/*.db,.gitignore 补上对应兜底规则。
AGENTS.md 增加上游/下游改动归属规约,并把仍指向前 Cordis 布局的硬性约束
(internal/router + Serve、internal/repository/logstore、internal/platform/bootstrap、
internal/cmd)改到当前插件路径。
验证:go build 通过;go test ./... exit 0(144 包 ok);make swagger 232 条
操作与基线逐条一致;make build-all 四进制;gofmt 干净。
feat(cordis): server 插件化并改由内核挂载控制面路由
新增 plugins/server/plugin.go:Apply 以 ctx.Router().Group(app.api_prefix)
声明根级与 /v1 全部路由;33 个注册函数由 *gin.RouterGroup 改为
core.RouterExtension,RegisterCollection 改用内核新增的 HandleRaw 保留
尾部斜杠变体,AdminMiddlewares 返回 []any(Go 不允许把 []T 展开为 ...any)。
删除 router.Serve 与 registerRoutes,装配根改为 core.App +
driver_http.New(WithEngine(router.BuildEngine())),监听、信号与优雅退出归内核;
前端 SPA 的 NoRoute 兜底因内核暂无贡献点而保留在引擎层。
路由保真证据:plugin_parity_test 对拍 baseline/routes-engine.txt 的 256 条
(方法 路径) 零差异;go test ./... exit 0(144 包 ok,含真实 handler 的
openflare/integration 用例走同一条挂载路径);make swagger 232 条操作与基线
逐条一致;golangci-lint 0 issues;make build-all 四进制;embed_frontend
标签编译通过;前端零改动。
已知待补:带 Redis 的实机 HTTP 冒烟(本机 6379 未启动,session store 与
改造前一样在建店阶段即 fatal),以及 bootstrap 的任务/设置/迁移注册迁入 Apply。
feat(core): RouterExtension 增加 HandleRaw 与 BasePath 以保真尾部斜杠路由
server 插件化的前置:Handle 经 cleanPath 会剥掉尾部斜杠,无法表达
/resource 与 /resource/ 两条不同路由,而 OpenFlare 有 20 个历史 list
端点两者都注册且部署关闭了 RedirectTrailingSlash,缺失即 404。新增
HandleRaw 与 BasePath(作用域包装器同样登记反注册),补 extpoints 用例;
并把 router.Serve 拆出 BuildEngine 以便交给 driver_http.WithEngine 复用,
新增路由表导出 harness,固化 256 条 (方法 路径) 基线供插件化对拍。
上游补丁登记于 backend/OpenFlare/upstream-patches.md,同步脚本改为按目录
前缀输出差异并在同步后提醒确认补丁是否仍在。
验证:go build 通过;go test ./... exit 0(143 包 ok);gofmt 干净。
docs(cordis): 记录 server 插件接入内核的可行路径与内核能力缺口
feat(cordis): agent/relay/flared 落地为内核驱动插件
三个边缘守护进程各新增 plugin.go,实现 core.Plugin + core.Driver
(自定义 DriverType 与同名 profile),装配与生命周期从 main 迁入
Apply/Start/Stop:Apply 负责 JSON 配置加载、运行环境与用户确保、
openresty/frps/frpc 管理器与各服务装配;Start 以 util.Go 拉起阻塞式
runner 与 GeoIP 周期更新;Stop 收敛主循环结果并在超时时报错而非静默。
入口改为 core.NewApp(core.WithProfile(...)) + Prepare/Run,保持
-config 旗标、默认路径、退出码与启动/停止日志不变。
验证:go build 通过;go test ./... exit 0(143 包 ok,含 3 个插件身份
与配置失败路径测试);make build-all 四进制产出;三进制实跑缺失配置
均 exit 1 且错误链保留 load {agent,relay,flared} config 原因;gofmt 干净。
refactor(cordis): 按功能职责拆分为 4 个插件与 share 共享层
backend/OpenFlare 不再平铺遗留分层,改为 plugins/{server,agent,relay,flared}
加 share/:控制面业务(openflare/admin/oauth/user/upload/cap/config/health 与
repository/model/infra/router 等支撑层)归 server;三个边缘守护进程各自成插件;
被两个以上插件消费的 protocol/geoip/wsclient/render/pagesarchive/edge 归 share。
同时把 pkg/util 与 buildinfo 合并回上游 pkg(上游已覆盖全部符号,仅 8 个函数与
2 个类型为 OpenFlare 独有,已一并迁入),装配根统一到 backend/cmd(含三个 daemon
入口),Dockerfile 与 release 工作流的构建路径和 -X 注入路径同步更新。
验证:go build 通过;go test ./... exit 0(141 包 ok);make swagger exit 0 且
232 条 API 操作与基线逐条一致;make build-all 产出 4 进制;-X 注入经二进制
strings 实测生效;日志后端直连门禁改写为按 server 插件业务域扫描并在扫描数为 0
时报错(防门禁静默失效);前端零改动。
feat(cordis): 落地 backend/share 共享层与上游同步脚本
跨插件共享资源(控制消息协议、GeoIP+iputil、边缘守护进程日志)从下游包
移入 backend/share,并声明其只能依赖 core/pkg 与标准/第三方库,禁止反向
引用下游业务与具体插件实现;新增 scripts/sync-upstream.sh 只覆盖
backend/{core,pkg,plugins},同步后 --check 报告零差异,证明与上游逐字一致。
go build 通过,go test ./... exit 0(142 包 ok),前端零改动。
refactor(cordis): 采用与 Wavelet 同构的单模块布局并引入上游内核
按上游结构落位:backend/{core,pkg,plugins} 为 Wavelet 上游拷贝,OpenFlare
全部业务收拢到上游 downstream 所对应的位置 backend/OpenFlare/,模块名保持
Wavelet 以保证上游 import 路径逐字一致、同步零改写;三个 daemon 入口移至
backend/OpenFlare/cmd,backend/cmd 与 main.go 作为控制面装配根。
行为不变:go build 通过,142 个测试包全绿(含上游插件测试),232 条 API
操作与改造前逐条一致,四进制产物正常,前端零改动。swagger 暂只扫描下游代码,
待 P4 挂载上游路由后再纳入 plugins/。
style: 修正模块路径改写导致的 import 分组排序漂移
refactor(layout): Go 代码迁入 backend/ 并将模块名简化为 OpenFlare
对齐上游 Wavelet 的仓库布局,为以第二 module 形态 vendoring Cordis 内核与
平台插件做准备:模块路径整体改写为 OpenFlare,Go 目标加 cd backend,
swaggo 产物移至 backend/docs 并把 json/yaml 复制回 docs/ 供站点消费,
Dockerfile 与 release 工作流的构建目录、ldflags 模块路径同步更新。
行为保持不变:232 条路由与改造前逐条一致,95 个测试包全绿,
四进制产物正常,前端零改动。
chore(cordis): 落地改造计划与 schema/路由基线
新增 legacy_dump_test 迁移快照 harness:在临时 sqlite 库上按生产顺序
(goose.UpTo → zone 导入 → goose.Up)跑完 76 个历史迁移并导出 schema 与
版本序列,作为改造前后一致性门禁的唯一事实来源。同时记录 232 条路由清单
与 foundation 实施计划。
docs(cordis): add OpenFlare Cordis 架构改造设计
明确上游以第二 module 形态 vendoring 进 backend/Wavelet、4 个插件
(server/agent/relay/flared) 全部装载内核,并规定保留 76 个历史 goose
迁移 + 一次性版本 stamp 桥接的迁移方案,配套三方 schema 一致性门禁,
确保已部署库不重跑历史、不丢数据。
698 lines
17 KiB
Go
698 lines
17 KiB
Go
// Copyright 2026 Arctel.net
|
|
// SPDX-License-Identifier: Apache-2.0
|
|
|
|
package core
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"os"
|
|
"os/signal"
|
|
"strings"
|
|
"sync"
|
|
"syscall"
|
|
"time"
|
|
)
|
|
|
|
const (
|
|
defaultShutdownTimeout = 10 * time.Second
|
|
)
|
|
|
|
// AppOption configures an App instance during construction.
|
|
type AppOption func(*App)
|
|
|
|
// WithContext sets a custom root Context for the App.
|
|
func WithContext(ctx *Context) AppOption {
|
|
return func(a *App) {
|
|
if ctx != nil {
|
|
a.ctx = ctx
|
|
}
|
|
}
|
|
}
|
|
|
|
// WithProfile sets the runtime profile for the App.
|
|
func WithProfile(profile Profile) AppOption {
|
|
return func(a *App) {
|
|
a.profile = normalizeProfile(profile)
|
|
}
|
|
}
|
|
|
|
// WithPlugins registers initial plugins for the App.
|
|
func WithPlugins(plugins ...Plugin) AppOption {
|
|
return func(a *App) {
|
|
a.Use(plugins...)
|
|
}
|
|
}
|
|
|
|
// WithMigrationEngine sets the database migration engine for the App.
|
|
func WithMigrationEngine(engine MigrationEngine) AppOption {
|
|
return func(a *App) {
|
|
a.migrationEngine = engine
|
|
}
|
|
}
|
|
|
|
// WithMigrationRunner sets the migration runner function for the App.
|
|
func WithMigrationRunner(runner MigrationRunner) AppOption {
|
|
return func(a *App) {
|
|
a.migrationEngine = runner
|
|
}
|
|
}
|
|
|
|
// WithShutdownTimeout sets the fallback timeout for graceful application shutdown.
|
|
func WithShutdownTimeout(timeout time.Duration) AppOption {
|
|
return func(a *App) {
|
|
if timeout > 0 {
|
|
a.shutdownTimeout = timeout
|
|
}
|
|
}
|
|
}
|
|
|
|
// WithConfigSource installs the raw configuration source adapter, typically built by an
|
|
// infrastructure package outside the kernel, before any plugin is applied.
|
|
func WithConfigSource(src ConfigSource) AppOption {
|
|
return func(a *App) {
|
|
if src == nil {
|
|
return
|
|
}
|
|
// Installed during Prepare so the option order, including WithContext, is irrelevant.
|
|
a.configSource = src
|
|
}
|
|
}
|
|
|
|
// WithConfigDecl lets the composition root declare the configuration it reads itself,
|
|
// so host-level values take part in conflict validation and the redacted report. The
|
|
// bindings are registered during Prepare, so option order does not matter.
|
|
func WithConfigDecl(pluginID string, bindings ...ConfigBinding) AppOption {
|
|
return func(a *App) {
|
|
if len(bindings) == 0 {
|
|
return
|
|
}
|
|
if a.hostDeclOwner == "" {
|
|
a.hostDeclOwner = pluginID
|
|
}
|
|
a.hostDeclBindings = append(a.hostDeclBindings, bindings...)
|
|
}
|
|
}
|
|
|
|
// App is the unified assembly entrypoint and runtime aspect dispatcher of the Cordis micro-kernel.
|
|
// It manages plugin collection, dependency mounting, migration execution, profile-based driver startup,
|
|
// and graceful signal-driven LIFO shutdown.
|
|
type App struct {
|
|
mu sync.RWMutex
|
|
ctx *Context
|
|
profile Profile
|
|
plugins []Plugin
|
|
pluginMap map[string]Plugin
|
|
fibers []*Fiber
|
|
fiberMap map[string]*Fiber
|
|
applied bool
|
|
running bool
|
|
startedDrivers []Driver
|
|
migrationEngine MigrationEngine
|
|
shutdownTimeout time.Duration
|
|
configSource ConfigSource
|
|
hostDeclOwner string
|
|
hostDeclBindings []ConfigBinding
|
|
prepared bool
|
|
applyErr error
|
|
}
|
|
|
|
// NewApp creates a new Cordis application instance with default options.
|
|
func NewApp(opts ...AppOption) *App {
|
|
app := &App{
|
|
ctx: NewContext(context.Background()),
|
|
profile: ProfileAll,
|
|
pluginMap: make(map[string]Plugin),
|
|
fiberMap: make(map[string]*Fiber),
|
|
shutdownTimeout: defaultShutdownTimeout,
|
|
}
|
|
|
|
for _, opt := range opts {
|
|
if opt != nil {
|
|
opt(app)
|
|
}
|
|
}
|
|
|
|
return app
|
|
}
|
|
|
|
// Context returns the root micro-kernel Context of the application.
|
|
func (a *App) Context() *Context {
|
|
return a.ctx
|
|
}
|
|
|
|
// Profile returns the current runtime profile of the application.
|
|
func (a *App) Profile() Profile {
|
|
a.mu.RLock()
|
|
defer a.mu.RUnlock()
|
|
return a.profile
|
|
}
|
|
|
|
// WithProfile sets the application runtime profile and returns the App for fluent chaining.
|
|
func (a *App) WithProfile(profile Profile) *App {
|
|
a.mu.Lock()
|
|
defer a.mu.Unlock()
|
|
a.profile = normalizeProfile(profile)
|
|
return a
|
|
}
|
|
|
|
// SetProfile sets the application runtime profile.
|
|
func (a *App) SetProfile(profile Profile) *App {
|
|
return a.WithProfile(profile)
|
|
}
|
|
|
|
// Use registers one or more plugins into the application in registration order.
|
|
// Duplicate plugins (by Name) update existing registrations in-place to preserve order.
|
|
func (a *App) Use(plugins ...Plugin) *App {
|
|
a.mu.Lock()
|
|
defer a.mu.Unlock()
|
|
|
|
for _, p := range plugins {
|
|
if p == nil {
|
|
continue
|
|
}
|
|
name := p.Name()
|
|
if name == "" {
|
|
continue
|
|
}
|
|
|
|
if _, exists := a.pluginMap[name]; exists {
|
|
for i, existing := range a.plugins {
|
|
if existing.Name() == name {
|
|
a.plugins[i] = p
|
|
break
|
|
}
|
|
}
|
|
if existingFiber, ok := a.fiberMap[name]; ok {
|
|
existingFiber.plugin = p
|
|
}
|
|
} else {
|
|
a.plugins = append(a.plugins, p)
|
|
f := NewFiber(a.ctx, p)
|
|
a.fibers = append(a.fibers, f)
|
|
a.fiberMap[name] = f
|
|
}
|
|
a.pluginMap[name] = p
|
|
|
|
if gated, ok := p.(ConfigGatedPlugin); ok && a.applyErr == nil {
|
|
// Gates are evaluated before Apply, so their keys must be declared at mount time.
|
|
a.applyErr = a.ctx.Config().Declare(name, gated.DeclareConfig()...)
|
|
}
|
|
}
|
|
|
|
return a
|
|
}
|
|
|
|
// Plugins returns a copy of all registered plugins in registration order.
|
|
func (a *App) Plugins() []Plugin {
|
|
a.mu.RLock()
|
|
defer a.mu.RUnlock()
|
|
|
|
res := make([]Plugin, len(a.plugins))
|
|
copy(res, a.plugins)
|
|
return res
|
|
}
|
|
|
|
// Plugin retrieves a registered plugin by its unique name.
|
|
func (a *App) Plugin(name string) (Plugin, bool) {
|
|
a.mu.RLock()
|
|
defer a.mu.RUnlock()
|
|
|
|
p, ok := a.pluginMap[name]
|
|
return p, ok
|
|
}
|
|
|
|
// Fibers returns a copy of all plugin Fibers.
|
|
func (a *App) Fibers() []*Fiber {
|
|
a.mu.RLock()
|
|
defer a.mu.RUnlock()
|
|
|
|
res := make([]*Fiber, len(a.fibers))
|
|
copy(res, a.fibers)
|
|
return res
|
|
}
|
|
|
|
// Fiber retrieves a Fiber by its unique plugin name.
|
|
func (a *App) Fiber(name string) (*Fiber, bool) {
|
|
a.mu.RLock()
|
|
defer a.mu.RUnlock()
|
|
|
|
f, ok := a.fiberMap[name]
|
|
return f, ok
|
|
}
|
|
|
|
// SetMigrationEngine sets the migration engine for the application.
|
|
func (a *App) SetMigrationEngine(engine MigrationEngine) *App {
|
|
a.mu.Lock()
|
|
defer a.mu.Unlock()
|
|
a.migrationEngine = engine
|
|
return a
|
|
}
|
|
|
|
// SetMigrationRunner sets the migration runner function for the application.
|
|
func (a *App) SetMigrationRunner(runner MigrationRunner) *App {
|
|
return a.SetMigrationEngine(runner)
|
|
}
|
|
|
|
// Reconcile evaluates all pending Fibers and reactively transitions them to ACTIVE
|
|
// as their declared dependencies become satisfied.
|
|
func (a *App) Reconcile() error {
|
|
a.mu.Lock()
|
|
defer a.mu.Unlock()
|
|
return a.reconcileLocked()
|
|
}
|
|
|
|
func (a *App) reconcileLocked() error {
|
|
if err := a.prepareLocked(); err != nil {
|
|
return err
|
|
}
|
|
|
|
for {
|
|
progress := false
|
|
for _, f := range a.fibers {
|
|
if f.State() != FiberPending {
|
|
continue
|
|
}
|
|
|
|
gated, skip, err := a.evaluateGateLocked(f)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if gated && skip {
|
|
if err := f.Skip(); err != nil {
|
|
return fmt.Errorf("core: skip gated fiber %q failed: %w", f.Name(), err)
|
|
}
|
|
continue
|
|
}
|
|
|
|
if f.DependenciesSatisfied(a.ctx) {
|
|
if err := f.Load(); err != nil {
|
|
return fmt.Errorf("core: load fiber %q failed: %w", f.Name(), err)
|
|
}
|
|
progress = true
|
|
}
|
|
}
|
|
if !progress {
|
|
break
|
|
}
|
|
}
|
|
|
|
var unsatisfied []string
|
|
for _, f := range a.fibers {
|
|
if f.State() == FiberPending {
|
|
unsatisfied = append(unsatisfied, fmt.Sprintf("%s (waiting for %v)", f.Name(), f.Dependencies()))
|
|
}
|
|
}
|
|
if len(unsatisfied) > 0 {
|
|
return fmt.Errorf("core: unsatisfied dependencies for plugins: %s", strings.Join(unsatisfied, ", "))
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// evaluateGateLocked reports whether a configuration-gated plugin is excluded by the
|
|
// resolved values. Plugins that do not implement the gate interface are never skipped.
|
|
func (a *App) evaluateGateLocked(f *Fiber) (gated bool, skip bool, err error) {
|
|
gatedPlugin, ok := f.plugin.(ConfigGatedPlugin)
|
|
if !ok {
|
|
return false, false, nil
|
|
}
|
|
|
|
view := a.ctx.Config()
|
|
if !view.Resolved() {
|
|
return true, false, fmt.Errorf(
|
|
"core: plugin %q is configuration-gated but the App has no ConfigSource; "+
|
|
"pass core.WithConfigSource or remove DeclareConfig", f.Name())
|
|
}
|
|
|
|
return true, !gatedPlugin.ConfigEnabled(view), nil
|
|
}
|
|
|
|
// ApplyPlugins applies all registered plugins on the application Context via reactive reconciliation.
|
|
// It is idempotent and only applies plugins once per App instance.
|
|
func (a *App) ApplyPlugins() error {
|
|
a.mu.Lock()
|
|
if a.applied {
|
|
a.mu.Unlock()
|
|
return nil
|
|
}
|
|
a.applied = true
|
|
|
|
declaredErr, prepareErr := a.applyErr, a.prepareLocked()
|
|
a.mu.Unlock()
|
|
|
|
if declaredErr != nil {
|
|
return declaredErr
|
|
}
|
|
if prepareErr != nil {
|
|
return prepareErr
|
|
}
|
|
|
|
return a.Reconcile()
|
|
}
|
|
|
|
// Prepare resolves declared configuration and establishes the resolution barrier that
|
|
// gates and plugin Bind calls depend on. It is idempotent and runs implicitly from
|
|
// ApplyPlugins; callers that need resolved values earlier — for example to size a
|
|
// shutdown budget — invoke it explicitly right after mounting plugins.
|
|
func (a *App) Prepare() error {
|
|
a.mu.Lock()
|
|
defer a.mu.Unlock()
|
|
|
|
if a.applyErr != nil {
|
|
return a.applyErr
|
|
}
|
|
return a.prepareLocked()
|
|
}
|
|
|
|
// prepareLocked installs the injected source, registers host declarations and resolves
|
|
// every declared key once. An App without a ConfigSource leaves configuration unused,
|
|
// so kernel-level usage stays opt-in for embedders that configure nothing.
|
|
func (a *App) prepareLocked() error {
|
|
if a.prepared {
|
|
return nil
|
|
}
|
|
if a.configSource == nil {
|
|
a.prepared = true
|
|
return nil
|
|
}
|
|
|
|
config := a.ctx.Config()
|
|
config.SetSource(a.configSource)
|
|
|
|
if err := config.Declare(a.hostDeclOwner, a.hostDeclBindings...); err != nil {
|
|
return err
|
|
}
|
|
if err := config.Resolve(); err != nil {
|
|
return err
|
|
}
|
|
a.prepared = true
|
|
|
|
return nil
|
|
}
|
|
|
|
// ShutdownTimeout returns the graceful shutdown budget for the application.
|
|
func (a *App) ShutdownTimeout() time.Duration {
|
|
a.mu.RLock()
|
|
defer a.mu.RUnlock()
|
|
return a.shutdownTimeout
|
|
}
|
|
|
|
// SetShutdownTimeout replaces the graceful shutdown budget, ignoring non-positive
|
|
// values so a missing configuration key can never shrink the kernel fallback to zero.
|
|
func (a *App) SetShutdownTimeout(timeout time.Duration) *App {
|
|
a.mu.Lock()
|
|
defer a.mu.Unlock()
|
|
if timeout > 0 {
|
|
a.shutdownTimeout = timeout
|
|
}
|
|
return a
|
|
}
|
|
|
|
// RunMigrations dispatches migration execution across all registered plugin migration entries.
|
|
func (a *App) RunMigrations() error {
|
|
entries := a.ctx.Migrations().Entries()
|
|
if len(entries) == 0 {
|
|
return nil
|
|
}
|
|
|
|
a.mu.RLock()
|
|
engine := a.migrationEngine
|
|
a.mu.RUnlock()
|
|
|
|
if engine == nil {
|
|
// Attempt to resolve from IoC container
|
|
if resolved, err := Inject[MigrationEngine](a.ctx); err == nil && resolved != nil {
|
|
engine = resolved
|
|
}
|
|
}
|
|
|
|
if engine == nil {
|
|
return nil
|
|
}
|
|
|
|
if err := engine.Migrate(a.ctx, entries); err != nil {
|
|
return fmt.Errorf("core: migration failed: %w", err)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// Start executes the application boot pipeline:
|
|
// 1. Applies all registered plugins to populate services, routes, tasks, and drivers.
|
|
// 2. Dispatches database migrations via MigrationEngine.
|
|
// 3. Filters and starts drivers matching the active Profile.
|
|
// 4. Emits "app:ready" on the EventBus.
|
|
func (a *App) Start(ctx ...context.Context) error {
|
|
a.mu.Lock()
|
|
if a.running {
|
|
a.mu.Unlock()
|
|
return ErrAppRunning
|
|
}
|
|
a.running = true
|
|
a.mu.Unlock()
|
|
|
|
var baseCtx context.Context
|
|
switch {
|
|
case len(ctx) > 0 && ctx[0] != nil:
|
|
baseCtx = ctx[0]
|
|
case a.ctx != nil:
|
|
baseCtx = a.ctx.GoContext()
|
|
default:
|
|
baseCtx = context.Background()
|
|
}
|
|
|
|
// 1. Apply plugins
|
|
if err := a.ApplyPlugins(); err != nil {
|
|
a.mu.Lock()
|
|
a.running = false
|
|
a.mu.Unlock()
|
|
return err
|
|
}
|
|
|
|
// 2. Run migrations
|
|
if err := a.RunMigrations(); err != nil {
|
|
a.mu.Lock()
|
|
a.running = false
|
|
a.mu.Unlock()
|
|
return err
|
|
}
|
|
|
|
// 3. Filter drivers matching active profile
|
|
a.mu.RLock()
|
|
prof := a.profile
|
|
a.mu.RUnlock()
|
|
|
|
allDrivers := a.ctx.Drivers()
|
|
var driversToStart []Driver
|
|
for _, d := range allDrivers {
|
|
if matchesProfile(prof, d.Type()) {
|
|
driversToStart = append(driversToStart, d)
|
|
}
|
|
}
|
|
|
|
// 4. Start matching drivers
|
|
for _, d := range driversToStart {
|
|
if err := d.Start(baseCtx); err != nil {
|
|
// Rollback already started drivers in reverse order
|
|
a.mu.Lock()
|
|
started := a.startedDrivers
|
|
a.startedDrivers = nil
|
|
a.running = false
|
|
a.mu.Unlock()
|
|
|
|
for i := len(started) - 1; i >= 0; i-- {
|
|
_ = started[i].Stop(context.Background())
|
|
}
|
|
|
|
return fmt.Errorf("core: start driver %s failed: %w", d.Type(), err)
|
|
}
|
|
|
|
a.mu.Lock()
|
|
a.startedDrivers = append(a.startedDrivers, d)
|
|
a.mu.Unlock()
|
|
}
|
|
|
|
// 5. Emit app:ready event
|
|
_ = a.ctx.Events().Emit(baseCtx, "app:ready", a)
|
|
|
|
return nil
|
|
}
|
|
|
|
// Stop gracefully shuts down the application:
|
|
// 1. Emits "app:stopping" on the EventBus.
|
|
// 2. Stops all started drivers in LIFO (reverse) order.
|
|
// 3. Disposes the Context (running registered OnDispose callbacks in LIFO order).
|
|
// 4. Emits "app:stopped" on the EventBus.
|
|
func (a *App) Stop(ctx ...context.Context) error {
|
|
a.mu.Lock()
|
|
if !a.running {
|
|
a.mu.Unlock()
|
|
return nil
|
|
}
|
|
a.running = false
|
|
started := a.startedDrivers
|
|
a.startedDrivers = nil
|
|
timeout := a.shutdownTimeout
|
|
a.mu.Unlock()
|
|
|
|
var shutdownCtx context.Context
|
|
if len(ctx) > 0 && ctx[0] != nil {
|
|
shutdownCtx = ctx[0]
|
|
} else {
|
|
var cancel context.CancelFunc
|
|
shutdownCtx, cancel = context.WithTimeout(context.Background(), timeout)
|
|
defer cancel()
|
|
}
|
|
|
|
_ = a.ctx.Events().Emit(shutdownCtx, "app:stopping", a)
|
|
|
|
var errs []error
|
|
|
|
// 1. Stop drivers in reverse order
|
|
for i := len(started) - 1; i >= 0; i-- {
|
|
d := started[i]
|
|
if err := d.Stop(shutdownCtx); err != nil {
|
|
errs = append(errs, fmt.Errorf("core: stop driver %s failed: %w", d.Type(), err))
|
|
}
|
|
}
|
|
|
|
// 2. Unload fibers in reverse order
|
|
a.mu.RLock()
|
|
fibers := make([]*Fiber, len(a.fibers))
|
|
copy(fibers, a.fibers)
|
|
a.mu.RUnlock()
|
|
|
|
for i := len(fibers) - 1; i >= 0; i-- {
|
|
if err := fibers[i].Unload(); err != nil {
|
|
errs = append(errs, fmt.Errorf("core: unload fiber %s failed: %w", fibers[i].Name(), err))
|
|
}
|
|
}
|
|
|
|
// 3. Dispose root context
|
|
if a.ctx != nil && !a.ctx.IsDisposed() {
|
|
if err := a.ctx.Dispose(); err != nil {
|
|
errs = append(errs, fmt.Errorf("core: dispose context failed: %w", err))
|
|
}
|
|
}
|
|
|
|
_ = a.ctx.Events().Emit(shutdownCtx, "app:stopped", a)
|
|
|
|
return errors.Join(errs...)
|
|
}
|
|
|
|
// Run starts the application and blocks until an OS signal (SIGINT, SIGTERM) or context cancellation is received,
|
|
// then executes graceful shutdown. It forwards a sigCtx derived from the caller's context to Start.
|
|
//
|
|
//nolint:contextcheck // the caller's ctx does reach Start via sigCtx; the rule cannot follow Run's variadic context parameter
|
|
func (a *App) Run(ctx ...context.Context) error {
|
|
var parent context.Context
|
|
switch {
|
|
case len(ctx) > 0 && ctx[0] != nil:
|
|
parent = ctx[0]
|
|
case a.ctx != nil:
|
|
parent = a.ctx.GoContext()
|
|
default:
|
|
parent = context.Background()
|
|
}
|
|
|
|
sigCtx, stopSignals := signal.NotifyContext(parent, syscall.SIGINT, syscall.SIGTERM, os.Interrupt)
|
|
defer stopSignals()
|
|
|
|
if err := a.Start(sigCtx); err != nil {
|
|
return err
|
|
}
|
|
|
|
// Wait for OS signal or context cancellation
|
|
<-sigCtx.Done()
|
|
|
|
shutdownCtx, cancel := context.WithTimeout(context.Background(), a.shutdownTimeout)
|
|
defer cancel()
|
|
|
|
return a.Stop(shutdownCtx)
|
|
}
|
|
|
|
// IsRunning returns whether the application is currently running.
|
|
func (a *App) IsRunning() bool {
|
|
a.mu.RLock()
|
|
defer a.mu.RUnlock()
|
|
return a.running
|
|
}
|
|
|
|
// StartedDrivers returns a copy of currently running drivers.
|
|
func (a *App) StartedDrivers() []Driver {
|
|
a.mu.RLock()
|
|
defer a.mu.RUnlock()
|
|
|
|
res := make([]Driver, len(a.startedDrivers))
|
|
copy(res, a.startedDrivers)
|
|
return res
|
|
}
|
|
|
|
// ExecuteCLI parses CLI arguments to configure the profile and runs the application.
|
|
func (a *App) ExecuteCLI(args ...string) error {
|
|
var ctx context.Context
|
|
if a.ctx != nil {
|
|
ctx = a.ctx.GoContext()
|
|
} else {
|
|
ctx = context.Background()
|
|
}
|
|
return a.ExecuteCLIWithContext(ctx, args...)
|
|
}
|
|
|
|
// ExecuteCLIWithContext parses CLI arguments, configures the profile, and runs the application with the given context.
|
|
func (a *App) ExecuteCLIWithContext(ctx context.Context, args ...string) error {
|
|
cliArgs := args
|
|
if len(cliArgs) == 0 {
|
|
cliArgs = os.Args[1:]
|
|
}
|
|
|
|
profile := ProfileAll
|
|
if len(cliArgs) > 0 {
|
|
first := strings.TrimSpace(cliArgs[0])
|
|
switch {
|
|
case strings.HasPrefix(first, "--profile="):
|
|
profile = Profile(strings.TrimPrefix(first, "--profile="))
|
|
case strings.HasPrefix(first, "-p="):
|
|
profile = Profile(strings.TrimPrefix(first, "-p="))
|
|
case !strings.HasPrefix(first, "-"):
|
|
profile = Profile(first)
|
|
}
|
|
}
|
|
|
|
a.WithProfile(profile)
|
|
return a.Run(ctx)
|
|
}
|
|
|
|
func matchesProfile(profile Profile, dt DriverType) bool {
|
|
norm := normalizeProfile(profile)
|
|
switch norm {
|
|
case ProfileAll, "":
|
|
return true
|
|
case ProfileAPI:
|
|
return dt == DriverTypeHTTP
|
|
case ProfileWorker:
|
|
return dt == DriverTypeWorker
|
|
case ProfileSchedule:
|
|
return dt == DriverTypeScheduler
|
|
default:
|
|
return string(norm) == string(dt)
|
|
}
|
|
}
|
|
|
|
func normalizeProfile(p Profile) Profile {
|
|
switch strings.ToLower(strings.TrimSpace(string(p))) {
|
|
case "api", "http":
|
|
return ProfileAPI
|
|
case "worker":
|
|
return ProfileWorker
|
|
case "schedule", "scheduler", "cron":
|
|
return ProfileSchedule
|
|
case "all", "fused", "full", "":
|
|
return ProfileAll
|
|
default:
|
|
return p
|
|
}
|
|
}
|