# Plugin 系统规范 ## 模块边界 plugin 包定义插件的契约与注册中心,是所有业务模块(包括内核模块和第三方插件)的统一接入方式。 **属于本模块:** Plugin 接口定义、注册中心、生命周期管理 **不属于本模块:** 具体插件的业务逻辑 ## Plugin 接口 每个插件必须实现: ```go type Plugin interface { Metadata() Metadata // 身份标识(name/version/description) FxOption() fx.Option // 依赖注入(提供 repo/service/handler) SetupRoutes(engine, authMW, tenantResolver) // HTTP 路由注册 Init() error // 启动钩子(worker/cache/外部连接) MigrationsFS() fs.FS // 插件自主迁移(独立 schema_migrations_{name} 表) } ``` ## 生命周期 ``` 1. app.go 启动 → fx 解析所有 Module → 依赖注入 2. OnStart → 核心迁移 → 插件迁移 → plugin.InitAll() 3. HTTP Server 启动 → 请求路由到各插件 Handler 4. OnStop → 优雅关闭 ``` ## 创建新插件步骤 1. 在 `internal/modules//` 创建 4 层目录 2. domain/ — 定义实体 + Repository 接口(零外部依赖) 3. infrastructure/ — GORM Repo 实现 + migrate.go 4. application/ — Service 编排 5. interfaces/ — Handler + Routes + Plugin 实现 6. 在 `app.go` 的 `NewApp()` 注册 fx.Module 7. 在 `newEngine()` 调用 `plugin.SetupRoutes()` ## 插件自主迁移 - 每个插件的迁移使用独立表:`schema_migrations_{pluginName}` - 插件通过 `MigrationsFS()` 返回嵌入的迁移文件 FS - 返回 nil 表示无迁移 - 迁移在核心迁移之后、Init() 之前执行 ## 路由约定 - 插件路由前缀:`/api/v1/{module}/` - 必须经过 authMW(JWT 认证)+ MultiTenant(租户识别) - 公开接口(如注册)不走 authMW ## 禁止 - 插件不得 import 其他插件的内部代码 - 插件不得直接操作其他插件的数据库表 - 插件间通信走事件总线(kernel/eventbus) - kernel/ 不得 import 任何插件代码