mirror of
https://github.com/Rain-kl/OpenFlare.git
synced 2026-10-08 16:46:37 +08:00
chore(cordis): sync Wavelet core/pkg/plugins after W1-W9
This commit is contained in:
@@ -1,28 +1,3 @@
|
|||||||
# 上游本地补丁清单
|
# 上游本地补丁清单
|
||||||
|
|
||||||
`scripts/sync-upstream.sh` 会用上游覆盖 `backend/{core,pkg,plugins}`。以下文件带有
|
当前无本地内核补丁。
|
||||||
OpenFlare 侧必需的内核补丁:同步后若丢失,`go build ./...` 或用例集会失败,
|
|
||||||
按本表重新应用,并应回流 Wavelet 上游后删除本条记录。
|
|
||||||
|
|
||||||
- `core/extpoints/router.go`
|
|
||||||
- `core/scoped_extpoints.go`
|
|
||||||
|
|
||||||
## core:RouterExtension 增加 HandleRaw / BasePath
|
|
||||||
|
|
||||||
`Handle` 经 `cleanPath` 归一化会剥掉尾部斜杠,无法表达 `/resource` 与 `/resource/`
|
|
||||||
两条不同路由;OpenFlare 的 20 个历史 list 端点两者都注册且部署关闭了
|
|
||||||
`RedirectTrailingSlash`,缺失即 404。
|
|
||||||
|
|
||||||
- `HandleRaw(method, path, handlers...)`:与组前缀拼接但**保留**尾部斜杠;
|
|
||||||
- `BasePath()`:返回组绝对前缀(根注册表为空串);
|
|
||||||
- 作用域包装器为 `HandleRaw` 同样登记 `OnDispose` 反注册;
|
|
||||||
- 用例:`core/extpoints/router_raw_test.go`。
|
|
||||||
|
|
||||||
## 回流状态
|
|
||||||
|
|
||||||
上述内核补丁与 `pkg/util` 新增助手已提交到 Wavelet 分支
|
|
||||||
`feat/cordis-router-raw-routes`(worktree `/Users/ryan/Code/Go/Wavelet-router-raw`,
|
|
||||||
提交 `cb339ab`、`bad6fa7`、`8ff017b`)。**合并进 Wavelet main 后**:重跑
|
|
||||||
`scripts/sync-upstream.sh`,确认 `sync-upstream.sh --check` 零差异,然后清空本清单。
|
|
||||||
|
|
||||||
`pkg/util` 的版本比较 / 网络 / 格式化助手已回流,当前零漂移。
|
|
||||||
|
|||||||
+37
-30
@@ -59,6 +59,14 @@ func WithMigrationRunner(runner MigrationRunner) AppOption {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// WithMigrationBaseline registers a hook the migration engine runs after the
|
||||||
|
// shared version table exists and before any plugin Up.
|
||||||
|
func WithMigrationBaseline(fn func(*Context) error) AppOption {
|
||||||
|
return func(a *App) {
|
||||||
|
a.migrationBaseline = fn
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// WithShutdownTimeout sets the fallback timeout for graceful application shutdown.
|
// WithShutdownTimeout sets the fallback timeout for graceful application shutdown.
|
||||||
func WithShutdownTimeout(timeout time.Duration) AppOption {
|
func WithShutdownTimeout(timeout time.Duration) AppOption {
|
||||||
return func(a *App) {
|
return func(a *App) {
|
||||||
@@ -99,23 +107,24 @@ func WithConfigDecl(pluginID string, bindings ...ConfigBinding) AppOption {
|
|||||||
// It manages plugin collection, dependency mounting, migration execution, profile-based driver startup,
|
// It manages plugin collection, dependency mounting, migration execution, profile-based driver startup,
|
||||||
// and graceful signal-driven LIFO shutdown.
|
// and graceful signal-driven LIFO shutdown.
|
||||||
type App struct {
|
type App struct {
|
||||||
mu sync.RWMutex
|
mu sync.RWMutex
|
||||||
ctx *Context
|
ctx *Context
|
||||||
profile Profile
|
profile Profile
|
||||||
plugins []Plugin
|
plugins []Plugin
|
||||||
pluginMap map[string]Plugin
|
pluginMap map[string]Plugin
|
||||||
fibers []*Fiber
|
fibers []*Fiber
|
||||||
fiberMap map[string]*Fiber
|
fiberMap map[string]*Fiber
|
||||||
applied bool
|
applied bool
|
||||||
running bool
|
running bool
|
||||||
startedDrivers []Driver
|
startedDrivers []Driver
|
||||||
migrationEngine MigrationEngine
|
migrationEngine MigrationEngine
|
||||||
shutdownTimeout time.Duration
|
migrationBaseline func(*Context) error
|
||||||
configSource ConfigSource
|
shutdownTimeout time.Duration
|
||||||
hostDeclOwner string
|
configSource ConfigSource
|
||||||
hostDeclBindings []ConfigBinding
|
hostDeclOwner string
|
||||||
prepared bool
|
hostDeclBindings []ConfigBinding
|
||||||
applyErr error
|
prepared bool
|
||||||
|
applyErr error
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewApp creates a new Cordis application instance with default options.
|
// NewApp creates a new Cordis application instance with default options.
|
||||||
@@ -373,22 +382,20 @@ func (a *App) prepareLocked() error {
|
|||||||
if a.prepared {
|
if a.prepared {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
if a.configSource == nil {
|
if a.configSource != nil {
|
||||||
a.prepared = true
|
config := a.ctx.Config()
|
||||||
return nil
|
config.SetSource(a.configSource)
|
||||||
|
|
||||||
|
if err := config.Declare(a.hostDeclOwner, a.hostDeclBindings...); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := config.Resolve(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
config := a.ctx.Config()
|
a.ctx.setMigrationBaseline(a.migrationBaseline)
|
||||||
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
|
a.prepared = true
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -594,3 +594,61 @@ func TestAppSetShutdownTimeoutIgnoresNonPositive(t *testing.T) {
|
|||||||
app.SetShutdownTimeout(45 * time.Second)
|
app.SetShutdownTimeout(45 * time.Second)
|
||||||
assert.Equal(t, 45*time.Second, app.ShutdownTimeout())
|
assert.Equal(t, 45*time.Second, app.ShutdownTimeout())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestWithMigrationBaselineVisibleAfterPrepare(t *testing.T) {
|
||||||
|
var called bool
|
||||||
|
fn := func(*core.Context) error {
|
||||||
|
called = true
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
app := core.NewApp(core.WithMigrationBaseline(fn))
|
||||||
|
require.Nil(t, app.Context().MigrationBaseline(), "baseline must be copied during Prepare")
|
||||||
|
|
||||||
|
require.NoError(t, app.Prepare())
|
||||||
|
|
||||||
|
got := app.Context().MigrationBaseline()
|
||||||
|
require.NotNil(t, got, "Prepare must copy the baseline onto the root Context")
|
||||||
|
require.NoError(t, got(app.Context()))
|
||||||
|
assert.True(t, called)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWithMigrationBaselineRunsBeforeEngineMigrate(t *testing.T) {
|
||||||
|
var order []string
|
||||||
|
engine := core.MigrationRunner(func(ctx *core.Context, _ []extpoints.MigrationEntry) error {
|
||||||
|
order = append(order, "engine")
|
||||||
|
if ctx.MigrationBaseline() == nil {
|
||||||
|
t.Fatal("baseline must be visible on context inside Migrate")
|
||||||
|
}
|
||||||
|
return ctx.MigrationBaseline()(ctx)
|
||||||
|
})
|
||||||
|
|
||||||
|
sqlFS := fstest.MapFS{
|
||||||
|
"migrations/001_init.sql": &fstest.MapFile{Data: []byte("-- +goose Up\nSELECT 1;\n")},
|
||||||
|
}
|
||||||
|
app := core.NewApp(
|
||||||
|
core.WithMigrationEngine(engine),
|
||||||
|
core.WithMigrationBaseline(func(*core.Context) error {
|
||||||
|
order = append(order, "baseline")
|
||||||
|
return nil
|
||||||
|
}),
|
||||||
|
core.WithPlugins(&appMockPlugin{
|
||||||
|
name: "t",
|
||||||
|
applyFn: func(ctx *core.Context) error {
|
||||||
|
ctx.Migrations().Register("t", sqlFS)
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
require.NoError(t, app.Start(context.Background()))
|
||||||
|
defer func() { _ = app.Stop(context.Background()) }()
|
||||||
|
|
||||||
|
assert.Equal(t, []string{"engine", "baseline"}, order)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWithMigrationBaselineNilByDefault(t *testing.T) {
|
||||||
|
app := core.NewApp()
|
||||||
|
require.NoError(t, app.Prepare())
|
||||||
|
assert.Nil(t, app.Context().MigrationBaseline())
|
||||||
|
}
|
||||||
|
|||||||
+47
-18
@@ -29,12 +29,13 @@ type Context struct {
|
|||||||
settings extpoints.SettingExtension
|
settings extpoints.SettingExtension
|
||||||
config extpoints.ConfigExtension
|
config extpoints.ConfigExtension
|
||||||
|
|
||||||
mu sync.RWMutex
|
mu sync.RWMutex
|
||||||
children []*Context
|
children []*Context
|
||||||
disposers []Disposer
|
disposers []Disposer
|
||||||
drivers []Driver
|
drivers []Driver
|
||||||
values map[any]any
|
values map[any]any
|
||||||
disposed bool
|
disposed bool
|
||||||
|
migrationBaseline func(*Context) error
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewContext creates a new root Context wrapping a standard Go context.
|
// NewContext creates a new root Context wrapping a standard Go context.
|
||||||
@@ -159,18 +160,19 @@ func (c *Context) ForkWithContext(base context.Context) *Context {
|
|||||||
ctx, cancel := context.WithCancel(base)
|
ctx, cancel := context.WithCancel(base)
|
||||||
|
|
||||||
child := &Context{
|
child := &Context{
|
||||||
goCtx: ctx,
|
goCtx: ctx,
|
||||||
cancel: cancel,
|
cancel: cancel,
|
||||||
parent: c,
|
parent: c,
|
||||||
container: NewContainer(c.container),
|
container: NewContainer(c.container),
|
||||||
events: c.events,
|
events: c.events,
|
||||||
router: c.router,
|
router: c.router,
|
||||||
migrations: c.migrations,
|
migrations: c.migrations,
|
||||||
tasks: c.tasks,
|
tasks: c.tasks,
|
||||||
schedules: c.schedules,
|
schedules: c.schedules,
|
||||||
settings: c.settings,
|
settings: c.settings,
|
||||||
config: c.config,
|
config: c.config,
|
||||||
values: make(map[any]any),
|
values: make(map[any]any),
|
||||||
|
migrationBaseline: c.MigrationBaseline(),
|
||||||
}
|
}
|
||||||
|
|
||||||
c.mu.Lock()
|
c.mu.Lock()
|
||||||
@@ -208,6 +210,33 @@ func (c *Context) Migrations() extpoints.MigrationExtension {
|
|||||||
return c.migrations
|
return c.migrations
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// MigrationBaseline returns the hook copied onto this Context during App.Prepare.
|
||||||
|
// Child contexts fall back to their parent so forks still see the root hook.
|
||||||
|
func (c *Context) MigrationBaseline() func(*Context) error {
|
||||||
|
if c == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
c.mu.RLock()
|
||||||
|
fn := c.migrationBaseline
|
||||||
|
c.mu.RUnlock()
|
||||||
|
if fn != nil {
|
||||||
|
return fn
|
||||||
|
}
|
||||||
|
if c.parent != nil {
|
||||||
|
return c.parent.MigrationBaseline()
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Context) setMigrationBaseline(fn func(*Context) error) {
|
||||||
|
if c == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.mu.Lock()
|
||||||
|
c.migrationBaseline = fn
|
||||||
|
c.mu.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
// Tasks returns the scoped TaskExtension registry with automatic disposer tracking.
|
// Tasks returns the scoped TaskExtension registry with automatic disposer tracking.
|
||||||
func (c *Context) Tasks() extpoints.TaskExtension {
|
func (c *Context) Tasks() extpoints.TaskExtension {
|
||||||
return newScopedTaskExtension(c, c.tasks)
|
return newScopedTaskExtension(c, c.tasks)
|
||||||
|
|||||||
@@ -0,0 +1,12 @@
|
|||||||
|
// Copyright 2026 Arctel.net
|
||||||
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
|
|
||||||
|
package contracts
|
||||||
|
|
||||||
|
// CaptchaService defines the contract for CAPTCHA challenge issuance,
|
||||||
|
// redemption, and scoped verification middleware.
|
||||||
|
type CaptchaService interface {
|
||||||
|
VerifyMiddleware(scope string) any
|
||||||
|
ChallengeHandler() any
|
||||||
|
RedeemHandler() any
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
// Copyright 2026 Arctel.net
|
||||||
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
|
|
||||||
|
package contracts
|
||||||
|
|
||||||
|
import "context"
|
||||||
|
|
||||||
|
// PublicConfigProvider supplies the payload for GET /api/v1/config/public
|
||||||
|
// when a downstream plugin replaces Wavelet's default {configs, app} JSON.
|
||||||
|
type PublicConfigProvider interface {
|
||||||
|
PublicConfig(ctx context.Context) (any, error)
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
// 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"
|
||||||
|
|
||||||
|
type PushNotificationTemplate struct {
|
||||||
|
Title string
|
||||||
|
Content string
|
||||||
|
Level string
|
||||||
|
Ext map[string]any
|
||||||
|
}
|
||||||
|
|
||||||
|
type PushEventMeta struct {
|
||||||
|
Key string
|
||||||
|
Name string
|
||||||
|
Description string
|
||||||
|
DefaultTemplate PushNotificationTemplate
|
||||||
|
}
|
||||||
|
|
||||||
|
type PushRegistry interface {
|
||||||
|
RegisterBuiltInEvent(meta PushEventMeta)
|
||||||
|
SyncEvents(ctx context.Context) error
|
||||||
|
}
|
||||||
@@ -180,6 +180,13 @@ func formatEntryValue(value any, secret bool) string {
|
|||||||
if value == nil {
|
if value == nil {
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
rv := reflect.ValueOf(value)
|
||||||
|
if rv.Kind() == reflect.Ptr {
|
||||||
|
if rv.IsNil() {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return fmt.Sprint(rv.Elem().Interface())
|
||||||
|
}
|
||||||
return fmt.Sprint(value)
|
return fmt.Sprint(value)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -224,6 +224,54 @@ func TestEntriesRedactSecretsAndReportDefaults(t *testing.T) {
|
|||||||
assert.Equal(t, "86400", entries["app.session_age"].Value)
|
assert.Equal(t, "86400", entries["app.session_age"].Value)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type optionalBoolConfig struct {
|
||||||
|
RedirectTrailingSlash *bool `config:"redirect_trailing_slash" env:"APP_REDIRECT_TRAILING_SLASH"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBindBoolPointerFromFileAndEnv(t *testing.T) {
|
||||||
|
t.Run("absent stays nil", func(t *testing.T) {
|
||||||
|
r := extpoints.NewConfigRegistry(newFakeSource())
|
||||||
|
require.NoError(t, r.Declare("driver_http", extpoints.ConfigBinding{Prefix: "app", Target: &optionalBoolConfig{}}))
|
||||||
|
require.NoError(t, r.Resolve())
|
||||||
|
|
||||||
|
var got optionalBoolConfig
|
||||||
|
require.NoError(t, r.Bind("app", &got))
|
||||||
|
assert.Nil(t, got.RedirectTrailingSlash)
|
||||||
|
assert.Equal(t, "", r.Origin("app.redirect_trailing_slash"))
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("file false", func(t *testing.T) {
|
||||||
|
src := newFakeSource()
|
||||||
|
src.values["app.redirect_trailing_slash"] = false
|
||||||
|
|
||||||
|
r := extpoints.NewConfigRegistry(src)
|
||||||
|
require.NoError(t, r.Declare("driver_http", extpoints.ConfigBinding{Prefix: "app", Target: &optionalBoolConfig{}}))
|
||||||
|
require.NoError(t, r.Resolve())
|
||||||
|
|
||||||
|
var got optionalBoolConfig
|
||||||
|
require.NoError(t, r.Bind("app", &got))
|
||||||
|
require.NotNil(t, got.RedirectTrailingSlash)
|
||||||
|
assert.False(t, *got.RedirectTrailingSlash)
|
||||||
|
assert.Equal(t, extpoints.OriginFile, r.Origin("app.redirect_trailing_slash"))
|
||||||
|
assert.False(t, r.Bool("app.redirect_trailing_slash", true))
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("env false", func(t *testing.T) {
|
||||||
|
src := newFakeSource()
|
||||||
|
src.env["APP_REDIRECT_TRAILING_SLASH"] = "false"
|
||||||
|
|
||||||
|
r := extpoints.NewConfigRegistry(src)
|
||||||
|
require.NoError(t, r.Declare("driver_http", extpoints.ConfigBinding{Prefix: "app", Target: &optionalBoolConfig{}}))
|
||||||
|
require.NoError(t, r.Resolve())
|
||||||
|
|
||||||
|
var got optionalBoolConfig
|
||||||
|
require.NoError(t, r.Bind("app", &got))
|
||||||
|
require.NotNil(t, got.RedirectTrailingSlash)
|
||||||
|
assert.False(t, *got.RedirectTrailingSlash)
|
||||||
|
assert.Equal(t, extpoints.OriginEnv, r.Origin("app.redirect_trailing_slash"))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
func TestBindRejectsReadsBeforeSourceIsRegistered(t *testing.T) {
|
func TestBindRejectsReadsBeforeSourceIsRegistered(t *testing.T) {
|
||||||
r := extpoints.NewConfigRegistry(nil)
|
r := extpoints.NewConfigRegistry(nil)
|
||||||
require.NoError(t, r.Declare("cache", extpoints.ConfigBinding{Prefix: "redis", Target: &redisConfig{}}))
|
require.NoError(t, r.Declare("cache", extpoints.ConfigBinding{Prefix: "redis", Target: &redisConfig{}}))
|
||||||
|
|||||||
@@ -33,15 +33,38 @@ func convertValue(raw any, typ reflect.Type) (any, error) {
|
|||||||
return convertSlice(raw, typ)
|
return convertSlice(raw, typ)
|
||||||
case reflect.Struct:
|
case reflect.Struct:
|
||||||
return convertStruct(raw, typ)
|
return convertStruct(raw, typ)
|
||||||
|
case reflect.Ptr:
|
||||||
|
return convertPointer(raw, typ)
|
||||||
default:
|
default:
|
||||||
return nil, fmt.Errorf("%w: %s is not a supported configuration type", ErrConfigType, typ)
|
return nil, fmt.Errorf("%w: %s is not a supported configuration type", ErrConfigType, typ)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// convertPointer decodes into the element type and returns a non-nil pointer to it.
|
||||||
|
// Nested pointers are rejected so configuration tags stay one level deep.
|
||||||
|
func convertPointer(raw any, typ reflect.Type) (any, error) {
|
||||||
|
elemType := typ.Elem()
|
||||||
|
if elemType.Kind() == reflect.Ptr {
|
||||||
|
return nil, fmt.Errorf("%w: %s is not a supported configuration type", ErrConfigType, typ)
|
||||||
|
}
|
||||||
|
elem, err := convertValue(raw, elemType)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
ptr := reflect.New(elemType)
|
||||||
|
ptr.Elem().Set(reflect.ValueOf(elem))
|
||||||
|
return ptr.Interface(), nil
|
||||||
|
}
|
||||||
|
|
||||||
func convertBool(raw any) (any, error) {
|
func convertBool(raw any) (any, error) {
|
||||||
switch v := raw.(type) {
|
switch v := raw.(type) {
|
||||||
case bool:
|
case bool:
|
||||||
return v, nil
|
return v, nil
|
||||||
|
case *bool:
|
||||||
|
if v == nil {
|
||||||
|
return nil, fmt.Errorf("%w: nil *bool is not a boolean", ErrConfigType)
|
||||||
|
}
|
||||||
|
return *v, nil
|
||||||
case string:
|
case string:
|
||||||
parsed, err := strconv.ParseBool(strings.TrimSpace(v))
|
parsed, err := strconv.ParseBool(strings.TrimSpace(v))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -1,12 +1,7 @@
|
|||||||
// Copyright 2026 Arctel.net
|
|
||||||
// SPDX-License-Identifier: Apache-2.0
|
|
||||||
|
|
||||||
package extpoints
|
package extpoints
|
||||||
|
|
||||||
import "testing"
|
import "testing"
|
||||||
|
|
||||||
// TestHandleRawPreservesTrailingSlash 验证 HandleRaw 能表达 /x 与 /x/ 两条不同路由,
|
|
||||||
// 而 Handle 会归一化掉尾部斜杠(server 插件的 list 端点历史行为依赖这一点)。
|
|
||||||
func TestHandleRawPreservesTrailingSlash(t *testing.T) {
|
func TestHandleRawPreservesTrailingSlash(t *testing.T) {
|
||||||
r := &RouterRegistry{}
|
r := &RouterRegistry{}
|
||||||
g := r.Group("/api/v1/nodes")
|
g := r.Group("/api/v1/nodes")
|
||||||
@@ -24,29 +19,9 @@ func TestHandleRawPreservesTrailingSlash(t *testing.T) {
|
|||||||
t.Errorf("HandleRaw(\"/\") path = %q, want %q", slashed.Path, "/api/v1/nodes/")
|
t.Errorf("HandleRaw(\"/\") path = %q, want %q", slashed.Path, "/api/v1/nodes/")
|
||||||
}
|
}
|
||||||
if slashed.ID == slashless.ID {
|
if slashed.ID == slashless.ID {
|
||||||
t.Error("HandleRaw must allocate its own route ID so scoped teardown can unregister both")
|
t.Error("HandleRaw must allocate its own route ID")
|
||||||
}
|
}
|
||||||
if got := len(r.Routes()); got != 2 {
|
if got := len(r.Routes()); got != 2 {
|
||||||
t.Errorf("registry routes = %d, want 2", got)
|
t.Errorf("registry routes = %d, want 2", got)
|
||||||
}
|
}
|
||||||
if !r.UnregisterByID(slashed.ID) {
|
|
||||||
t.Error("UnregisterByID(HandleRaw route) = false, want true")
|
|
||||||
}
|
|
||||||
if got := len(r.Routes()); got != 1 {
|
|
||||||
t.Errorf("routes after unregister = %d, want 1", got)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestRegistryHandleRawKeepsAbsolutePath 根注册表上 HandleRaw 只做绝对化处理。
|
|
||||||
func TestRegistryHandleRawKeepsAbsolutePath(t *testing.T) {
|
|
||||||
r := &RouterRegistry{}
|
|
||||||
if got := r.HandleRaw("GET", "/health/").Path; got != "/health/" {
|
|
||||||
t.Errorf("path = %q, want %q", got, "/health/")
|
|
||||||
}
|
|
||||||
if got := r.HandleRaw("POST", "submit").Path; got != "/submit" {
|
|
||||||
t.Errorf("path = %q, want %q", got, "/submit")
|
|
||||||
}
|
|
||||||
if got := r.BasePath(); got != "" {
|
|
||||||
t.Errorf("registry BasePath() = %q, want empty", got)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
Vendored
+7
-28
@@ -143,10 +143,7 @@ func (c *Cache) Set(key string, value []byte, ttl time.Duration) error {
|
|||||||
|
|
||||||
// Update memory tracker
|
// Update memory tracker
|
||||||
if elem, ok := c.items[key]; ok {
|
if elem, ok := c.items[key]; ok {
|
||||||
item, ok := elem.Value.(*cacheItem)
|
item := elem.Value.(*cacheItem)
|
||||||
if !ok {
|
|
||||||
return fmt.Errorf("cache: evict list entry for %q has invalid type %T", key, elem.Value)
|
|
||||||
}
|
|
||||||
c.currentSize += size - item.size
|
c.currentSize += size - item.size
|
||||||
item.size = size
|
item.size = size
|
||||||
item.expiredAt = expiredAt
|
item.expiredAt = expiredAt
|
||||||
@@ -177,11 +174,7 @@ func (c *Cache) Get(key string) ([]byte, error) {
|
|||||||
return nil, ErrCacheMiss
|
return nil, ErrCacheMiss
|
||||||
}
|
}
|
||||||
|
|
||||||
item, ok := elem.Value.(*cacheItem)
|
item := elem.Value.(*cacheItem)
|
||||||
if !ok {
|
|
||||||
c.mu.RUnlock()
|
|
||||||
return nil, ErrCacheMiss
|
|
||||||
}
|
|
||||||
if !item.expiredAt.IsZero() && time.Now().After(item.expiredAt) {
|
if !item.expiredAt.IsZero() && time.Now().After(item.expiredAt) {
|
||||||
c.mu.RUnlock()
|
c.mu.RUnlock()
|
||||||
return c.getAndDeleteIfExpired(key)
|
return c.getAndDeleteIfExpired(key)
|
||||||
@@ -231,11 +224,7 @@ func (c *Cache) getAndDeleteIfExpired(key string) ([]byte, error) {
|
|||||||
return nil, ErrCacheMiss
|
return nil, ErrCacheMiss
|
||||||
}
|
}
|
||||||
|
|
||||||
item, ok := elem.Value.(*cacheItem)
|
item := elem.Value.(*cacheItem)
|
||||||
if !ok {
|
|
||||||
_ = c.deleteUnlocked(key)
|
|
||||||
return nil, ErrCacheMiss
|
|
||||||
}
|
|
||||||
if !item.expiredAt.IsZero() && time.Now().After(item.expiredAt) {
|
if !item.expiredAt.IsZero() && time.Now().After(item.expiredAt) {
|
||||||
_ = c.deleteUnlocked(key)
|
_ = c.deleteUnlocked(key)
|
||||||
return nil, ErrCacheMiss
|
return nil, ErrCacheMiss
|
||||||
@@ -265,9 +254,8 @@ func (c *Cache) Delete(key string) error {
|
|||||||
|
|
||||||
func (c *Cache) deleteUnlocked(key string) error {
|
func (c *Cache) deleteUnlocked(key string) error {
|
||||||
if elem, ok := c.items[key]; ok {
|
if elem, ok := c.items[key]; ok {
|
||||||
if item, ok := elem.Value.(*cacheItem); ok {
|
item := elem.Value.(*cacheItem)
|
||||||
c.currentSize -= item.size
|
c.currentSize -= item.size
|
||||||
}
|
|
||||||
c.evictList.Remove(elem)
|
c.evictList.Remove(elem)
|
||||||
delete(c.items, key)
|
delete(c.items, key)
|
||||||
}
|
}
|
||||||
@@ -320,11 +308,7 @@ func (c *Cache) evict() {
|
|||||||
|
|
||||||
for c.currentSize > c.maxSize && c.evictList.Len() > 0 {
|
for c.currentSize > c.maxSize && c.evictList.Len() > 0 {
|
||||||
elem := c.evictList.Back()
|
elem := c.evictList.Back()
|
||||||
item, ok := elem.Value.(*cacheItem)
|
item := elem.Value.(*cacheItem)
|
||||||
if !ok {
|
|
||||||
c.evictList.Remove(elem)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
c.currentSize -= item.size
|
c.currentSize -= item.size
|
||||||
c.evictList.Remove(elem)
|
c.evictList.Remove(elem)
|
||||||
delete(c.items, item.key)
|
delete(c.items, item.key)
|
||||||
@@ -416,12 +400,7 @@ func (c *Cache) cleanExpired() {
|
|||||||
|
|
||||||
now := time.Now()
|
now := time.Now()
|
||||||
for key, elem := range c.items {
|
for key, elem := range c.items {
|
||||||
item, ok := elem.Value.(*cacheItem)
|
item := elem.Value.(*cacheItem)
|
||||||
if !ok {
|
|
||||||
c.evictList.Remove(elem)
|
|
||||||
delete(c.items, key)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if !item.expiredAt.IsZero() && now.After(item.expiredAt) {
|
if !item.expiredAt.IsZero() && now.After(item.expiredAt) {
|
||||||
c.currentSize -= item.size
|
c.currentSize -= item.size
|
||||||
c.evictList.Remove(elem)
|
c.evictList.Remove(elem)
|
||||||
|
|||||||
-63
@@ -1,63 +0,0 @@
|
|||||||
// Copyright 2026 Arctel.net
|
|
||||||
// SPDX-License-Identifier: Apache-2.0
|
|
||||||
|
|
||||||
package disk
|
|
||||||
|
|
||||||
import (
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/stretchr/testify/require"
|
|
||||||
)
|
|
||||||
|
|
||||||
// 这些用例锁住「LRU 链表节点被污染时不得 panic」的行为:一旦 items 与 evictList
|
|
||||||
// 的不变量被破坏(例如后续改动误写节点),缓存必须降级为未命中/跳过,
|
|
||||||
// 而不是在读、写、删除与淘汰路径上崩掉整个进程。
|
|
||||||
|
|
||||||
// corruptEntry 写入一个键后把其链表节点值换成非法类型,返回缓存。
|
|
||||||
func corruptEntry(t *testing.T, key string) *Cache {
|
|
||||||
t.Helper()
|
|
||||||
|
|
||||||
c := New(t.TempDir())
|
|
||||||
require.NoError(t, c.Set(key, []byte("payload"), time.Minute))
|
|
||||||
|
|
||||||
elem, ok := c.items[key]
|
|
||||||
require.True(t, ok, "entry must be tracked after Set")
|
|
||||||
elem.Value = "not-a-cacheItem"
|
|
||||||
return c
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestGetToleratesCorruptEvictEntry(t *testing.T) {
|
|
||||||
c := corruptEntry(t, "k")
|
|
||||||
|
|
||||||
got, err := c.Get("k")
|
|
||||||
require.ErrorIs(t, err, ErrCacheMiss)
|
|
||||||
require.Nil(t, got)
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestSetOverCorruptEvictEntryReportsError(t *testing.T) {
|
|
||||||
c := corruptEntry(t, "k")
|
|
||||||
|
|
||||||
err := c.Set("k", []byte("second"), time.Minute)
|
|
||||||
require.Error(t, err, "Set must report the corrupted tracker entry instead of panicking")
|
|
||||||
require.Contains(t, err.Error(), "invalid type")
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestDeleteToleratesCorruptEvictEntry(t *testing.T) {
|
|
||||||
c := corruptEntry(t, "k")
|
|
||||||
|
|
||||||
require.NotPanics(t, func() { _ = c.Delete("k") })
|
|
||||||
require.NotContains(t, c.items, "k")
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestEvictToleratesCorruptEvictEntry(t *testing.T) {
|
|
||||||
c := corruptEntry(t, "k")
|
|
||||||
// 让任意写入都触发淘汰扫描:扫到被污染的节点必须跳过而非 panic。
|
|
||||||
c.UpdatePolicy(0, 0, true)
|
|
||||||
|
|
||||||
require.NotPanics(t, func() {
|
|
||||||
for i := range 4 {
|
|
||||||
_ = c.Set(string(rune('a'+i)), []byte("x"), time.Minute)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
@@ -1,70 +0,0 @@
|
|||||||
// Copyright 2026 Arctel.net
|
|
||||||
// SPDX-License-Identifier: Apache-2.0
|
|
||||||
|
|
||||||
// Package util provides shared formatting and string helper functions.
|
|
||||||
package util
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"strconv"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
secondsPerYear = 31104000 // 360 days
|
|
||||||
secondsPerMonth = 2592000 // 30 days
|
|
||||||
secondsPerDay = 86400
|
|
||||||
secondsPerHour = 3600
|
|
||||||
secondsPerMinute = 60
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
sizeKB = 1024
|
|
||||||
sizeMB = sizeKB * 1024
|
|
||||||
sizeGB = sizeMB * 1024
|
|
||||||
)
|
|
||||||
|
|
||||||
// Bytes2Size converts a byte count to a human-readable string with unit (B, KB, MB, GB).
|
|
||||||
func Bytes2Size(num int64) string {
|
|
||||||
var numStr string
|
|
||||||
unit := "B"
|
|
||||||
switch {
|
|
||||||
case num/int64(sizeGB) >= 1:
|
|
||||||
numStr = fmt.Sprintf("%.2f", float64(num)/float64(sizeGB))
|
|
||||||
unit = "GB"
|
|
||||||
case num/int64(sizeMB) >= 1:
|
|
||||||
numStr = strconv.Itoa(int(float64(num) / float64(sizeMB)))
|
|
||||||
unit = "MB"
|
|
||||||
case num/int64(sizeKB) >= 1:
|
|
||||||
numStr = strconv.Itoa(int(float64(num) / float64(sizeKB)))
|
|
||||||
unit = "KB"
|
|
||||||
default:
|
|
||||||
numStr = strconv.FormatInt(num, 10)
|
|
||||||
}
|
|
||||||
return numStr + " " + unit
|
|
||||||
}
|
|
||||||
|
|
||||||
// Seconds2Time converts a number of seconds to a human-readable Chinese duration string.
|
|
||||||
func Seconds2Time(num int) (time string) {
|
|
||||||
if num/secondsPerYear > 0 {
|
|
||||||
time += strconv.Itoa(num/secondsPerYear) + " 年 "
|
|
||||||
num %= secondsPerYear
|
|
||||||
}
|
|
||||||
if num/secondsPerMonth > 0 {
|
|
||||||
time += strconv.Itoa(num/secondsPerMonth) + " 个月 "
|
|
||||||
num %= secondsPerMonth
|
|
||||||
}
|
|
||||||
if num/secondsPerDay > 0 {
|
|
||||||
time += strconv.Itoa(num/secondsPerDay) + " 天 "
|
|
||||||
num %= secondsPerDay
|
|
||||||
}
|
|
||||||
if num/secondsPerHour > 0 {
|
|
||||||
time += strconv.Itoa(num/secondsPerHour) + " 小时 "
|
|
||||||
num %= secondsPerHour
|
|
||||||
}
|
|
||||||
if num/secondsPerMinute > 0 {
|
|
||||||
time += strconv.Itoa(num/secondsPerMinute) + " 分钟 "
|
|
||||||
num %= secondsPerMinute
|
|
||||||
}
|
|
||||||
time += strconv.Itoa(num) + " 秒"
|
|
||||||
return
|
|
||||||
}
|
|
||||||
@@ -1,52 +0,0 @@
|
|||||||
// Copyright 2026 Arctel.net
|
|
||||||
// SPDX-License-Identifier: Apache-2.0
|
|
||||||
|
|
||||||
package util
|
|
||||||
|
|
||||||
import (
|
|
||||||
"testing"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestBytes2Size(t *testing.T) {
|
|
||||||
tests := []struct {
|
|
||||||
input int64
|
|
||||||
expected string
|
|
||||||
}{
|
|
||||||
{0, "0 B"},
|
|
||||||
{500, "500 B"},
|
|
||||||
{1023, "1023 B"},
|
|
||||||
{1024, "1 KB"},
|
|
||||||
{2048, "2 KB"},
|
|
||||||
{1024 * 1024, "1 MB"},
|
|
||||||
{1024 * 1024 * 1024, "1.00 GB"},
|
|
||||||
{1024 * 1024 * 1024 * 2, "2.00 GB"},
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, tt := range tests {
|
|
||||||
result := Bytes2Size(tt.input)
|
|
||||||
if result != tt.expected {
|
|
||||||
t.Errorf("Bytes2Size(%d) = %q, expected %q", tt.input, result, tt.expected)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestSeconds2Time(t *testing.T) {
|
|
||||||
tests := []struct {
|
|
||||||
input int
|
|
||||||
expected string
|
|
||||||
}{
|
|
||||||
{0, "0 秒"},
|
|
||||||
{30, "30 秒"},
|
|
||||||
{60, "1 分钟 0 秒"},
|
|
||||||
{125, "2 分钟 5 秒"},
|
|
||||||
{3600, "1 小时 0 秒"},
|
|
||||||
{86400, "1 天 0 秒"},
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, tt := range tests {
|
|
||||||
result := Seconds2Time(tt.input)
|
|
||||||
if result != tt.expected {
|
|
||||||
t.Errorf("Seconds2Time(%d) = %q, expected %q", tt.input, result, tt.expected)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,45 +0,0 @@
|
|||||||
// Copyright 2026 Arctel.net
|
|
||||||
// SPDX-License-Identifier: Apache-2.0
|
|
||||||
|
|
||||||
package util
|
|
||||||
|
|
||||||
import (
|
|
||||||
"log/slog"
|
|
||||||
"net"
|
|
||||||
)
|
|
||||||
|
|
||||||
// GetIP returns the first private IPv4 address found on the local network interfaces.
|
|
||||||
func GetIP() (ip string) {
|
|
||||||
ips, err := net.InterfaceAddrs()
|
|
||||||
if err != nil {
|
|
||||||
slog.Error("get interface addresses failed", "error", err)
|
|
||||||
return ip
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, a := range ips {
|
|
||||||
if candidate, ok := privateIPv4FromAddr(a); ok {
|
|
||||||
return candidate
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
func privateIPv4FromAddr(addr net.Addr) (string, bool) {
|
|
||||||
ipNet, ok := addr.(*net.IPNet)
|
|
||||||
if !ok || ipNet.IP.IsLoopback() || ipNet.IP.To4() == nil {
|
|
||||||
return "", false
|
|
||||||
}
|
|
||||||
ip := ipNet.IP.String()
|
|
||||||
if isPrivateIPv4(ip) {
|
|
||||||
return ip, true
|
|
||||||
}
|
|
||||||
return "", false
|
|
||||||
}
|
|
||||||
|
|
||||||
func isPrivateIPv4(ip string) bool {
|
|
||||||
parsedIP := net.ParseIP(ip)
|
|
||||||
if parsedIP == nil {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
return parsedIP.IsPrivate()
|
|
||||||
}
|
|
||||||
@@ -1,36 +0,0 @@
|
|||||||
// Copyright 2026 Arctel.net
|
|
||||||
// SPDX-License-Identifier: Apache-2.0
|
|
||||||
|
|
||||||
package util
|
|
||||||
|
|
||||||
import (
|
|
||||||
"testing"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestIsPrivateIPv4(t *testing.T) {
|
|
||||||
tests := []struct {
|
|
||||||
ip string
|
|
||||||
expected bool
|
|
||||||
}{
|
|
||||||
{"127.0.0.1", false}, // Loopback is not in RFC 1918 private range
|
|
||||||
{"10.0.0.1", true},
|
|
||||||
{"172.16.0.1", true},
|
|
||||||
{"192.168.1.1", true},
|
|
||||||
{"8.8.8.8", false},
|
|
||||||
{"invalid-ip", false},
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, tt := range tests {
|
|
||||||
result := isPrivateIPv4(tt.ip)
|
|
||||||
if result != tt.expected {
|
|
||||||
t.Errorf("isPrivateIPv4(%q) = %v, expected %v", tt.ip, result, tt.expected)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestGetIP(t *testing.T) {
|
|
||||||
ip := GetIP()
|
|
||||||
// GetIP should return empty if no private IPv4 address is configured, or a valid IP.
|
|
||||||
// We just ensure it doesn't panic.
|
|
||||||
t.Logf("GetIP returned: %q", ip)
|
|
||||||
}
|
|
||||||
@@ -1,79 +0,0 @@
|
|||||||
// Copyright 2026 Arctel.net
|
|
||||||
// SPDX-License-Identifier: Apache-2.0
|
|
||||||
|
|
||||||
package util
|
|
||||||
|
|
||||||
import (
|
|
||||||
"sort"
|
|
||||||
"strings"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Unique returns a new slice containing only the unique elements of the input slice,
|
|
||||||
// preserving their original order.
|
|
||||||
func Unique[T comparable](slice []T) []T {
|
|
||||||
if slice == nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
seen := make(map[T]struct{})
|
|
||||||
result := make([]T, 0)
|
|
||||||
for _, item := range slice {
|
|
||||||
if _, ok := seen[item]; ok {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
seen[item] = struct{}{}
|
|
||||||
result = append(result, item)
|
|
||||||
}
|
|
||||||
return result
|
|
||||||
}
|
|
||||||
|
|
||||||
// UniqueAndCleanStringSlice trims spaces, removes empty elements, and returns only the unique elements
|
|
||||||
// of the input string slice. It preserves order and returns nil if the resulting slice is empty.
|
|
||||||
func UniqueAndCleanStringSlice(slice []string) []string {
|
|
||||||
if slice == nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
seen := make(map[string]struct{})
|
|
||||||
result := make([]string, 0)
|
|
||||||
for _, item := range slice {
|
|
||||||
trimmed := strings.TrimSpace(item)
|
|
||||||
if trimmed == "" {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if _, ok := seen[trimmed]; ok {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
seen[trimmed] = struct{}{}
|
|
||||||
result = append(result, trimmed)
|
|
||||||
}
|
|
||||||
if len(result) == 0 {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return result
|
|
||||||
}
|
|
||||||
|
|
||||||
// IdentifiableTimeRecord represents a database record that has a unique ID and a primary timestamp field.
|
|
||||||
type IdentifiableTimeRecord interface {
|
|
||||||
GetID() uint
|
|
||||||
GetTime() time.Time
|
|
||||||
}
|
|
||||||
|
|
||||||
// SortAndLimitRecords sorts a slice of IdentifiableTimeRecord descendingly by their timestamp (and ID as a tie-breaker),
|
|
||||||
// and limits the slice to the specified size if limit > 0.
|
|
||||||
func SortAndLimitRecords[T IdentifiableTimeRecord](rows []T, limit int) []T {
|
|
||||||
if len(rows) == 0 {
|
|
||||||
return rows
|
|
||||||
}
|
|
||||||
sort.Slice(rows, func(i, j int) bool {
|
|
||||||
ti := rows[i].GetTime()
|
|
||||||
tj := rows[j].GetTime()
|
|
||||||
if ti.Equal(tj) {
|
|
||||||
return rows[i].GetID() > rows[j].GetID()
|
|
||||||
}
|
|
||||||
return ti.After(tj)
|
|
||||||
})
|
|
||||||
if limit > 0 && len(rows) > limit {
|
|
||||||
rows = rows[:limit]
|
|
||||||
}
|
|
||||||
return rows
|
|
||||||
}
|
|
||||||
@@ -1,15 +0,0 @@
|
|||||||
// Copyright 2026 Arctel.net
|
|
||||||
// SPDX-License-Identifier: Apache-2.0
|
|
||||||
|
|
||||||
package util
|
|
||||||
|
|
||||||
import "strings"
|
|
||||||
|
|
||||||
// TrimStringFields trims leading and trailing spaces from all provided string pointers.
|
|
||||||
func TrimStringFields(fields ...*string) {
|
|
||||||
for _, f := range fields {
|
|
||||||
if f != nil {
|
|
||||||
*f = strings.TrimSpace(*f)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
// Copyright 2026 Arctel.net
|
|
||||||
// SPDX-License-Identifier: Apache-2.0
|
|
||||||
|
|
||||||
package util
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"strconv"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Interface2String converts a string, int, or float64 value to its string representation.
|
|
||||||
func Interface2String(inter any) string {
|
|
||||||
switch v := inter.(type) {
|
|
||||||
case string:
|
|
||||||
return v
|
|
||||||
case int:
|
|
||||||
return strconv.Itoa(v)
|
|
||||||
case float64:
|
|
||||||
return fmt.Sprintf("%f", v)
|
|
||||||
}
|
|
||||||
return "Not Implemented"
|
|
||||||
}
|
|
||||||
@@ -1,129 +0,0 @@
|
|||||||
// Copyright 2026 Arctel.net
|
|
||||||
// SPDX-License-Identifier: Apache-2.0
|
|
||||||
|
|
||||||
package util
|
|
||||||
|
|
||||||
import (
|
|
||||||
"strconv"
|
|
||||||
"strings"
|
|
||||||
)
|
|
||||||
|
|
||||||
const gitDescribeMinIdentifiers = 2
|
|
||||||
|
|
||||||
// VersionInfo holds the parsed components of a semantic version string.
|
|
||||||
type VersionInfo struct {
|
|
||||||
Valid bool
|
|
||||||
IsDev bool
|
|
||||||
Numbers []int
|
|
||||||
Prerelease []string
|
|
||||||
GitDescribeDistance int
|
|
||||||
GitDescribeTail []string
|
|
||||||
}
|
|
||||||
|
|
||||||
// ParseVersionInfo parses a version string into a structured VersionInfo.
|
|
||||||
func ParseVersionInfo(version string) VersionInfo {
|
|
||||||
normalized := strings.TrimSpace(strings.TrimPrefix(version, "v"))
|
|
||||||
if normalized == "" || normalized == "dev" {
|
|
||||||
return VersionInfo{IsDev: strings.EqualFold(normalized, "dev")}
|
|
||||||
}
|
|
||||||
base := normalized
|
|
||||||
prerelease := ""
|
|
||||||
if separator := strings.IndexRune(normalized, '-'); separator >= 0 {
|
|
||||||
base = normalized[:separator]
|
|
||||||
prerelease = normalized[separator+1:]
|
|
||||||
}
|
|
||||||
|
|
||||||
segments := strings.Split(base, ".")
|
|
||||||
parts := make([]int, 0, len(segments))
|
|
||||||
for _, segment := range segments {
|
|
||||||
segment = strings.TrimSpace(segment)
|
|
||||||
if segment == "" {
|
|
||||||
parts = append(parts, 0)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
numeric := strings.Builder{}
|
|
||||||
for _, r := range segment {
|
|
||||||
if r < '0' || r > '9' {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
numeric.WriteRune(r)
|
|
||||||
}
|
|
||||||
if numeric.Len() == 0 {
|
|
||||||
parts = append(parts, 0)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
value, err := strconv.Atoi(numeric.String())
|
|
||||||
if err != nil {
|
|
||||||
return VersionInfo{}
|
|
||||||
}
|
|
||||||
parts = append(parts, value)
|
|
||||||
}
|
|
||||||
info := VersionInfo{Valid: len(parts) > 0, Numbers: parts}
|
|
||||||
if prerelease != "" {
|
|
||||||
identifiers := splitPrereleaseIdentifiers(prerelease)
|
|
||||||
if distance, tail, ok := parseGitDescribeIdentifiers(identifiers); ok {
|
|
||||||
info.GitDescribeDistance = distance
|
|
||||||
info.GitDescribeTail = tail
|
|
||||||
} else {
|
|
||||||
info.Prerelease = identifiers
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return info
|
|
||||||
}
|
|
||||||
|
|
||||||
func parseGitDescribeIdentifiers(identifiers []string) (int, []string, bool) {
|
|
||||||
if len(identifiers) < gitDescribeMinIdentifiers {
|
|
||||||
return 0, nil, false
|
|
||||||
}
|
|
||||||
distance, err := strconv.Atoi(strings.TrimSpace(identifiers[0]))
|
|
||||||
if err != nil || distance <= 0 {
|
|
||||||
return 0, nil, false
|
|
||||||
}
|
|
||||||
commitToken := strings.TrimSpace(identifiers[1])
|
|
||||||
if commitToken == "" || !strings.HasPrefix(strings.ToLower(commitToken), "g") {
|
|
||||||
return 0, nil, false
|
|
||||||
}
|
|
||||||
return distance, identifiers[1:], true
|
|
||||||
}
|
|
||||||
|
|
||||||
func splitPrereleaseIdentifiers(value string) []string {
|
|
||||||
parts := strings.FieldsFunc(strings.TrimSpace(value), func(r rune) bool {
|
|
||||||
return r == '.' || r == '-'
|
|
||||||
})
|
|
||||||
filtered := make([]string, 0, len(parts))
|
|
||||||
for _, part := range parts {
|
|
||||||
part = strings.TrimSpace(part)
|
|
||||||
if part != "" {
|
|
||||||
filtered = append(filtered, part)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return filtered
|
|
||||||
}
|
|
||||||
|
|
||||||
// CompareVersions compares two version strings.
|
|
||||||
// Returns -1 if left < right, 1 if left > right, and 0 if they are equal.
|
|
||||||
func CompareVersions(local, remote string) int {
|
|
||||||
left := ParseVersionInfo(local)
|
|
||||||
right := ParseVersionInfo(remote)
|
|
||||||
if left.IsDev {
|
|
||||||
if right.Valid {
|
|
||||||
return -1
|
|
||||||
}
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
if !left.Valid || !right.Valid {
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
|
|
||||||
if result := compareVersionNumbers(left, right); result != 0 {
|
|
||||||
return result
|
|
||||||
}
|
|
||||||
if result := compareGitDescribeDistance(left, right); result != 0 {
|
|
||||||
return result
|
|
||||||
}
|
|
||||||
if left.GitDescribeDistance > 0 || right.GitDescribeDistance > 0 {
|
|
||||||
return compareGitDescribeTails(left, right)
|
|
||||||
}
|
|
||||||
return comparePrereleaseIdentifiers(left, right)
|
|
||||||
}
|
|
||||||
@@ -1,108 +0,0 @@
|
|||||||
// Copyright 2026 Arctel.net
|
|
||||||
// SPDX-License-Identifier: Apache-2.0
|
|
||||||
|
|
||||||
package util
|
|
||||||
|
|
||||||
import "strconv"
|
|
||||||
|
|
||||||
func compareVersionNumbers(left, right VersionInfo) int {
|
|
||||||
maxLen := max(len(right.Numbers), len(left.Numbers))
|
|
||||||
for index := range maxLen {
|
|
||||||
leftValue := 0
|
|
||||||
rightValue := 0
|
|
||||||
if index < len(left.Numbers) {
|
|
||||||
leftValue = left.Numbers[index]
|
|
||||||
}
|
|
||||||
if index < len(right.Numbers) {
|
|
||||||
rightValue = right.Numbers[index]
|
|
||||||
}
|
|
||||||
if leftValue < rightValue {
|
|
||||||
return -1
|
|
||||||
}
|
|
||||||
if leftValue > rightValue {
|
|
||||||
return 1
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
|
|
||||||
func compareGitDescribeDistance(left, right VersionInfo) int {
|
|
||||||
if left.GitDescribeDistance == right.GitDescribeDistance {
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
if left.GitDescribeDistance < right.GitDescribeDistance {
|
|
||||||
return -1
|
|
||||||
}
|
|
||||||
return 1
|
|
||||||
}
|
|
||||||
|
|
||||||
func compareGitDescribeTails(left, right VersionInfo) int {
|
|
||||||
maxLen := max(len(right.GitDescribeTail), len(left.GitDescribeTail))
|
|
||||||
for index := range maxLen {
|
|
||||||
if index >= len(left.GitDescribeTail) {
|
|
||||||
return -1
|
|
||||||
}
|
|
||||||
if index >= len(right.GitDescribeTail) {
|
|
||||||
return 1
|
|
||||||
}
|
|
||||||
if left.GitDescribeTail[index] < right.GitDescribeTail[index] {
|
|
||||||
return -1
|
|
||||||
}
|
|
||||||
if left.GitDescribeTail[index] > right.GitDescribeTail[index] {
|
|
||||||
return 1
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
|
|
||||||
func comparePrereleaseIdentifiers(left, right VersionInfo) int {
|
|
||||||
if len(left.Prerelease) == 0 && len(right.Prerelease) == 0 {
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
if len(left.Prerelease) == 0 {
|
|
||||||
return 1
|
|
||||||
}
|
|
||||||
if len(right.Prerelease) == 0 {
|
|
||||||
return -1
|
|
||||||
}
|
|
||||||
|
|
||||||
maxLen := max(len(right.Prerelease), len(left.Prerelease))
|
|
||||||
for index := range maxLen {
|
|
||||||
if index >= len(left.Prerelease) {
|
|
||||||
return -1
|
|
||||||
}
|
|
||||||
if index >= len(right.Prerelease) {
|
|
||||||
return 1
|
|
||||||
}
|
|
||||||
if result := comparePrereleasePart(left.Prerelease[index], right.Prerelease[index]); result != 0 {
|
|
||||||
return result
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
|
|
||||||
func comparePrereleasePart(leftPart, rightPart string) int {
|
|
||||||
leftNumber, leftErr := strconv.Atoi(leftPart)
|
|
||||||
rightNumber, rightErr := strconv.Atoi(rightPart)
|
|
||||||
switch {
|
|
||||||
case leftErr == nil && rightErr == nil:
|
|
||||||
if leftNumber < rightNumber {
|
|
||||||
return -1
|
|
||||||
}
|
|
||||||
if leftNumber > rightNumber {
|
|
||||||
return 1
|
|
||||||
}
|
|
||||||
case leftErr == nil:
|
|
||||||
return -1
|
|
||||||
case rightErr == nil:
|
|
||||||
return 1
|
|
||||||
default:
|
|
||||||
if leftPart < rightPart {
|
|
||||||
return -1
|
|
||||||
}
|
|
||||||
if leftPart > rightPart {
|
|
||||||
return 1
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
@@ -77,6 +77,8 @@ func (p *Plugin) Apply(ctx *core.Context) error {
|
|||||||
InvalidateRuntimeSettings()
|
InvalidateRuntimeSettings()
|
||||||
})
|
})
|
||||||
|
|
||||||
|
core.Provide[contracts.CaptchaService](ctx, captchaService{})
|
||||||
|
|
||||||
// Register HTTP Routes
|
// Register HTTP Routes
|
||||||
capGroup := ctx.Router().Group("/api/v1/cap")
|
capGroup := ctx.Router().Group("/api/v1/cap")
|
||||||
{
|
{
|
||||||
@@ -85,6 +87,11 @@ func (p *Plugin) Apply(ctx *core.Context) error {
|
|||||||
capGroup.POST("/redeem", Redeem)
|
capGroup.POST("/redeem", Redeem)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
legacy := ctx.Router().Group("/api/cap")
|
||||||
|
legacy.POST("/challenge", Challenge)
|
||||||
|
legacy.POST("/redeem", Redeem)
|
||||||
|
ctx.Router().RegisterWhitelist("/api/cap/challenge", "/api/cap/redeem")
|
||||||
|
|
||||||
// Register Settings Schemas
|
// Register Settings Schemas
|
||||||
ctx.Settings().Register(extpoints.SettingSchema{
|
ctx.Settings().Register(extpoints.SettingSchema{
|
||||||
Key: "cap.login_enabled",
|
Key: "cap.login_enabled",
|
||||||
@@ -103,3 +110,13 @@ func (p *Plugin) Apply(ctx *core.Context) error {
|
|||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type captchaService struct{}
|
||||||
|
|
||||||
|
func (captchaService) VerifyMiddleware(scope string) any {
|
||||||
|
return VerifyMiddleware(GetDefaultManager(), scope)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (captchaService) ChallengeHandler() any { return Challenge }
|
||||||
|
|
||||||
|
func (captchaService) RedeemHandler() any { return Redeem }
|
||||||
|
|||||||
@@ -0,0 +1,52 @@
|
|||||||
|
// Copyright 2026 Arctel.net
|
||||||
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
|
|
||||||
|
package cap
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"Wavelet/core"
|
||||||
|
"Wavelet/core/contracts"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestApplyProvidesCaptchaService(t *testing.T) {
|
||||||
|
ctx := core.NewContext(context.Background())
|
||||||
|
if err := New().Apply(ctx); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
svc, err := core.Inject[contracts.CaptchaService](ctx)
|
||||||
|
if err != nil || svc == nil {
|
||||||
|
t.Fatalf("Inject CaptchaService: svc=%v err=%v", svc, err)
|
||||||
|
}
|
||||||
|
if svc.ChallengeHandler() == nil || svc.RedeemHandler() == nil {
|
||||||
|
t.Fatal("handlers must be non-nil")
|
||||||
|
}
|
||||||
|
if svc.VerifyMiddleware("login") == nil {
|
||||||
|
t.Fatal("VerifyMiddleware(login) must be non-nil")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestApplyRegistersUnversionedCapRoutes(t *testing.T) {
|
||||||
|
ctx := core.NewContext(context.Background())
|
||||||
|
if err := New().Apply(ctx); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
want := map[string]bool{
|
||||||
|
"POST /api/v1/cap/challenge": false,
|
||||||
|
"POST /api/cap/challenge": false,
|
||||||
|
"POST /api/cap/redeem": false,
|
||||||
|
}
|
||||||
|
for _, rd := range ctx.Router().Routes() {
|
||||||
|
key := rd.Method + " " + rd.Path
|
||||||
|
if _, ok := want[key]; ok {
|
||||||
|
want[key] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for key, ok := range want {
|
||||||
|
if !ok {
|
||||||
|
t.Errorf("missing route %s", key)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -231,8 +231,9 @@ func (p *Plugin) Apply(ctx *core.Context) error {
|
|||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
|
|
||||||
// 9. Register built-in domain events
|
// 9. Register built-in domain events and provide PushRegistry
|
||||||
service.RegisterCustomEvents()
|
service.RegisterCustomEvents()
|
||||||
|
core.Provide[contracts.PushRegistry](ctx, service.PushRegistryAdapter{})
|
||||||
|
|
||||||
// 10. Register Settings Schemas
|
// 10. Register Settings Schemas
|
||||||
ctx.Settings().Register(extpoints.SettingSchema{
|
ctx.Settings().Register(extpoints.SettingSchema{
|
||||||
|
|||||||
@@ -0,0 +1,54 @@
|
|||||||
|
// Copyright 2026 Arctel.net
|
||||||
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
|
|
||||||
|
package message_gateway_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"Wavelet/core"
|
||||||
|
"Wavelet/core/contracts"
|
||||||
|
"Wavelet/plugins/domain/message_gateway"
|
||||||
|
"Wavelet/plugins/domain/message_gateway/service"
|
||||||
|
"context"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestPushRegistry(t *testing.T) {
|
||||||
|
ctx := core.NewContext(context.Background())
|
||||||
|
require.NoError(t, message_gateway.New().Apply(ctx))
|
||||||
|
|
||||||
|
registry, err := core.Inject[contracts.PushRegistry](ctx)
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.NotNil(t, registry)
|
||||||
|
|
||||||
|
const key = "test.push_registry.probe"
|
||||||
|
registry.RegisterBuiltInEvent(contracts.PushEventMeta{
|
||||||
|
Key: key,
|
||||||
|
Name: "Push Registry Probe",
|
||||||
|
Description: "observability probe for contracts.PushRegistry",
|
||||||
|
DefaultTemplate: contracts.PushNotificationTemplate{
|
||||||
|
Title: "Probe Title",
|
||||||
|
Content: "Probe Content",
|
||||||
|
Level: "INFO",
|
||||||
|
Ext: map[string]any{"source": "test"},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
found := false
|
||||||
|
for _, ev := range service.GetBuiltInEvents() {
|
||||||
|
if ev.Key != key {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
found = true
|
||||||
|
assert.Equal(t, "Push Registry Probe", ev.Name)
|
||||||
|
assert.Equal(t, "observability probe for contracts.PushRegistry", ev.Description)
|
||||||
|
assert.Equal(t, "Probe Title", ev.DefaultTemplate.Title)
|
||||||
|
assert.Equal(t, "Probe Content", ev.DefaultTemplate.Content)
|
||||||
|
assert.Equal(t, "INFO", ev.DefaultTemplate.Level)
|
||||||
|
assert.Equal(t, map[string]any{"source": "test"}, ev.DefaultTemplate.Ext)
|
||||||
|
break
|
||||||
|
}
|
||||||
|
require.True(t, found, "registered key %q should be visible via GetBuiltInEvents", key)
|
||||||
|
}
|
||||||
@@ -49,6 +49,31 @@ func GetBuiltInEvents() []model.EventMetadata {
|
|||||||
return out
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// PushRegistryAdapter adapts contracts.PushRegistry onto the built-in event store.
|
||||||
|
type PushRegistryAdapter struct{}
|
||||||
|
|
||||||
|
func (PushRegistryAdapter) RegisterBuiltInEvent(meta contracts.PushEventMeta) {
|
||||||
|
RegisterBuiltInEvent(eventMetadataFromContract(meta))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (PushRegistryAdapter) SyncEvents(ctx context.Context) error {
|
||||||
|
return SyncEvents(ctx)
|
||||||
|
}
|
||||||
|
|
||||||
|
func eventMetadataFromContract(meta contracts.PushEventMeta) model.EventMetadata {
|
||||||
|
return model.EventMetadata{
|
||||||
|
Key: meta.Key,
|
||||||
|
Name: meta.Name,
|
||||||
|
Description: meta.Description,
|
||||||
|
DefaultTemplate: model.NotificationMessage{
|
||||||
|
Title: meta.DefaultTemplate.Title,
|
||||||
|
Content: meta.DefaultTemplate.Content,
|
||||||
|
Level: meta.DefaultTemplate.Level,
|
||||||
|
Ext: meta.DefaultTemplate.Ext,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// SyncBuiltInEvents seeds a database row for every registered built-in event.
|
// SyncBuiltInEvents seeds a database row for every registered built-in event.
|
||||||
func SyncBuiltInEvents(ctx context.Context) error {
|
func SyncBuiltInEvents(ctx context.Context) error {
|
||||||
for _, meta := range GetBuiltInEvents() {
|
for _, meta := range GetBuiltInEvents() {
|
||||||
|
|||||||
@@ -0,0 +1,97 @@
|
|||||||
|
// Copyright 2026 Arctel.net
|
||||||
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
|
|
||||||
|
package system
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"Wavelet/core"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestHealthRouteReturnsOKNil(t *testing.T) {
|
||||||
|
gin.SetMode(gin.TestMode)
|
||||||
|
ctx := core.NewContext(context.Background())
|
||||||
|
if err := New().Apply(ctx); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
healthHandler := routeHandler(t, ctx, "GET", "/api/health")
|
||||||
|
routeHandler(t, ctx, "GET", "/healthz")
|
||||||
|
if !ctx.Router().IsWhitelisted("/api/health") {
|
||||||
|
t.Fatal("GET /api/health is not whitelisted")
|
||||||
|
}
|
||||||
|
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
c, _ := gin.CreateTestContext(w)
|
||||||
|
c.Request = httptest.NewRequest(http.MethodGet, "/api/health", nil)
|
||||||
|
healthHandler(c)
|
||||||
|
|
||||||
|
if w.Code != http.StatusOK {
|
||||||
|
t.Fatalf("status = %d, want %d", w.Code, http.StatusOK)
|
||||||
|
}
|
||||||
|
|
||||||
|
var body struct {
|
||||||
|
ErrorMsg string `json:"error_msg"`
|
||||||
|
Data any `json:"data"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if body.ErrorMsg != "" {
|
||||||
|
t.Fatalf("error_msg = %q, want empty", body.ErrorMsg)
|
||||||
|
}
|
||||||
|
if body.Data != nil {
|
||||||
|
t.Fatalf("data = %#v, want null", body.Data)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHealthzRouteUnchanged(t *testing.T) {
|
||||||
|
gin.SetMode(gin.TestMode)
|
||||||
|
ctx := core.NewContext(context.Background())
|
||||||
|
if err := New().Apply(ctx); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
handler := routeHandler(t, ctx, "GET", "/healthz")
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
c, _ := gin.CreateTestContext(w)
|
||||||
|
c.Request = httptest.NewRequest(http.MethodGet, "/healthz", nil)
|
||||||
|
handler(c)
|
||||||
|
|
||||||
|
var body map[string]any
|
||||||
|
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if body["status"] != "ok" {
|
||||||
|
t.Fatalf("body = %s, want {status: ok}", w.Body.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func routeHandler(t *testing.T, ctx *core.Context, method, path string) gin.HandlerFunc {
|
||||||
|
t.Helper()
|
||||||
|
for _, rd := range ctx.Router().Routes() {
|
||||||
|
if rd.Method != method || rd.Path != path {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if len(rd.Handlers) == 0 {
|
||||||
|
t.Fatalf("%s %s has no handlers", method, path)
|
||||||
|
}
|
||||||
|
switch h := rd.Handlers[0].(type) {
|
||||||
|
case gin.HandlerFunc:
|
||||||
|
return h
|
||||||
|
case func(*gin.Context):
|
||||||
|
return h
|
||||||
|
default:
|
||||||
|
t.Fatalf("unexpected handler type %T", rd.Handlers[0])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
t.Fatalf("%s %s missing", method, path)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -56,9 +56,23 @@ func (p *Plugin) Apply(ctx *core.Context) error {
|
|||||||
ctx.Router().GET("/api/healthz", func(c *gin.Context) {
|
ctx.Router().GET("/api/healthz", func(c *gin.Context) {
|
||||||
c.JSON(http.StatusOK, gin.H{"status": "ok"})
|
c.JSON(http.StatusOK, gin.H{"status": "ok"})
|
||||||
})
|
})
|
||||||
|
ctx.Router().GET("/api/health", func(c *gin.Context) {
|
||||||
|
c.JSON(http.StatusOK, response.OKNil())
|
||||||
|
})
|
||||||
|
ctx.Router().RegisterWhitelist("/api/health")
|
||||||
|
|
||||||
// 2. Public config
|
// 2. Public config
|
||||||
ctx.Router().GET("/api/v1/config/public", func(c *gin.Context) {
|
ctx.Router().GET("/api/v1/config/public", func(c *gin.Context) {
|
||||||
|
if p, err := core.Inject[contracts.PublicConfigProvider](ctx); err == nil && p != nil {
|
||||||
|
data, err := p.PublicConfig(c.Request.Context())
|
||||||
|
if err != nil {
|
||||||
|
logger.ErrorF(c.Request.Context(), "[System] public config provider failed: %v", err)
|
||||||
|
response.AbortInternal(c, "public config unavailable")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, response.OK(data))
|
||||||
|
return
|
||||||
|
}
|
||||||
configs, err := listPublicSystemConfigs(c.Request.Context(), ctx)
|
configs, err := listPublicSystemConfigs(c.Request.Context(), ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logger.ErrorF(c.Request.Context(), "[System] query public system configs failed: %v", err)
|
logger.ErrorF(c.Request.Context(), "[System] query public system configs failed: %v", err)
|
||||||
|
|||||||
@@ -0,0 +1,149 @@
|
|||||||
|
// Copyright 2026 Arctel.net
|
||||||
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
|
|
||||||
|
package system
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"Wavelet/core"
|
||||||
|
"Wavelet/core/contracts"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
type stubPublic struct{ payload any }
|
||||||
|
|
||||||
|
func (s stubPublic) PublicConfig(context.Context) (any, error) { return s.payload, nil }
|
||||||
|
|
||||||
|
type errPublic struct{ err error }
|
||||||
|
|
||||||
|
func (s errPublic) PublicConfig(context.Context) (any, error) { return nil, s.err }
|
||||||
|
|
||||||
|
func TestPublicConfigUsesProviderWhenPresent(t *testing.T) {
|
||||||
|
gin.SetMode(gin.TestMode)
|
||||||
|
ctx := core.NewContext(context.Background())
|
||||||
|
core.Provide[contracts.PublicConfigProvider](ctx, stubPublic{payload: map[string]string{"k": "v"}})
|
||||||
|
if err := New().Apply(ctx); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
body := invokePublicConfig(t, publicConfigHandler(t, ctx))
|
||||||
|
assertFlatKV(t, body)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPublicConfigUsesProviderRegisteredAfterApply(t *testing.T) {
|
||||||
|
gin.SetMode(gin.TestMode)
|
||||||
|
ctx := core.NewContext(context.Background())
|
||||||
|
if err := New().Apply(ctx); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
core.Provide[contracts.PublicConfigProvider](ctx, stubPublic{payload: map[string]string{"k": "v"}})
|
||||||
|
body := invokePublicConfig(t, publicConfigHandler(t, ctx))
|
||||||
|
assertFlatKV(t, body)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPublicConfigDefaultWithoutProvider(t *testing.T) {
|
||||||
|
gin.SetMode(gin.TestMode)
|
||||||
|
ctx := core.NewContext(context.Background())
|
||||||
|
if err := New().Apply(ctx); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
raw := invokePublicConfig(t, publicConfigHandler(t, ctx))
|
||||||
|
var data map[string]any
|
||||||
|
if err := json.Unmarshal(raw, &data); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, ok := data["configs"]; !ok {
|
||||||
|
t.Fatalf("data = %s, want key configs", raw)
|
||||||
|
}
|
||||||
|
if _, ok := data["app"]; !ok {
|
||||||
|
t.Fatalf("data = %s, want key app", raw)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPublicConfigProviderErrorAbortsInternal(t *testing.T) {
|
||||||
|
gin.SetMode(gin.TestMode)
|
||||||
|
ctx := core.NewContext(context.Background())
|
||||||
|
core.Provide[contracts.PublicConfigProvider](ctx, errPublic{err: errors.New("secret boom")})
|
||||||
|
if err := New().Apply(ctx); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
c, _ := gin.CreateTestContext(w)
|
||||||
|
c.Request = httptest.NewRequest(http.MethodGet, "/api/v1/config/public", nil)
|
||||||
|
publicConfigHandler(t, ctx)(c)
|
||||||
|
|
||||||
|
if !c.IsAborted() {
|
||||||
|
t.Fatal("want request aborted on provider error")
|
||||||
|
}
|
||||||
|
if len(c.Errors) == 0 {
|
||||||
|
t.Fatal("want gin error on provider failure")
|
||||||
|
}
|
||||||
|
if got := c.Errors.Last().Error(); got != "public config unavailable" {
|
||||||
|
t.Fatalf("error = %q, want generic message", got)
|
||||||
|
}
|
||||||
|
if strings.Contains(w.Body.String(), "secret boom") {
|
||||||
|
t.Fatalf("leaked provider error: %s", w.Body.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func publicConfigHandler(t *testing.T, ctx *core.Context) gin.HandlerFunc {
|
||||||
|
t.Helper()
|
||||||
|
for _, rd := range ctx.Router().Routes() {
|
||||||
|
if rd.Method != "GET" || rd.Path != "/api/v1/config/public" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if len(rd.Handlers) == 0 {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
switch h := rd.Handlers[0].(type) {
|
||||||
|
case gin.HandlerFunc:
|
||||||
|
return h
|
||||||
|
case func(*gin.Context):
|
||||||
|
return h
|
||||||
|
default:
|
||||||
|
t.Fatalf("unexpected handler type %T", rd.Handlers[0])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
t.Fatal("public config route missing")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func invokePublicConfig(t *testing.T, handler gin.HandlerFunc) json.RawMessage {
|
||||||
|
t.Helper()
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
c, _ := gin.CreateTestContext(w)
|
||||||
|
c.Request = httptest.NewRequest(http.MethodGet, "/api/v1/config/public", nil)
|
||||||
|
handler(c)
|
||||||
|
var body struct {
|
||||||
|
Data json.RawMessage `json:"data"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return body.Data
|
||||||
|
}
|
||||||
|
|
||||||
|
func assertFlatKV(t *testing.T, raw json.RawMessage) {
|
||||||
|
t.Helper()
|
||||||
|
var data map[string]any
|
||||||
|
if err := json.Unmarshal(raw, &data); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if data["k"] != "v" {
|
||||||
|
t.Fatalf("data = %s, want flat map", raw)
|
||||||
|
}
|
||||||
|
if _, ok := data["configs"]; ok {
|
||||||
|
t.Fatalf("data = %s, want provider payload without default configs", raw)
|
||||||
|
}
|
||||||
|
if _, ok := data["app"]; ok {
|
||||||
|
t.Fatalf("data = %s, want provider payload without default app", raw)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -126,6 +126,10 @@ func (p *Plugin) Apply(ctx *core.Context) error {
|
|||||||
uploadGroup.GET("", handler.ListFiles)
|
uploadGroup.GET("", handler.ListFiles)
|
||||||
uploadGroup.DELETE("/:id", handler.DeleteFile)
|
uploadGroup.DELETE("/:id", handler.DeleteFile)
|
||||||
uploadGroup.POST("/batch-download", handler.BatchDownloadFiles)
|
uploadGroup.POST("/batch-download", handler.BatchDownloadFiles)
|
||||||
|
uploadGroup.GET("/my", handler.ListMyFiles)
|
||||||
|
uploadGroup.PUT("/:id", handler.UpdateMyFile)
|
||||||
|
uploadGroup.GET("/download/:id", handler.DownloadFile)
|
||||||
|
uploadGroup.POST("/download/batch", handler.BatchDownloadFiles)
|
||||||
}
|
}
|
||||||
|
|
||||||
adminUploadGroup := ctx.Router().Group("/api/v1/admin/uploads", loginMW)
|
adminUploadGroup := ctx.Router().Group("/api/v1/admin/uploads", loginMW)
|
||||||
|
|||||||
@@ -0,0 +1,53 @@
|
|||||||
|
// Copyright 2026 Arctel.net
|
||||||
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
|
|
||||||
|
package upload
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
|
||||||
|
"Wavelet/core"
|
||||||
|
"Wavelet/core/contracts"
|
||||||
|
)
|
||||||
|
|
||||||
|
type stubDBService struct{ contracts.DBService }
|
||||||
|
|
||||||
|
type stubStorageService struct{ contracts.StorageService }
|
||||||
|
|
||||||
|
type stubAuthService struct{ contracts.AuthService }
|
||||||
|
|
||||||
|
func (stubAuthService) RequireAuthMiddleware() any {
|
||||||
|
return gin.HandlerFunc(func(c *gin.Context) { c.Next() })
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUserUploadRoutes(t *testing.T) {
|
||||||
|
gin.SetMode(gin.TestMode)
|
||||||
|
ctx := core.NewContext(context.Background())
|
||||||
|
core.Provide[contracts.DBService](ctx, stubDBService{})
|
||||||
|
core.Provide[contracts.StorageService](ctx, stubStorageService{})
|
||||||
|
core.Provide[contracts.AuthService](ctx, stubAuthService{})
|
||||||
|
if err := New().Apply(ctx); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
want := []string{
|
||||||
|
"GET /api/v1/upload/my",
|
||||||
|
"PUT /api/v1/upload/:id",
|
||||||
|
"GET /api/v1/upload/download/:id",
|
||||||
|
"POST /api/v1/upload/download/batch",
|
||||||
|
"GET /api/v1/upload",
|
||||||
|
"POST /api/v1/upload/batch-download",
|
||||||
|
}
|
||||||
|
found := make(map[string]bool, len(want))
|
||||||
|
for _, rd := range ctx.Router().Routes() {
|
||||||
|
found[rd.Method+" "+rd.Path] = true
|
||||||
|
}
|
||||||
|
for _, key := range want {
|
||||||
|
if !found[key] {
|
||||||
|
t.Errorf("missing route %s", key)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -200,6 +200,22 @@ func ChangePassword(c *gin.Context) {
|
|||||||
c.JSON(http.StatusOK, response.OKNil())
|
c.JSON(http.StatusOK, response.OKNil())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Self returns the current authenticated user.
|
||||||
|
func Self(c *gin.Context) {
|
||||||
|
svc := getAuthService()
|
||||||
|
if svc == nil {
|
||||||
|
response.AbortUnauthorized(c, errUserNotFound)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
user, err := svc.GetCurrentUser(c)
|
||||||
|
if err != nil {
|
||||||
|
logger.ErrorF(c.Request.Context(), "get current user failed: %v", err)
|
||||||
|
response.AbortUnauthorized(c, errUserNotFound)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, response.OK(user))
|
||||||
|
}
|
||||||
|
|
||||||
// UpdateProfile updates profile info.
|
// UpdateProfile updates profile info.
|
||||||
func UpdateProfile(c *gin.Context) {
|
func UpdateProfile(c *gin.Context) {
|
||||||
var req updateProfileRequest
|
var req updateProfileRequest
|
||||||
|
|||||||
@@ -120,14 +120,29 @@ func (p *Plugin) Apply(ctx *core.Context) error {
|
|||||||
}
|
}
|
||||||
core.Provide[contracts.UserService](ctx, p.userSvc)
|
core.Provide[contracts.UserService](ctx, p.userSvc)
|
||||||
|
|
||||||
|
passThrough := gin.HandlerFunc(func(c *gin.Context) { c.Next() })
|
||||||
|
loginCap, registerCap, emailCap := passThrough, passThrough, passThrough
|
||||||
|
if capSvc, err := core.Inject[contracts.CaptchaService](ctx); err == nil && capSvc != nil {
|
||||||
|
if mw, ok := capSvc.VerifyMiddleware("login").(gin.HandlerFunc); ok {
|
||||||
|
loginCap = mw
|
||||||
|
}
|
||||||
|
if mw, ok := capSvc.VerifyMiddleware("register").(gin.HandlerFunc); ok {
|
||||||
|
registerCap = mw
|
||||||
|
}
|
||||||
|
if mw, ok := capSvc.VerifyMiddleware("send_email_code").(gin.HandlerFunc); ok {
|
||||||
|
emailCap = mw
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// 3. Register HTTP Routes
|
// 3. Register HTTP Routes
|
||||||
userGroup := ctx.Router().Group("/api/v1/user")
|
userGroup := ctx.Router().Group("/api/v1/user")
|
||||||
{
|
{
|
||||||
userGroup.POST("/login", Login)
|
userGroup.POST("/login", loginCap, Login)
|
||||||
userGroup.POST("/register", Register)
|
userGroup.POST("/register", registerCap, Register)
|
||||||
userGroup.GET("/logout", Logout)
|
userGroup.GET("/logout", Logout)
|
||||||
userGroup.POST("/send-email-code", SendEmailCode)
|
userGroup.POST("/send-email-code", emailCap, SendEmailCode)
|
||||||
userGroup.POST("/change-password", loginMW, ChangePassword)
|
userGroup.POST("/change-password", loginMW, ChangePassword)
|
||||||
|
userGroup.GET("/self", loginMW, Self)
|
||||||
userGroup.PUT("/profile", loginMW, UpdateProfile)
|
userGroup.PUT("/profile", loginMW, UpdateProfile)
|
||||||
|
|
||||||
// Access Tokens
|
// Access Tokens
|
||||||
|
|||||||
@@ -0,0 +1,74 @@
|
|||||||
|
// Copyright 2026 Arctel.net
|
||||||
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
|
|
||||||
|
package user_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"reflect"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
|
||||||
|
"Wavelet/core"
|
||||||
|
"Wavelet/core/contracts"
|
||||||
|
"Wavelet/plugins/domain/user"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestApplyWithoutCaptchaServiceKeepsAuthRoutes(t *testing.T) {
|
||||||
|
ctx := core.NewContext(context.Background())
|
||||||
|
if err := user.New().Apply(ctx); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
want := map[string]bool{
|
||||||
|
"POST /api/v1/user/login": false,
|
||||||
|
"POST /api/v1/user/register": false,
|
||||||
|
"POST /api/v1/user/send-email-code": false,
|
||||||
|
}
|
||||||
|
for _, rd := range ctx.Router().Routes() {
|
||||||
|
key := rd.Method + " " + rd.Path
|
||||||
|
if _, ok := want[key]; ok {
|
||||||
|
want[key] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for key, ok := range want {
|
||||||
|
if !ok {
|
||||||
|
t.Errorf("missing route %s", key)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestInjectDoesNotRequireCaptchaService(t *testing.T) {
|
||||||
|
for _, dep := range user.New().Inject() {
|
||||||
|
if dep == reflect.TypeFor[contracts.CaptchaService]() {
|
||||||
|
t.Fatal("CaptchaService must not be a hard Inject() dependency")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type fakeCaptchaService struct{}
|
||||||
|
|
||||||
|
func (fakeCaptchaService) VerifyMiddleware(scope string) any {
|
||||||
|
return gin.HandlerFunc(func(c *gin.Context) { c.Next() })
|
||||||
|
}
|
||||||
|
|
||||||
|
func (fakeCaptchaService) ChallengeHandler() any { return gin.HandlerFunc(func(c *gin.Context) {}) }
|
||||||
|
|
||||||
|
func (fakeCaptchaService) RedeemHandler() any { return gin.HandlerFunc(func(c *gin.Context) {}) }
|
||||||
|
|
||||||
|
func TestApplyWithCaptchaServiceWrapsLogin(t *testing.T) {
|
||||||
|
ctx := core.NewContext(context.Background())
|
||||||
|
core.Provide[contracts.CaptchaService](ctx, fakeCaptchaService{})
|
||||||
|
if err := user.New().Apply(ctx); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, rd := range ctx.Router().Routes() {
|
||||||
|
if rd.Method == "POST" && rd.Path == "/api/v1/user/login" {
|
||||||
|
if len(rd.Handlers) <= 1 {
|
||||||
|
t.Fatalf("login handler chain length = %d, want > 1", len(rd.Handlers))
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
t.Fatal("missing POST /api/v1/user/login")
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
// Copyright 2026 Arctel.net
|
||||||
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
|
|
||||||
|
package user_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"Wavelet/core"
|
||||||
|
"Wavelet/core/extpoints"
|
||||||
|
"Wavelet/plugins/domain/user"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestSelfRouteRegisteredWithLoginProtection(t *testing.T) {
|
||||||
|
ctx := core.NewContext(context.Background())
|
||||||
|
if err := user.New().Apply(ctx); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
routes := ctx.Router().Routes()
|
||||||
|
self, ok := findRoute(routes, "GET", "/api/v1/user/self")
|
||||||
|
if !ok {
|
||||||
|
t.Fatal("GET /api/v1/user/self missing")
|
||||||
|
}
|
||||||
|
profile, ok := findRoute(routes, "PUT", "/api/v1/user/profile")
|
||||||
|
if !ok {
|
||||||
|
t.Fatal("PUT /api/v1/user/profile missing")
|
||||||
|
}
|
||||||
|
|
||||||
|
selfCount := len(self.Handlers) + len(self.Middlewares)
|
||||||
|
profileCount := len(profile.Handlers) + len(profile.Middlewares)
|
||||||
|
if selfCount < profileCount {
|
||||||
|
t.Fatalf("GET /api/v1/user/self handler/middleware count = %d, want >= %d (profile)", selfCount, profileCount)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func findRoute(routes []extpoints.RouteDefinition, method, path string) (extpoints.RouteDefinition, bool) {
|
||||||
|
for _, rd := range routes {
|
||||||
|
if rd.Method == method && rd.Path == path {
|
||||||
|
return rd, true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return extpoints.RouteDefinition{}, false
|
||||||
|
}
|
||||||
@@ -15,6 +15,7 @@ type httpAppConfig struct {
|
|||||||
SessionAge int `config:"session_age" env:"APP_SESSION_AGE" default:"86400"`
|
SessionAge int `config:"session_age" env:"APP_SESSION_AGE" default:"86400"`
|
||||||
SessionHTTPOnly bool `config:"session_http_only" env:"APP_SESSION_HTTP_ONLY" default:"true"`
|
SessionHTTPOnly bool `config:"session_http_only" env:"APP_SESSION_HTTP_ONLY" default:"true"`
|
||||||
SessionSecure bool `config:"session_secure" env:"APP_SESSION_SECURE"`
|
SessionSecure bool `config:"session_secure" env:"APP_SESSION_SECURE"`
|
||||||
|
RedirectTrailingSlash *bool `config:"redirect_trailing_slash" env:"APP_REDIRECT_TRAILING_SLASH"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type httpRedisConfig struct {
|
type httpRedisConfig struct {
|
||||||
|
|||||||
@@ -31,6 +31,11 @@ func BuildEngineWithConfig(appCfg httpAppConfig, redisCfg httpRedisConfig) (*gin
|
|||||||
|
|
||||||
// 初始化路由
|
// 初始化路由
|
||||||
r := gin.New()
|
r := gin.New()
|
||||||
|
redirect := true
|
||||||
|
if appCfg.RedirectTrailingSlash != nil {
|
||||||
|
redirect = *appCfg.RedirectTrailingSlash
|
||||||
|
}
|
||||||
|
r.RedirectTrailingSlash = redirect
|
||||||
r.Use(gin.Recovery())
|
r.Use(gin.Recovery())
|
||||||
r.Use(corsMiddleware())
|
r.Use(corsMiddleware())
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,113 @@
|
|||||||
|
// Copyright 2026 Arctel.net
|
||||||
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
|
|
||||||
|
package driver_http
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"Wavelet/core/extpoints"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestBuildEngineDefaultRedirectsTrailingSlash(t *testing.T) {
|
||||||
|
eng, err := BuildEngineWithConfig(httpAppConfig{}, httpRedisConfig{})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !eng.RedirectTrailingSlash {
|
||||||
|
t.Fatal("default RedirectTrailingSlash must be true")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBuildEngineCanDisableRedirectTrailingSlash(t *testing.T) {
|
||||||
|
eng, err := BuildEngineWithConfig(httpAppConfig{RedirectTrailingSlash: boolPtr(false)}, httpRedisConfig{})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if eng.RedirectTrailingSlash {
|
||||||
|
t.Fatal("RedirectTrailingSlash must honor false")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBindAppConfigDefaultKeepsTrailingSlashRedirect(t *testing.T) {
|
||||||
|
cfg := bindAppConfig(t, map[string]any{}, map[string]string{})
|
||||||
|
if cfg.RedirectTrailingSlash != nil {
|
||||||
|
t.Fatal("absent redirect_trailing_slash must leave *bool nil")
|
||||||
|
}
|
||||||
|
eng, err := BuildEngineWithConfig(cfg, httpRedisConfig{})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !eng.RedirectTrailingSlash {
|
||||||
|
t.Fatal("default RedirectTrailingSlash must be true after Bind")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBindAppConfigCanDisableTrailingSlashRedirect(t *testing.T) {
|
||||||
|
cfg := bindAppConfig(t, map[string]any{"app.redirect_trailing_slash": false}, nil)
|
||||||
|
if cfg.RedirectTrailingSlash == nil || *cfg.RedirectTrailingSlash {
|
||||||
|
t.Fatal("yaml false must bind *false")
|
||||||
|
}
|
||||||
|
eng, err := BuildEngineWithConfig(cfg, httpRedisConfig{})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if eng.RedirectTrailingSlash {
|
||||||
|
t.Fatal("RedirectTrailingSlash must honor bound false")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBindAppConfigEnvCanDisableTrailingSlashRedirect(t *testing.T) {
|
||||||
|
cfg := bindAppConfig(t, nil, map[string]string{"APP_REDIRECT_TRAILING_SLASH": "false"})
|
||||||
|
if cfg.RedirectTrailingSlash == nil || *cfg.RedirectTrailingSlash {
|
||||||
|
t.Fatal("env false must bind *false")
|
||||||
|
}
|
||||||
|
eng, err := BuildEngineWithConfig(cfg, httpRedisConfig{})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if eng.RedirectTrailingSlash {
|
||||||
|
t.Fatal("RedirectTrailingSlash must honor env-bound false")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type slashConfigSource struct {
|
||||||
|
values map[string]any
|
||||||
|
env map[string]string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s slashConfigSource) Lookup(path string) (any, bool) {
|
||||||
|
v, ok := s.values[path]
|
||||||
|
return v, ok
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s slashConfigSource) LookupEnv(name string) (string, bool) {
|
||||||
|
v, ok := s.env[name]
|
||||||
|
return v, ok
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s slashConfigSource) Describe() string { return "slash-test" }
|
||||||
|
|
||||||
|
func bindAppConfig(t *testing.T, values map[string]any, env map[string]string) httpAppConfig {
|
||||||
|
t.Helper()
|
||||||
|
if values == nil {
|
||||||
|
values = map[string]any{}
|
||||||
|
}
|
||||||
|
if env == nil {
|
||||||
|
env = map[string]string{}
|
||||||
|
}
|
||||||
|
r := extpoints.NewConfigRegistry(slashConfigSource{values: values, env: env})
|
||||||
|
if err := r.Declare("driver_http", extpoints.ConfigBinding{Prefix: "app", Target: &httpAppConfig{}}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := r.Resolve(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var cfg httpAppConfig
|
||||||
|
if err := r.Bind("app", &cfg); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return cfg
|
||||||
|
}
|
||||||
|
|
||||||
|
func boolPtr(v bool) *bool { return &v }
|
||||||
Reference in New Issue
Block a user