mirror of
https://github.com/Rain-kl/OpenFlare.git
synced 2026-10-07 08:06:37 +08:00
feat(cordis): add OpenFlare Cordis 架构改造设计
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 一致性门禁,
确保已部署库不重跑历史、不丢数据。
This commit is contained in:
@@ -0,0 +1,143 @@
|
||||
// Copyright 2026 Arctel.net
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
// Package contracts defines unified service interfaces and DTOs for cross-plugin communication.
|
||||
package contracts
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
)
|
||||
|
||||
// UserDTO represents a unified user data transfer object across plugins.
|
||||
type UserDTO struct {
|
||||
ID uint64 `json:"id,string"`
|
||||
Username string `json:"username"`
|
||||
Nickname string `json:"nickname"`
|
||||
Email string `json:"email"`
|
||||
AvatarURL string `json:"avatar_url"`
|
||||
IsActive bool `json:"is_active"`
|
||||
IsAdmin bool `json:"is_admin"`
|
||||
NeedChangePassword bool `json:"need_change_password,omitempty"`
|
||||
Bio string `json:"bio,omitempty"`
|
||||
Phone string `json:"phone,omitempty"`
|
||||
Gender string `json:"gender,omitempty"`
|
||||
Website string `json:"website,omitempty"`
|
||||
Location string `json:"location,omitempty"`
|
||||
LastLoginAt time.Time `json:"last_login_at"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// OAuthUserInfoDTO contains user identity claims obtained from an OAuth provider.
|
||||
type OAuthUserInfoDTO struct {
|
||||
ID uint64 `json:"id"`
|
||||
Sub string `json:"sub"`
|
||||
Username string `json:"username"`
|
||||
PreferredUsername string `json:"preferred_username"`
|
||||
Email string `json:"email"`
|
||||
Name string `json:"name"`
|
||||
Active bool `json:"active"`
|
||||
AvatarURL string `json:"avatar_url"`
|
||||
}
|
||||
|
||||
// AuthSourceDTO represents an OAuth / OIDC authentication source.
|
||||
type AuthSourceDTO struct {
|
||||
ID uint64 `json:"id,string"`
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
DisplayName string `json:"display_name"`
|
||||
ClientID string `json:"client_id"`
|
||||
ClientSecret string `json:"client_secret,omitempty"`
|
||||
OpenIDDiscoveryURL string `json:"openid_discovery_url"`
|
||||
Scopes string `json:"scopes"`
|
||||
IconURL string `json:"icon_url"`
|
||||
IsActive bool `json:"is_active"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// AuthSourceViewDTO is a sanitized view of an AuthSource for admin display.
|
||||
type AuthSourceViewDTO struct {
|
||||
ID uint64 `json:"id,string"`
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
DisplayName string `json:"display_name"`
|
||||
IsActive bool `json:"is_active"`
|
||||
IconURL string `json:"icon_url"`
|
||||
ClientSecretConfigured bool `json:"client_secret_configured"`
|
||||
}
|
||||
|
||||
// OAuthProvider defines the pluggable OAuth provider contract.
|
||||
type OAuthProvider interface {
|
||||
Name() string
|
||||
GetAuthURL(state string) string
|
||||
ExchangeCode(ctx context.Context, code string) (*OAuthUserInfoDTO, error)
|
||||
}
|
||||
|
||||
// AuthService defines the contract for authentication, session verification, and token management.
|
||||
type AuthService interface {
|
||||
// RequireAuthMiddleware returns a middleware handler (compatible with gin.HandlerFunc or standard middleware).
|
||||
RequireAuthMiddleware() any
|
||||
|
||||
// RequireAdminMiddleware returns an admin authorization middleware.
|
||||
RequireAdminMiddleware() any
|
||||
|
||||
// GetCurrentUser retrieves the authenticated UserDTO from context.
|
||||
GetCurrentUser(ctx context.Context) (*UserDTO, error)
|
||||
|
||||
// GetCurrentUserID retrieves the authenticated user ID from session/context.
|
||||
GetCurrentUserID(ctx context.Context) (uint64, error)
|
||||
|
||||
// VerifyToken validates an access token and returns the associated user DTO.
|
||||
VerifyToken(ctx context.Context, token string) (*UserDTO, error)
|
||||
|
||||
// CreateSession establishes an authenticated session for the given user ID.
|
||||
CreateSession(ctx context.Context, userID uint64, extras map[string]any) (string, error)
|
||||
|
||||
// RevokeToken invalidates a specific access token by its hash.
|
||||
RevokeToken(ctx context.Context, tokenHash string) error
|
||||
|
||||
// RevokeUserSessions revokes all active sessions and cached tokens for a user.
|
||||
RevokeUserSessions(ctx context.Context, userID uint64) error
|
||||
|
||||
// InvalidateCachedUser invalidates cached user profile data.
|
||||
InvalidateCachedUser(ctx context.Context, userID uint64)
|
||||
|
||||
// InvalidateCachedToken invalidates cached access token data.
|
||||
InvalidateCachedToken(ctx context.Context, tokenHash string)
|
||||
|
||||
// ListAuthSources lists all configured authentication sources.
|
||||
ListAuthSources(ctx context.Context) ([]AuthSourceViewDTO, error)
|
||||
|
||||
// CreateAuthSource creates a new authentication source.
|
||||
CreateAuthSource(ctx context.Context, source AuthSourceDTO) (*AuthSourceDTO, error)
|
||||
|
||||
// UpdateAuthSource updates an authentication source.
|
||||
UpdateAuthSource(ctx context.Context, id uint64, source AuthSourceDTO) (*AuthSourceDTO, error)
|
||||
|
||||
// DeleteAuthSource removes an authentication source.
|
||||
DeleteAuthSource(ctx context.Context, id uint64) error
|
||||
|
||||
// ToggleAuthSource toggles the active state of an authentication source.
|
||||
ToggleAuthSource(ctx context.Context, id uint64) (*AuthSourceDTO, error)
|
||||
|
||||
// DisallowTokenAuthMiddleware returns a middleware that rejects requests authenticated via access token.
|
||||
DisallowTokenAuthMiddleware() any
|
||||
}
|
||||
|
||||
// AuthRegistry allows downstream and domain plugins to register custom authentication providers.
|
||||
type AuthRegistry interface {
|
||||
RegisterOAuthProvider(name string, provider OAuthProvider)
|
||||
GetOAuthProvider(name string) (OAuthProvider, bool)
|
||||
ListOAuthProviders() []string
|
||||
}
|
||||
|
||||
// Auth context keys — stored in Gin context by auth middleware, consumed by domain plugins.
|
||||
const (
|
||||
AuthUserIDKey = "user_id"
|
||||
AuthUserNameKey = "username"
|
||||
AuthUserObjKey = "user_obj"
|
||||
AuthTokenAuthKey = "token_auth" // marks if request uses access token auth
|
||||
AuthTokenAdminKey = "token_admin" // whether the access token has admin privileges
|
||||
)
|
||||
@@ -0,0 +1,32 @@
|
||||
// Copyright 2026 Arctel.net
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
// Package contracts defines unified service interfaces and DTOs for cross-plugin communication.
|
||||
package contracts
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ErrCacheMiss is returned when an item is not found in the cache.
|
||||
var ErrCacheMiss = errors.New("contracts/cache: key not found")
|
||||
|
||||
// CacheService defines the contract for multi-layer cache operations (RAM L1 + Redis L2 + Pub/Sub invalidation).
|
||||
type CacheService interface {
|
||||
// Get retrieves an item from cache into target. Returns ErrCacheMiss if not found.
|
||||
Get(ctx context.Context, key string, target any) error
|
||||
|
||||
// Set stores an item into cache with a specified time-to-live duration.
|
||||
Set(ctx context.Context, key string, value any, ttl time.Duration) error
|
||||
|
||||
// Delete evicts a key from local and remote cache tiers and broadcasts invalidation.
|
||||
Delete(ctx context.Context, key string) error
|
||||
|
||||
// GetOrSet retrieves an item from cache, or calls loader to populate and return if missing.
|
||||
GetOrSet(ctx context.Context, key string, target any, ttl time.Duration, loader func() (any, error)) error
|
||||
|
||||
// Invalidate is a semantic alias for Delete.
|
||||
Invalidate(ctx context.Context, key string) error
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
// Copyright 2026 Arctel.net
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
// Package contracts defines unified service interfaces and DTOs for cross-plugin communication.
|
||||
package contracts
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// DBService defines the standard contract for relational database access and multi-datasource routing.
|
||||
type DBService interface {
|
||||
// GORM returns the underlying GORM database instance.
|
||||
GORM() *gorm.DB
|
||||
|
||||
// DB returns the GORM database instance bound to the given context.
|
||||
DB(ctx context.Context) *gorm.DB
|
||||
|
||||
// Named returns a named database connection if multiple data sources or replicas are configured.
|
||||
Named(name string) *gorm.DB
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
// Copyright 2026 Arctel.net
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
// Package contracts defines unified service interfaces and DTOs for cross-plugin communication.
|
||||
package contracts
|
||||
|
||||
// ======================================================================
|
||||
// Domain Event Topic Constants
|
||||
// ======================================================================
|
||||
//
|
||||
// All cross-plugin domain event topics MUST be declared here so that
|
||||
// producers and consumers share the same string values without importing
|
||||
// each other's implementation packages.
|
||||
// ======================================================================
|
||||
|
||||
// --- Auth & User Events ---
|
||||
const (
|
||||
// EventTopicAdminLoggedIn fires when an admin user logs in.
|
||||
EventTopicAdminLoggedIn = "admin:logged_in"
|
||||
|
||||
// EventTopicUserCreated fires when a new user account is created.
|
||||
EventTopicUserCreated = "user:created"
|
||||
|
||||
// EventTopicUserUpdated fires when a user profile is updated.
|
||||
EventTopicUserUpdated = "user:updated"
|
||||
|
||||
// EventTopicUserDeleted fires when a user account is deleted.
|
||||
EventTopicUserDeleted = "user:deleted"
|
||||
|
||||
// EventTopicUserStatusChanged fires when a user account active status changes.
|
||||
EventTopicUserStatusChanged = "user:status_changed"
|
||||
|
||||
// EventTopicTokenRevoked fires when an access token is revoked.
|
||||
// #nosec G101
|
||||
EventTopicTokenRevoked = "auth:token_revoked"
|
||||
)
|
||||
|
||||
// --- Admin & System Events ---
|
||||
const (
|
||||
// EventTopicConfigChanged fires when a system configuration value changes.
|
||||
EventTopicConfigChanged = "admin:config_changed"
|
||||
|
||||
// EventTopicSystemCleanup fires when a periodic system cleanup completes.
|
||||
EventTopicSystemCleanup = "admin:system_cleanup"
|
||||
)
|
||||
|
||||
// --- Task Events ---
|
||||
const (
|
||||
// EventTopicTaskCompleted fires when an asynchronous background task execution finishes.
|
||||
EventTopicTaskCompleted = "task:completed"
|
||||
)
|
||||
|
||||
// TaskCompletedEvent carries task execution outcome details.
|
||||
type TaskCompletedEvent struct {
|
||||
TaskID string `json:"task_id"`
|
||||
TaskName string `json:"task_name"`
|
||||
TaskType string `json:"task_type"`
|
||||
Status string `json:"status"`
|
||||
Duration int64 `json:"duration"`
|
||||
ErrorMsg string `json:"error_msg,omitempty"`
|
||||
ResultMsg string `json:"result_msg,omitempty"`
|
||||
Payload string `json:"payload,omitempty"`
|
||||
Detail string `json:"detail,omitempty"`
|
||||
}
|
||||
|
||||
// --- Upload / Storage Events ---
|
||||
const (
|
||||
// EventTopicUploadCreated fires when a new file upload is recorded.
|
||||
EventTopicUploadCreated = "upload:created"
|
||||
|
||||
// EventTopicUploadDeleted fires when a file upload is removed.
|
||||
EventTopicUploadDeleted = "upload:deleted"
|
||||
|
||||
// EventTopicIngestComplete fires when a programmatic file ingest finishes.
|
||||
EventTopicIngestComplete = "upload:ingest_complete"
|
||||
)
|
||||
|
||||
// --- Message Gateway Events ---
|
||||
const (
|
||||
// EventTopicNotificationSent fires when a push notification is dispatched.
|
||||
EventTopicNotificationSent = "message:notification_sent"
|
||||
|
||||
// EventTopicChannelBound fires when a user binds a messaging channel.
|
||||
EventTopicChannelBound = "message:channel_bound"
|
||||
|
||||
// EventTopicChannelUnbound fires when a user unbinds a messaging channel.
|
||||
EventTopicChannelUnbound = "message:channel_unbound"
|
||||
)
|
||||
|
||||
// --- Risk Control Events ---
|
||||
const (
|
||||
// EventTopicAccessLogRecorded fires when a user access log entry is recorded.
|
||||
EventTopicAccessLogRecorded = "risk:access_log_recorded"
|
||||
)
|
||||
|
||||
// ======================================================================
|
||||
// Domain Event Payload DTOs
|
||||
// ======================================================================
|
||||
|
||||
// AdminLoggedIn 管理员登录领域事件载荷
|
||||
type AdminLoggedIn struct {
|
||||
User *UserDTO `json:"user"`
|
||||
IP string `json:"ip"`
|
||||
}
|
||||
|
||||
// UserCreatedEvent fires when a new user account is created.
|
||||
type UserCreatedEvent struct {
|
||||
User *UserDTO `json:"user"`
|
||||
Password string `json:"-"`
|
||||
}
|
||||
|
||||
// ConfigChangedEvent fires when a system configuration value changes.
|
||||
type ConfigChangedEvent struct {
|
||||
Key string `json:"key"`
|
||||
OldVal any `json:"old_val,omitempty"`
|
||||
NewVal any `json:"new_val,omitempty"`
|
||||
}
|
||||
|
||||
// UploadCreatedEvent fires when a new file upload is recorded.
|
||||
type UploadCreatedEvent struct {
|
||||
UploadID uint64 `json:"upload_id,string"`
|
||||
UserID uint64 `json:"user_id,string"`
|
||||
FileName string `json:"file_name"`
|
||||
FileSize int64 `json:"file_size"`
|
||||
MimeType string `json:"mime_type"`
|
||||
}
|
||||
|
||||
// NotificationSentEvent fires when a push notification is dispatched.
|
||||
type NotificationSentEvent struct {
|
||||
UserID uint64 `json:"user_id,string"`
|
||||
Channel string `json:"channel"`
|
||||
Title string `json:"title"`
|
||||
Success bool `json:"success"`
|
||||
ErrorInfo string `json:"error_info,omitempty"`
|
||||
}
|
||||
|
||||
// UserStatusChangedEvent fires when a user status is enabled/disabled.
|
||||
type UserStatusChangedEvent struct {
|
||||
UserID uint64 `json:"user_id,string"`
|
||||
IsActive bool `json:"is_active"`
|
||||
}
|
||||
|
||||
// TokenRevokedEvent fires when an access token is revoked.
|
||||
type TokenRevokedEvent struct {
|
||||
UserID uint64 `json:"user_id,string"`
|
||||
TokenHash string `json:"token_hash"`
|
||||
}
|
||||
|
||||
// UserDeletedEvent fires when a user account is deleted.
|
||||
type UserDeletedEvent struct {
|
||||
CurrentUserID uint64 `json:"current_user_id,string"`
|
||||
TargetUserID uint64 `json:"target_user_id,string"`
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
// Copyright 2026 Arctel.net
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
// Package contracts defines unified service interfaces and DTOs for cross-plugin communication.
|
||||
package contracts
|
||||
|
||||
import (
|
||||
"context"
|
||||
)
|
||||
|
||||
// LoggerService defines the contract for structured logging with trace ID and context correlation.
|
||||
type LoggerService interface {
|
||||
// Debug logs a debug message with optional key-value structured fields.
|
||||
Debug(ctx context.Context, msg string, keysAndValues ...any)
|
||||
|
||||
// Info logs an informational message with optional key-value structured fields.
|
||||
Info(ctx context.Context, msg string, keysAndValues ...any)
|
||||
|
||||
// Warn logs a warning message with optional key-value structured fields.
|
||||
Warn(ctx context.Context, msg string, keysAndValues ...any)
|
||||
|
||||
// Error logs an error message with optional key-value structured fields.
|
||||
Error(ctx context.Context, msg string, keysAndValues ...any)
|
||||
|
||||
// Debugf logs a formatted debug message.
|
||||
Debugf(ctx context.Context, format string, args ...any)
|
||||
|
||||
// Infof logs a formatted informational message.
|
||||
Infof(ctx context.Context, format string, args ...any)
|
||||
|
||||
// Warnf logs a formatted warning message.
|
||||
Warnf(ctx context.Context, format string, args ...any)
|
||||
|
||||
// Errorf logs a formatted error message.
|
||||
Errorf(ctx context.Context, format string, args ...any)
|
||||
|
||||
// With returns a child logger enriched with additional key-value attributes.
|
||||
With(keysAndValues ...any) LoggerService
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
// Copyright 2026 Arctel.net
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
// Package contracts defines unified service interfaces and DTOs for cross-plugin communication.
|
||||
package contracts
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
)
|
||||
|
||||
// AccessLogFilterDTO defines filter criteria for querying user access logs.
|
||||
type AccessLogFilterDTO struct {
|
||||
UserIDs []uint64
|
||||
Path string
|
||||
StartTime *time.Time
|
||||
EndTime *time.Time
|
||||
}
|
||||
|
||||
// AccessLogDTO represents a single access log entry.
|
||||
type AccessLogDTO struct {
|
||||
ID uint64 `json:"id"`
|
||||
UserID uint64 `json:"user_id"`
|
||||
IP string `json:"ip"`
|
||||
UserAgent string `json:"user_agent"`
|
||||
Method string `json:"method"`
|
||||
Path string `json:"path"`
|
||||
Status int32 `json:"status"`
|
||||
Latency int64 `json:"latency"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
// AccessLogDailyStatsDTO represents aggregate access statistics for a single day.
|
||||
type AccessLogDailyStatsDTO struct {
|
||||
Date string `json:"date"`
|
||||
PV uint64 `json:"pv"`
|
||||
UV uint64 `json:"uv"`
|
||||
IPCount uint64 `json:"ip_count"`
|
||||
ErrorCount uint64 `json:"error_count"`
|
||||
AvgLatencyMs int64 `json:"avg_latency_ms"`
|
||||
SlowReqCount uint64 `json:"slow_req_count"`
|
||||
MaxLatencyMs int64 `json:"max_latency_ms"`
|
||||
P95LatencyMs int64 `json:"p95_latency_ms"`
|
||||
P99LatencyMs int64 `json:"p99_latency_ms"`
|
||||
}
|
||||
|
||||
// RiskControlService defines the contract for accessing security risk control and audit logstore.
|
||||
type RiskControlService interface {
|
||||
// QueryAccessLogs retrieves paginated access logs matching the filter.
|
||||
QueryAccessLogs(ctx context.Context, filter AccessLogFilterDTO, page, pageSize int) ([]AccessLogDTO, uint64, error)
|
||||
|
||||
// QueryAccessLogStats returns aggregate daily statistics for the last N days.
|
||||
QueryAccessLogStats(ctx context.Context, days int) ([]AccessLogDailyStatsDTO, error)
|
||||
|
||||
// ActiveLogEngine returns the current active logstore engine name.
|
||||
ActiveLogEngine(ctx context.Context) string
|
||||
|
||||
// IsLogEngineMigrating reports whether a log engine migration is in progress.
|
||||
IsLogEngineMigrating(ctx context.Context) bool
|
||||
|
||||
// Drain flushes pending in-flight log buffers.
|
||||
Drain(ctx context.Context) error
|
||||
|
||||
// SwitchLogEngine migrates and switches the active log storage engine.
|
||||
SwitchLogEngine(ctx context.Context, targetEngine string) error
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
// Copyright 2026 Arctel.net
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
// Package contracts defines unified service interfaces and DTOs for cross-plugin communication.
|
||||
package contracts
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
)
|
||||
|
||||
// StorageObject represents a retrieved file object from the storage backend.
|
||||
type StorageObject struct {
|
||||
Key string
|
||||
CachePath string
|
||||
Body io.ReadCloser
|
||||
ContentLength int64
|
||||
ContentType string
|
||||
}
|
||||
|
||||
// StoragePutResult describes the output of a successful Put operation.
|
||||
type StoragePutResult struct {
|
||||
Key string
|
||||
Bucket string
|
||||
}
|
||||
|
||||
// IngestOptions configures programmatic ingest of files into the platform storage.
|
||||
type IngestOptions struct {
|
||||
UserID uint64
|
||||
Type string
|
||||
FileName string
|
||||
MimeType string
|
||||
Extension string
|
||||
Size int64
|
||||
Policy int
|
||||
Metadata map[string]any
|
||||
}
|
||||
|
||||
// IngestResult reports the outcome of a programmatic file ingest operation.
|
||||
type IngestResult struct {
|
||||
ID uint64
|
||||
Key string
|
||||
URL string
|
||||
Created bool
|
||||
Stored bool
|
||||
Resolved bool
|
||||
}
|
||||
|
||||
// StorageDriver identifies a supported storage backend.
|
||||
type StorageDriver string
|
||||
|
||||
// Storage drivers supported by the platform. Values persist in storage configs.
|
||||
const (
|
||||
StorageDriverLocal StorageDriver = "local"
|
||||
StorageDriverS3 StorageDriver = "s3"
|
||||
StorageDriverR2 StorageDriver = "r2"
|
||||
StorageDriverMinIO StorageDriver = "minio"
|
||||
StorageDriverOSS StorageDriver = "oss"
|
||||
StorageDriverWebDAV StorageDriver = "webdav"
|
||||
)
|
||||
|
||||
// LocalStorageConfigDTO configures local filesystem storage.
|
||||
type LocalStorageConfigDTO struct {
|
||||
Root string `json:"root"`
|
||||
}
|
||||
|
||||
// ObjectStorageConfigDTO configures S3-compatible or OSS object storage.
|
||||
type ObjectStorageConfigDTO struct {
|
||||
Endpoint string `json:"endpoint"`
|
||||
Region string `json:"region"`
|
||||
Bucket string `json:"bucket"`
|
||||
AccessKeyID string `json:"access_key_id"`
|
||||
SecretAccessKey string `json:"secret_access_key"`
|
||||
AccountID string `json:"account_id,omitempty"`
|
||||
PathStyle bool `json:"path_style"`
|
||||
KeyPrefix string `json:"key_prefix"`
|
||||
CDNURL string `json:"cdn_url"`
|
||||
}
|
||||
|
||||
// WebDAVStorageConfigDTO configures WebDAV storage.
|
||||
type WebDAVStorageConfigDTO struct {
|
||||
URL string `json:"url"`
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
Root string `json:"root"`
|
||||
}
|
||||
|
||||
// StorageConfigDTO encapsulates full storage configuration across all backends.
|
||||
type StorageConfigDTO struct {
|
||||
Driver StorageDriver `json:"driver"`
|
||||
Local LocalStorageConfigDTO `json:"local"`
|
||||
S3 ObjectStorageConfigDTO `json:"s3"`
|
||||
R2 ObjectStorageConfigDTO `json:"r2"`
|
||||
MinIO ObjectStorageConfigDTO `json:"minio"`
|
||||
OSS ObjectStorageConfigDTO `json:"oss"`
|
||||
WebDAV WebDAVStorageConfigDTO `json:"webdav"`
|
||||
}
|
||||
|
||||
// StorageService defines the contract for unified object storage and managed file ingestion.
|
||||
type StorageService interface {
|
||||
// Put writes an object to storage.
|
||||
Put(ctx context.Context, key string, body io.Reader, size int64, contentType string) (StoragePutResult, error)
|
||||
|
||||
// Get retrieves an object from storage.
|
||||
Get(ctx context.Context, key string) (*StorageObject, error)
|
||||
|
||||
// Delete removes an object from storage.
|
||||
Delete(ctx context.Context, key string) error
|
||||
|
||||
// Ingest performs managed file ingestion into the platform storage domain with deduplication and metadata tracking.
|
||||
Ingest(ctx context.Context, reader io.Reader, opts IngestOptions) (*IngestResult, error)
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
// Copyright 2026 Arctel.net
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
// Package contracts defines unified service interfaces and DTOs for cross-plugin communication.
|
||||
package contracts
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
)
|
||||
|
||||
// TaskParamDTO describes a parameter accepted by a background task.
|
||||
type TaskParamDTO struct {
|
||||
Name string `json:"name"`
|
||||
Label string `json:"label"`
|
||||
Type string `json:"type"`
|
||||
Required bool `json:"required"`
|
||||
Placeholder string `json:"placeholder,omitempty"`
|
||||
Description string `json:"description,omitempty"`
|
||||
Default any `json:"default,omitempty"`
|
||||
}
|
||||
|
||||
// TaskMetaDTO describes the metadata and configuration of a registered background task.
|
||||
type TaskMetaDTO struct {
|
||||
Type string `json:"type"`
|
||||
AsynqTask string `json:"asynq_task"`
|
||||
Name string `json:"name"`
|
||||
DisplayName string `json:"display_name,omitempty"`
|
||||
Description string `json:"description"`
|
||||
Category string `json:"category,omitempty"`
|
||||
SupportsTime bool `json:"supports_time"`
|
||||
Params []TaskParamDTO `json:"params,omitempty"`
|
||||
MaxRetry int `json:"max_retry"`
|
||||
Timeout time.Duration `json:"timeout,omitempty"`
|
||||
Queue string `json:"queue"`
|
||||
Retryable bool `json:"retryable"`
|
||||
Schedule string `json:"schedule,omitempty"`
|
||||
}
|
||||
|
||||
// TaskResultDTO represents the outcome of a background task execution.
|
||||
type TaskResultDTO struct {
|
||||
Message string `json:"message"`
|
||||
Detail any `json:"detail,omitempty"`
|
||||
}
|
||||
|
||||
// TaskExecutionDTO represents a single task execution record.
|
||||
type TaskExecutionDTO struct {
|
||||
ID uint64 `json:"id,string"`
|
||||
TaskID string `json:"task_id"`
|
||||
TaskType string `json:"task_type"`
|
||||
TaskName string `json:"task_name"`
|
||||
Status string `json:"status"`
|
||||
Retryable bool `json:"retryable"`
|
||||
MaxRetry int `json:"max_retry"`
|
||||
RetryCount int `json:"retry_count"`
|
||||
Log string `json:"log"`
|
||||
ErrorMessage string `json:"error_message"`
|
||||
Result string `json:"result"`
|
||||
StartedAt *time.Time `json:"started_at"`
|
||||
FinishedAt *time.Time `json:"finished_at"`
|
||||
Duration int64 `json:"duration"`
|
||||
Payload string `json:"payload"`
|
||||
TriggeredBy string `json:"triggered_by"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// TaskService defines the unified contract for dispatching and tracking background tasks.
|
||||
type TaskService interface {
|
||||
Dispatch(ctx context.Context, taskType string, payload []byte, triggeredBy string) (string, error)
|
||||
Retry(ctx context.Context, id uint64) (string, error)
|
||||
ListTasks() []TaskMetaDTO
|
||||
GetTaskMeta(taskType string) (TaskMetaDTO, bool)
|
||||
ValidatePayload(taskType string, payload []byte) ([]byte, error)
|
||||
ReloadScheduler() error
|
||||
AppendLog(ctx context.Context, format string, args ...any)
|
||||
ListExecutions(ctx context.Context, taskType, status string, page, pageSize int) ([]TaskExecutionDTO, int64, error)
|
||||
GetExecution(ctx context.Context, id uint64) (*TaskExecutionDTO, error)
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
// Copyright 2026 Arctel.net
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
// Package contracts defines unified service interfaces and DTOs for cross-plugin communication.
|
||||
package contracts
|
||||
|
||||
import (
|
||||
"context"
|
||||
)
|
||||
|
||||
// CreateUserRequest contains fields to register or create a new user.
|
||||
type CreateUserRequest struct {
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
Nickname string `json:"nickname"`
|
||||
Email string `json:"email"`
|
||||
IsAdmin bool `json:"is_admin"`
|
||||
}
|
||||
|
||||
// UpdateUserProfileRequest contains fields for updating a user's profile.
|
||||
type UpdateUserProfileRequest struct {
|
||||
Nickname *string `json:"nickname,omitempty"`
|
||||
Email *string `json:"email,omitempty"`
|
||||
AvatarURL *string `json:"avatar_url,omitempty"`
|
||||
Bio *string `json:"bio,omitempty"`
|
||||
Phone *string `json:"phone,omitempty"`
|
||||
Gender *string `json:"gender,omitempty"`
|
||||
Website *string `json:"website,omitempty"`
|
||||
Location *string `json:"location,omitempty"`
|
||||
}
|
||||
|
||||
// AdminListUsersFilter contains query parameters for filtering users in admin panel.
|
||||
type AdminListUsersFilter struct {
|
||||
Page int
|
||||
PageSize int
|
||||
UserID *uint64
|
||||
Username string
|
||||
Email string
|
||||
}
|
||||
|
||||
// AdminCreateUserRequest contains fields for admin to create a user.
|
||||
type AdminCreateUserRequest struct {
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
Nickname string `json:"nickname"`
|
||||
Email string `json:"email"`
|
||||
IsActive bool `json:"is_active"`
|
||||
IsAdmin bool `json:"is_admin"`
|
||||
}
|
||||
|
||||
// AdminUpdateUserRequest contains fields for admin to update a user.
|
||||
type AdminUpdateUserRequest struct {
|
||||
ID uint64 `json:"id,string"`
|
||||
Nickname string `json:"nickname"`
|
||||
Email string `json:"email"`
|
||||
IsAdmin bool `json:"is_admin"`
|
||||
Password string `json:"password,omitempty"`
|
||||
}
|
||||
|
||||
// UserService defines the contract for user account management and profile queries.
|
||||
type UserService interface {
|
||||
// GetUserByID retrieves a user by ID.
|
||||
GetUserByID(ctx context.Context, id uint64) (*UserDTO, error)
|
||||
|
||||
// GetUsersByIDs retrieves several users in one round-trip. An empty ids
|
||||
// slice yields no results and touches no storage.
|
||||
GetUsersByIDs(ctx context.Context, ids []uint64) ([]*UserDTO, error)
|
||||
|
||||
// GetUserByUsername retrieves a user by username.
|
||||
GetUserByUsername(ctx context.Context, username string) (*UserDTO, error)
|
||||
|
||||
// GetUserByEmail retrieves a user by email.
|
||||
GetUserByEmail(ctx context.Context, email string) (*UserDTO, error)
|
||||
|
||||
// CreateUser registers or creates a new user account.
|
||||
CreateUser(ctx context.Context, req CreateUserRequest) (*UserDTO, error)
|
||||
|
||||
// UpdateProfile updates the profile of the specified user.
|
||||
UpdateProfile(ctx context.Context, id uint64, req UpdateUserProfileRequest) (*UserDTO, error)
|
||||
|
||||
// UpdatePassword updates the password for the specified user after verifying the old password.
|
||||
UpdatePassword(ctx context.Context, id uint64, oldPassword, newPassword string) error
|
||||
|
||||
// VerifyPassword verifies if the given password matches the user's password.
|
||||
VerifyPassword(ctx context.Context, id uint64, password string) bool
|
||||
|
||||
// UpdateLastLogin updates the user's last login timestamp.
|
||||
UpdateLastLogin(ctx context.Context, id uint64, ip string) error
|
||||
|
||||
// ListUsers returns a paginated list of users with optional keyword search.
|
||||
ListUsers(ctx context.Context, page, pageSize int, keyword string) ([]*UserDTO, int64, error)
|
||||
|
||||
// SetUserActive sets the active/banned status for a user.
|
||||
SetUserActive(ctx context.Context, id uint64, active bool) error
|
||||
|
||||
// SetUserAdmin sets the admin role status for a user.
|
||||
SetUserAdmin(ctx context.Context, id uint64, admin bool) error
|
||||
|
||||
// VerifyAccessToken verifies an access token hash and returns the user DTO and isAdmin flag.
|
||||
VerifyAccessToken(ctx context.Context, tokenHash string) (*UserDTO, bool, error)
|
||||
|
||||
// DeleteUser removes a user and related access tokens.
|
||||
DeleteUser(ctx context.Context, id uint64) error
|
||||
|
||||
// CountUsers returns total user count.
|
||||
CountUsers(ctx context.Context) (int64, error)
|
||||
|
||||
// CountActiveUsers returns active user count.
|
||||
CountActiveUsers(ctx context.Context) (int64, error)
|
||||
|
||||
// GetFirstAdminUser returns the earliest admin user.
|
||||
GetFirstAdminUser(ctx context.Context) (*UserDTO, error)
|
||||
|
||||
// UniqueUsername generates a unique username candidate based on base.
|
||||
UniqueUsername(ctx context.Context, base string) (string, error)
|
||||
|
||||
// AdminListUsers returns a filtered paginated list of users for admin management.
|
||||
AdminListUsers(ctx context.Context, filter AdminListUsersFilter) (int64, []*UserDTO, error)
|
||||
|
||||
// AdminGetUser retrieves complete user details by ID for admin management.
|
||||
AdminGetUser(ctx context.Context, id uint64) (*UserDTO, error)
|
||||
|
||||
// AdminCreateUser creates a user with admin specified options.
|
||||
AdminCreateUser(ctx context.Context, req AdminCreateUserRequest) (*UserDTO, error)
|
||||
|
||||
// AdminUpdateUser updates user details, email, nickname, admin role, and optional password.
|
||||
AdminUpdateUser(ctx context.Context, currentUserID uint64, req AdminUpdateUserRequest) error
|
||||
|
||||
// AdminUpdateUserStatus updates a user's active status (with admin protection).
|
||||
AdminUpdateUserStatus(ctx context.Context, id uint64, active bool) error
|
||||
|
||||
// AdminDeleteUser deletes a user (with self and admin protection, cascading tokens and accounts).
|
||||
AdminDeleteUser(ctx context.Context, currentUserID, targetID uint64) error
|
||||
}
|
||||
Reference in New Issue
Block a user