chore: 初始化仓库,导入项目基线代码
Academy v0.8.3 完整代码基线:Go 后端(internal/cmd/cli/mcp-server/docreader)、 Vue 前端(frontend)、数据库迁移(migrations)、部署编排(docker/helm/deploy)与文档。 今日开发的培训推送管理改动随后单独提交。
This commit is contained in:
commit
7ec21f35b0
5767 files changed
+1436788
No files matched your search
@@ -0,0 +1,66 @@
|
||||
package container
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
|
||||
"academy/internal/application/repository/retriever/opensearch"
|
||||
"academy/internal/logger"
|
||||
"academy/internal/types"
|
||||
"academy/internal/types/interfaces"
|
||||
)
|
||||
|
||||
// auditSinkAdapter bridges the OpenSearch driver's AuditSink (which the driver
|
||||
// owns so it imports no service package) to the service-layer AuditLogService.
|
||||
// This keeps the dependency one-way: the driver depends only on its own
|
||||
// AuditSink abstraction; the container implements it.
|
||||
type auditSinkAdapter struct {
|
||||
svc interfaces.AuditLogService
|
||||
}
|
||||
|
||||
// newAuditSinkAdapter returns an opensearch.AuditSink backed by svc. A nil svc
|
||||
// yields a sink whose emits are no-ops.
|
||||
func newAuditSinkAdapter(svc interfaces.AuditLogService) opensearch.AuditSink {
|
||||
return auditSinkAdapter{svc: svc}
|
||||
}
|
||||
|
||||
func (a auditSinkAdapter) EmitIndexCreated(ctx context.Context, alias string, dim int) {
|
||||
a.emit(ctx, types.AuditActionOpenSearchIndexCreated, alias,
|
||||
map[string]any{"alias": alias, "dim": dim})
|
||||
}
|
||||
|
||||
func (a auditSinkAdapter) EmitReindexExecuted(ctx context.Context, srcAlias, dstAlias string, docs int64) {
|
||||
a.emit(ctx, types.AuditActionOpenSearchReindexExecuted, dstAlias,
|
||||
map[string]any{"src_alias": srcAlias, "dst_alias": dstAlias, "docs": docs})
|
||||
}
|
||||
|
||||
// emit writes one audit entry. It skips (with a warning) when the context
|
||||
// carries no tenant — driver events can fire from background task contexts
|
||||
// (e.g. lazy index creation under an async copy task), and writing tenant_id=0
|
||||
// would collide with the system-scope sentinel and corrupt the audit trail.
|
||||
func (a auditSinkAdapter) emit(ctx context.Context, action types.AuditAction, target string, detail map[string]any) {
|
||||
if a.svc == nil {
|
||||
return
|
||||
}
|
||||
tid, ok := types.TenantIDFromContext(ctx)
|
||||
if !ok {
|
||||
logger.GetLogger(ctx).Warnf("[audit] %s: no tenant in context, skipping audit (target=%s)", action, target)
|
||||
return
|
||||
}
|
||||
// Details is a typed JSON blob — only bounded, non-secret fields. Never
|
||||
// include cluster reason strings or connection secrets.
|
||||
b, err := json.Marshal(detail)
|
||||
if err != nil {
|
||||
logger.GetLogger(ctx).Warnf("[audit] %s: marshal details failed: %v", action, err)
|
||||
b = []byte("{}")
|
||||
}
|
||||
if err := a.svc.Log(ctx, &types.AuditLog{
|
||||
TenantID: tid,
|
||||
Action: action,
|
||||
TargetType: "opensearch_index",
|
||||
TargetID: target,
|
||||
Details: types.JSON(b),
|
||||
}); err != nil {
|
||||
logger.GetLogger(ctx).Warnf("[audit] %s emit failed: %v", action, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package container
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"academy/internal/types"
|
||||
"academy/internal/types/interfaces"
|
||||
)
|
||||
|
||||
// fakeAuditSvc records Log calls.
|
||||
type fakeAuditSvc struct {
|
||||
logged []*types.AuditLog
|
||||
err error
|
||||
}
|
||||
|
||||
func (f *fakeAuditSvc) Log(_ context.Context, e *types.AuditLog) error {
|
||||
f.logged = append(f.logged, e)
|
||||
return f.err
|
||||
}
|
||||
func (f *fakeAuditSvc) LogDenied(context.Context, *gin.Context, uint64, string, string, types.TenantRole) error {
|
||||
return nil
|
||||
}
|
||||
func (f *fakeAuditSvc) List(context.Context, uint64, *interfaces.AuditLogQuery) ([]*types.AuditLog, error) {
|
||||
return nil, nil
|
||||
}
|
||||
func (f *fakeAuditSvc) Purge(context.Context, int) (int64, error) { return 0, nil }
|
||||
|
||||
func ctxWithTenant(id uint64) context.Context {
|
||||
return context.WithValue(context.Background(), types.TenantIDContextKey, id)
|
||||
}
|
||||
|
||||
func TestAuditSinkAdapter_EmitsWithTenant(t *testing.T) {
|
||||
f := &fakeAuditSvc{}
|
||||
sink := newAuditSinkAdapter(f)
|
||||
|
||||
sink.EmitIndexCreated(ctxWithTenant(42), "academy_768", 768)
|
||||
if len(f.logged) != 1 {
|
||||
t.Fatalf("want 1 audit entry, got %d", len(f.logged))
|
||||
}
|
||||
e := f.logged[0]
|
||||
if e.TenantID != 42 {
|
||||
t.Errorf("tenant: want 42, got %d", e.TenantID)
|
||||
}
|
||||
if e.Action != types.AuditActionOpenSearchIndexCreated {
|
||||
t.Errorf("action: want %s, got %s", types.AuditActionOpenSearchIndexCreated, e.Action)
|
||||
}
|
||||
if e.Details == nil {
|
||||
t.Error("details should be populated")
|
||||
}
|
||||
|
||||
sink.EmitReindexExecuted(ctxWithTenant(7), "src", "dst", 9)
|
||||
if len(f.logged) != 2 || f.logged[1].Action != types.AuditActionOpenSearchReindexExecuted {
|
||||
t.Errorf("reindex audit not recorded: %+v", f.logged)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuditSinkAdapter_SkipsWithoutTenant(t *testing.T) {
|
||||
f := &fakeAuditSvc{}
|
||||
sink := newAuditSinkAdapter(f)
|
||||
// background ctx carries no tenant → adapter must skip (never write tenant=0)
|
||||
sink.EmitIndexCreated(context.Background(), "academy_768", 768)
|
||||
sink.EmitReindexExecuted(context.Background(), "a", "b", 1)
|
||||
if len(f.logged) != 0 {
|
||||
t.Errorf("want 0 audit entries without tenant, got %d", len(f.logged))
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuditSinkAdapter_NilServiceNoPanic(t *testing.T) {
|
||||
sink := newAuditSinkAdapter(nil)
|
||||
sink.EmitIndexCreated(ctxWithTenant(1), "x", 1) // must not panic
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
// Package container - background-work wiring.
|
||||
package container
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
|
||||
"academy/internal/application/service"
|
||||
"academy/internal/application/service/sandboxalloc"
|
||||
"academy/internal/background"
|
||||
"academy/internal/sandbox"
|
||||
"academy/internal/stream"
|
||||
"academy/internal/types/interfaces"
|
||||
)
|
||||
|
||||
// newBackgroundActivityRegistry returns the registry of live background work.
|
||||
// With Redis it lives on the binding store, so turn leases, the rebuild check
|
||||
// and the rewind lock read it in the same Lua call. The memory store uses
|
||||
// the same lock for activity registration and lifecycle checks.
|
||||
func newBackgroundActivityRegistry(
|
||||
store sandbox.SessionSandboxBindingStore, allocations *sandboxalloc.Service,
|
||||
) interfaces.ActivityRegistry {
|
||||
switch store := store.(type) {
|
||||
case *sandbox.RedisSessionSandboxBindingStore:
|
||||
registry := sandbox.NewRedisActivityRegistry(store)
|
||||
if allocations != nil {
|
||||
registry.WithAllocations(allocations)
|
||||
}
|
||||
return registry
|
||||
case *sandbox.MemorySessionSandboxBindingStore:
|
||||
return sandbox.NewMemoryActivityRegistry(store)
|
||||
}
|
||||
return background.NewMemoryActivityRegistry(nil)
|
||||
}
|
||||
|
||||
// newBackgroundNoticeInbox returns the completion-notice inbox. With Redis it
|
||||
// lives next to the steer lists; otherwise it is process-local, like the
|
||||
// in-memory stream manager it follows.
|
||||
func newBackgroundNoticeInbox(streams interfaces.StreamManager) interfaces.NoticeInbox {
|
||||
if redisStreams, ok := streams.(*stream.RedisStreamManager); ok {
|
||||
return stream.NewRedisNoticeInbox(redisStreams, nil)
|
||||
}
|
||||
return background.NewMemoryNoticeInbox(nil)
|
||||
}
|
||||
|
||||
// redisNamespace matches the session-binding store: ACADEMY_REDIS_NAMESPACE,
|
||||
// or "academy" when that variable is empty.
|
||||
func redisNamespace() string {
|
||||
namespace := strings.TrimSpace(os.Getenv("ACADEMY_REDIS_NAMESPACE"))
|
||||
if namespace == "" {
|
||||
return "academy"
|
||||
}
|
||||
return namespace
|
||||
}
|
||||
|
||||
// newRemoteShellJobService wires the shell feature into BackgroundWork:
|
||||
// Handler, the throttled keep-aliver, and (when Redis is configured) the job
|
||||
// index. Dig provides the build-tagged newShellJobService; the web stub
|
||||
// forwards here. The agent service depends on that constructor, so dig builds
|
||||
// it first.
|
||||
func newRemoteShellJobService(
|
||||
rdb *redis.Client,
|
||||
pinned *service.PinnedSessionSandbox,
|
||||
bg *service.BackgroundWork,
|
||||
streams interfaces.StreamManager,
|
||||
) *service.ShellJobService {
|
||||
var index *service.ShellJobIndex
|
||||
if rdb != nil {
|
||||
index = service.NewShellJobIndex(rdb, redisNamespace())
|
||||
}
|
||||
// A nil stream manager must stay a nil pointer. Storing (*Emitter)(nil)
|
||||
// in the lifecycle's event interface panics on the first call.
|
||||
var events *service.BackgroundEventEmitter
|
||||
if streams != nil {
|
||||
events = service.NewBackgroundEventEmitter(streams)
|
||||
}
|
||||
svc := service.NewShellJobService(pinned, bg, index, events, service.NewBackgroundKeepAliver(pinned))
|
||||
if bg != nil {
|
||||
bg.Handler = svc
|
||||
}
|
||||
return svc
|
||||
}
|
||||
|
||||
// startShellJobSweeper runs the remote handoff loop. Lite has no Redis index,
|
||||
// so RemoteAvailable is false and nothing is started.
|
||||
func startShellJobSweeper(svc *service.ShellJobService, cleaner interfaces.ResourceCleaner) {
|
||||
if svc == nil || !svc.RemoteAvailable() || cleaner == nil {
|
||||
return
|
||||
}
|
||||
sweeperCtx, stop := context.WithCancel(context.Background())
|
||||
svc.StartSweeper(sweeperCtx, 5*time.Second)
|
||||
cleaner.RegisterWithName("ShellJobSweeper", func() error {
|
||||
stop()
|
||||
return nil
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
//go:build desktop
|
||||
|
||||
package container
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
|
||||
"academy/internal/application/service"
|
||||
"academy/internal/localsandbox"
|
||||
"academy/internal/types/interfaces"
|
||||
)
|
||||
|
||||
// newShellJobService wires Lite shell jobs. Remote sandboxes are hidden, so
|
||||
// the index stays nil. A nil stream manager stays a nil emitter pointer:
|
||||
// storing (*BackgroundEventEmitter)(nil) in the lifecycle event interface
|
||||
// panics on the first call. The keep-aliver matches the web wiring;
|
||||
// NewBackgroundKeepAliver is a no-op for a host sandbox, and a nil keeper
|
||||
// fails the remote submit path.
|
||||
func newShellJobService(
|
||||
_ *redis.Client,
|
||||
pinned *service.PinnedSessionSandbox,
|
||||
bg *service.BackgroundWork,
|
||||
streams interfaces.StreamManager,
|
||||
cleaner interfaces.ResourceCleaner,
|
||||
host service.HostSandboxManager,
|
||||
) (*service.ShellJobService, error) {
|
||||
var events *service.BackgroundEventEmitter
|
||||
if streams != nil {
|
||||
events = service.NewBackgroundEventEmitter(streams)
|
||||
}
|
||||
jobs := service.NewShellJobService(pinned, bg, nil, events, service.NewBackgroundKeepAliver(pinned))
|
||||
if bg != nil {
|
||||
bg.Handler = jobs
|
||||
}
|
||||
provider, ok := host.Manager.(interface{ LocalSandboxService() *localsandbox.Service })
|
||||
if !ok || provider.LocalSandboxService() == nil {
|
||||
return jobs, nil
|
||||
}
|
||||
home, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
local, err := service.NewLocalShellJobService(
|
||||
provider.LocalSandboxService(), bg, events, filepath.Join(home, ".academy", "jobs"),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
jobs.WithLocal(local)
|
||||
cleaner.RegisterWithName("LocalShellJobs", func() error {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
return local.Shutdown(ctx)
|
||||
})
|
||||
return jobs, nil
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
//go:build desktop
|
||||
|
||||
package container
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"academy/internal/application/service"
|
||||
"academy/internal/background"
|
||||
)
|
||||
|
||||
func TestDesktopWithoutHostManagerStaysRemoteOnly(t *testing.T) {
|
||||
bg := service.NewBackgroundWork(background.NewMemoryActivityRegistry(nil), background.NewMemoryNoticeInbox(nil))
|
||||
jobs, err := newShellJobService(nil, nil, bg, nil, NewResourceCleaner(),
|
||||
service.HostSandboxManager{Desktop: true})
|
||||
require.NoError(t, err)
|
||||
require.False(t, jobs.LocalAvailable())
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
//go:build !desktop
|
||||
|
||||
package container
|
||||
|
||||
import (
|
||||
"github.com/redis/go-redis/v9"
|
||||
|
||||
"academy/internal/application/service"
|
||||
"academy/internal/types/interfaces"
|
||||
)
|
||||
|
||||
// newShellJobService is the web constructor dig provides. Host wiring and the
|
||||
// local-job cleaner are desktop-only, so this build ignores them and forwards
|
||||
// to the remote service.
|
||||
func newShellJobService(
|
||||
rdb *redis.Client,
|
||||
pinned *service.PinnedSessionSandbox,
|
||||
bg *service.BackgroundWork,
|
||||
streams interfaces.StreamManager,
|
||||
_ interfaces.ResourceCleaner,
|
||||
_ service.HostSandboxManager,
|
||||
) (*service.ShellJobService, error) {
|
||||
return newRemoteShellJobService(rdb, pinned, bg, streams), nil
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
package container
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"academy/internal/agent/tools"
|
||||
"academy/internal/application/service"
|
||||
"academy/internal/application/service/sandboxalloc"
|
||||
"academy/internal/background"
|
||||
"academy/internal/sandbox"
|
||||
"academy/internal/sandbox/allocation"
|
||||
"academy/internal/stream"
|
||||
"academy/internal/types"
|
||||
"academy/internal/types/interfaces"
|
||||
"github.com/alicebob/miniredis/v2"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestBackgroundActivityRegistrySharesMemoryBindingState(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
store := sandbox.NewMemorySessionSandboxBindingStore()
|
||||
registry := newBackgroundActivityRegistry(store, nil)
|
||||
ref := interfaces.SessionRef{TenantID: 42, SessionID: "s1"}
|
||||
key := sandbox.SessionSandboxKey{TenantID: ref.TenantID, SessionID: ref.SessionID}
|
||||
require.NoError(t, registry.Add(ctx, ref, interfaces.BackgroundActivity{ID: "sj_1"}, time.Minute, 0))
|
||||
require.NoError(t, store.BeginTurn(ctx, key))
|
||||
active, rebuild, err := store.TurnState(ctx, key)
|
||||
require.NoError(t, err)
|
||||
require.True(t, active)
|
||||
require.False(t, rebuild)
|
||||
require.NoError(t, store.EndTurn(ctx, key))
|
||||
_, err = store.TryLockRewind(ctx, key)
|
||||
require.ErrorIs(t, err, sandbox.ErrSessionWorkActive)
|
||||
}
|
||||
|
||||
type backgroundAllocationRepo struct {
|
||||
interfaces.SandboxAllocationRepository
|
||||
assignment *types.SessionSandboxAssignment
|
||||
machine *types.SandboxUserMachine
|
||||
}
|
||||
|
||||
func (r *backgroundAllocationRepo) GetAssignment(context.Context, string) (*types.SessionSandboxAssignment, error) {
|
||||
return r.assignment, nil
|
||||
}
|
||||
|
||||
func (r *backgroundAllocationRepo) GetUserMachine(context.Context, string) (*types.SandboxUserMachine, error) {
|
||||
return r.machine, nil
|
||||
}
|
||||
|
||||
func TestBackgroundActivityRegistryUsesRecordedUserAllocation(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
mini := miniredis.RunT(t)
|
||||
client := redis.NewClient(&redis.Options{Addr: mini.Addr()})
|
||||
t.Cleanup(func() { require.NoError(t, client.Close()) })
|
||||
store, err := sandbox.NewRedisSessionSandboxBindingStore(client, "test")
|
||||
require.NoError(t, err)
|
||||
a := allocation.Assignment{
|
||||
SessionID: "0f8fad5b-d9cb-469f-a165-70867728950e", ConfigTenantID: 42, ConfigID: "cfg-1",
|
||||
Machine: allocation.UserMachine{OwnerTenantID: 42, OwnerID: "u1", ConfigTenantID: 42, ConfigID: "cfg-1"},
|
||||
}
|
||||
row, machine := sandboxalloc.ToEntity(a, a.Machine.Digest("test"))
|
||||
allocations := sandboxalloc.New(&backgroundAllocationRepo{assignment: row, machine: machine}, nil, nil, "test")
|
||||
registry := newBackgroundActivityRegistry(store, allocations)
|
||||
ref := interfaces.SessionRef{TenantID: 42, SessionID: a.SessionID}
|
||||
require.NoError(t, registry.Add(ctx, ref, interfaces.BackgroundActivity{ID: "sj_1"}, time.Minute, 0))
|
||||
key := sandbox.SessionSandboxKey{TenantID: ref.TenantID, SessionID: ref.SessionID, User: a.Machine}
|
||||
active, rebuild, err := store.TurnState(ctx, key)
|
||||
require.NoError(t, err)
|
||||
require.True(t, active, "the production factory must address the same leases as the shared binding store")
|
||||
require.False(t, rebuild)
|
||||
_, err = store.TryLockRewind(ctx, key)
|
||||
require.ErrorIs(t, err, sandbox.ErrSessionWorkActive)
|
||||
}
|
||||
|
||||
func TestBackgroundActivityRegistryUsesRedisBindingStore(t *testing.T) {
|
||||
mini := miniredis.RunT(t)
|
||||
client := redis.NewClient(&redis.Options{Addr: mini.Addr()})
|
||||
t.Cleanup(func() { _ = client.Close() })
|
||||
|
||||
store := newSessionBindingStore(client)
|
||||
require.IsType(t, &sandbox.RedisSessionSandboxBindingStore{}, store)
|
||||
require.IsType(t, &sandbox.RedisActivityRegistry{}, newBackgroundActivityRegistry(store, nil))
|
||||
}
|
||||
|
||||
func TestBackgroundActivityRegistryIsProcessLocalWithoutRedis(t *testing.T) {
|
||||
store := newSessionBindingStore(nil)
|
||||
require.IsType(t, &sandbox.MemorySessionSandboxBindingStore{}, store)
|
||||
require.IsType(t, &sandbox.MemoryActivityRegistry{}, newBackgroundActivityRegistry(store, nil))
|
||||
}
|
||||
|
||||
func TestBackgroundActivityRegistryWithoutBindingStoreIsProcessLocal(t *testing.T) {
|
||||
require.IsType(t, &background.MemoryActivityRegistry{}, newBackgroundActivityRegistry(nil, nil))
|
||||
}
|
||||
|
||||
func TestBackgroundNoticeInboxFollowsTheStreamManager(t *testing.T) {
|
||||
mini := miniredis.RunT(t)
|
||||
redisStreams, err := stream.NewRedisStreamManager(mini.Addr(), "", "", 0, "test", time.Hour)
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { _ = redisStreams.Close() })
|
||||
require.IsType(t, &stream.RedisNoticeInbox{}, newBackgroundNoticeInbox(redisStreams))
|
||||
|
||||
require.IsType(t, &background.MemoryNoticeInbox{}, newBackgroundNoticeInbox(stream.NewMemoryStreamManager()))
|
||||
require.IsType(t, &background.MemoryNoticeInbox{}, newBackgroundNoticeInbox(nil))
|
||||
}
|
||||
|
||||
type nameCleaner struct {
|
||||
names []string
|
||||
stops []types.CleanupFunc
|
||||
}
|
||||
|
||||
func (c *nameCleaner) Register(fn types.CleanupFunc) { c.RegisterWithName("", fn) }
|
||||
|
||||
func (c *nameCleaner) RegisterWithName(name string, fn types.CleanupFunc) {
|
||||
c.names = append(c.names, name)
|
||||
c.stops = append(c.stops, fn)
|
||||
}
|
||||
|
||||
func (c *nameCleaner) Promote(string) {}
|
||||
|
||||
func (c *nameCleaner) Cleanup(context.Context) []error {
|
||||
var errs []error
|
||||
for _, fn := range c.stops {
|
||||
if err := fn(); err != nil {
|
||||
errs = append(errs, err)
|
||||
}
|
||||
}
|
||||
return errs
|
||||
}
|
||||
|
||||
func TestNewShellJobServiceSetsHandler(t *testing.T) {
|
||||
bg := service.NewBackgroundWork(background.NewMemoryActivityRegistry(nil), background.NewMemoryNoticeInbox(nil))
|
||||
svc := newRemoteShellJobService(nil, nil, bg, nil)
|
||||
require.Equal(t, svc, bg.Handler)
|
||||
require.False(t, svc.RemoteAvailable())
|
||||
_, err := svc.SubmitShellJob(context.Background(), interfaces.SessionRef{TenantID: 1, SessionID: "s"},
|
||||
tools.ShellJobSubmitRequest{Command: "true"})
|
||||
require.Error(t, err)
|
||||
}
|
||||
|
||||
func TestShellJobSweeperStartsOnlyWhenRemoteAvailable(t *testing.T) {
|
||||
bg := service.NewBackgroundWork(background.NewMemoryActivityRegistry(nil), background.NewMemoryNoticeInbox(nil))
|
||||
local := newRemoteShellJobService(nil, nil, bg, stream.NewMemoryStreamManager())
|
||||
cleaner := &nameCleaner{}
|
||||
startShellJobSweeper(local, cleaner)
|
||||
require.Empty(t, cleaner.names)
|
||||
|
||||
mini := miniredis.RunT(t)
|
||||
client := redis.NewClient(&redis.Options{Addr: mini.Addr()})
|
||||
t.Cleanup(func() { _ = client.Close() })
|
||||
remoteBG := service.NewBackgroundWork(
|
||||
background.NewMemoryActivityRegistry(nil),
|
||||
background.NewMemoryNoticeInbox(nil),
|
||||
)
|
||||
remote := newRemoteShellJobService(client, &service.PinnedSessionSandbox{}, remoteBG, nil)
|
||||
require.True(t, remote.RemoteAvailable())
|
||||
startShellJobSweeper(remote, cleaner)
|
||||
require.Equal(t, []string{"ShellJobSweeper"}, cleaner.names)
|
||||
for _, err := range cleaner.Cleanup(context.Background()) {
|
||||
require.NoError(t, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
package container
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"academy/internal/types"
|
||||
"academy/internal/types/interfaces"
|
||||
)
|
||||
|
||||
// cleanupStepTimeout bounds one shutdown hook that waits on in-flight work
|
||||
// (cron jobs, retention sweeps). Several of those hooks run before child
|
||||
// processes are reaped; an unbounded wait used to hold SIGTERM until the
|
||||
// supervisor killed the process and skipped the rest.
|
||||
const cleanupStepTimeout = 5 * time.Second
|
||||
|
||||
type cleanupEntry struct {
|
||||
name string
|
||||
fn types.CleanupFunc
|
||||
}
|
||||
|
||||
// ResourceCleaner is a resource cleaner that can be used to clean up resources
|
||||
type ResourceCleaner struct {
|
||||
mu sync.Mutex
|
||||
cleanups []cleanupEntry
|
||||
}
|
||||
|
||||
// NewResourceCleaner creates a new resource cleaner
|
||||
func NewResourceCleaner() interfaces.ResourceCleaner {
|
||||
return &ResourceCleaner{
|
||||
cleanups: make([]cleanupEntry, 0),
|
||||
}
|
||||
}
|
||||
|
||||
// Register registers a cleanup function.
|
||||
// The cleanup function runs in reverse order (the last registered runs first).
|
||||
func (c *ResourceCleaner) Register(cleanup types.CleanupFunc) {
|
||||
c.register("", cleanup)
|
||||
}
|
||||
|
||||
// RegisterWithName registers a cleanup function with a name, for logging tracking.
|
||||
func (c *ResourceCleaner) RegisterWithName(name string, cleanup types.CleanupFunc) {
|
||||
if cleanup == nil {
|
||||
return
|
||||
}
|
||||
|
||||
wrappedCleanup := func() error {
|
||||
log.Printf("Cleaning up resource: %s", name)
|
||||
err := cleanup()
|
||||
if err != nil {
|
||||
log.Printf("Error cleaning up resource %s: %v", name, err)
|
||||
} else {
|
||||
log.Printf("Successfully cleaned up resource: %s", name)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
c.register(name, wrappedCleanup)
|
||||
}
|
||||
|
||||
func (c *ResourceCleaner) register(name string, cleanup types.CleanupFunc) {
|
||||
if cleanup == nil {
|
||||
return
|
||||
}
|
||||
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
c.cleanups = append(c.cleanups, cleanupEntry{name: name, fn: cleanup})
|
||||
}
|
||||
|
||||
// Promote moves every callback registered under name to the end of the list.
|
||||
// Cleanup runs in reverse, so the promoted callbacks run first. BrowserSkill
|
||||
// is registered during early container wiring and would otherwise run last,
|
||||
// after hooks that wait on in-flight jobs.
|
||||
func (c *ResourceCleaner) Promote(name string) {
|
||||
if name == "" {
|
||||
return
|
||||
}
|
||||
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
|
||||
matched := make([]cleanupEntry, 0, 1)
|
||||
rest := make([]cleanupEntry, 0, len(c.cleanups))
|
||||
for _, entry := range c.cleanups {
|
||||
if entry.name == name {
|
||||
matched = append(matched, entry)
|
||||
continue
|
||||
}
|
||||
rest = append(rest, entry)
|
||||
}
|
||||
c.cleanups = append(rest, matched...)
|
||||
}
|
||||
|
||||
// Cleanup executes all cleanup functions.
|
||||
// A cancelled or expired context does not skip remaining functions: the
|
||||
// deadline used to return on the first select and drop every later hook,
|
||||
// including ones registered earliest (BrowserSkill). Context errors are not
|
||||
// reported as hook failures when the hooks themselves still ran.
|
||||
func (c *ResourceCleaner) Cleanup(ctx context.Context) (errs []error) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
|
||||
for i := len(c.cleanups) - 1; i >= 0; i-- {
|
||||
if err := c.cleanups[i].fn(); err != nil {
|
||||
errs = append(errs, err)
|
||||
}
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
log.Printf("Resource cleanup continued past its deadline: %v", err)
|
||||
}
|
||||
return errs
|
||||
}
|
||||
|
||||
// Reset clears all registered cleanup functions
|
||||
func (c *ResourceCleaner) Reset() {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
|
||||
c.cleanups = make([]cleanupEntry, 0)
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package container
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestCleanupRunsRemainingHooksAfterDeadline(t *testing.T) {
|
||||
cleaner := NewResourceCleaner()
|
||||
var ran []string
|
||||
// Registered first, so it runs last unless promoted. This is BrowserSkill's
|
||||
// position: an earlier slow hook must not cause it to be skipped.
|
||||
cleaner.RegisterWithName("tail", func() error {
|
||||
ran = append(ran, "tail")
|
||||
return nil
|
||||
})
|
||||
cleaner.RegisterWithName("slow", func() error {
|
||||
time.Sleep(40 * time.Millisecond)
|
||||
ran = append(ran, "slow")
|
||||
return errors.New("slow failed")
|
||||
})
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond)
|
||||
defer cancel()
|
||||
errs := cleaner.Cleanup(ctx)
|
||||
if len(ran) != 2 || ran[0] != "slow" || ran[1] != "tail" {
|
||||
t.Fatalf("ran = %v, want slow then tail", ran)
|
||||
}
|
||||
if len(errs) != 1 || errs[0].Error() != "slow failed" {
|
||||
t.Fatalf("errs = %v, want only the hook error", errs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPromoteRunsNamedHookFirst(t *testing.T) {
|
||||
cleaner := NewResourceCleaner()
|
||||
var ran []string
|
||||
cleaner.RegisterWithName("BrowserSkill", func() error {
|
||||
ran = append(ran, "browser")
|
||||
return nil
|
||||
})
|
||||
cleaner.RegisterWithName("later", func() error {
|
||||
ran = append(ran, "later")
|
||||
return nil
|
||||
})
|
||||
cleaner.Promote("BrowserSkill")
|
||||
|
||||
if errs := cleaner.Cleanup(context.Background()); len(errs) != 0 {
|
||||
t.Fatalf("errs = %v", errs)
|
||||
}
|
||||
if len(ran) != 2 || ran[0] != "browser" || ran[1] != "later" {
|
||||
t.Fatalf("ran = %v, want browser then later", ran)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCleanupAlreadyCanceledContextStillRunsHooks(t *testing.T) {
|
||||
cleaner := NewResourceCleaner()
|
||||
var n int
|
||||
cleaner.Register(func() error {
|
||||
n++
|
||||
return nil
|
||||
})
|
||||
cleaner.Register(func() error {
|
||||
n++
|
||||
return nil
|
||||
})
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
if errs := cleaner.Cleanup(ctx); len(errs) != 0 {
|
||||
t.Fatalf("errs = %v", errs)
|
||||
}
|
||||
if n != 2 {
|
||||
t.Fatalf("ran %d hooks, want 2", n)
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,39 @@
|
||||
package container
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"academy/internal/datasource"
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
func TestConnectorRegistryIncludesDingTalk(t *testing.T) {
|
||||
registry, err := initConnectorRegistry()
|
||||
if err != nil {
|
||||
t.Fatalf("initConnectorRegistry() error = %v", err)
|
||||
}
|
||||
connector, err := registry.Get(types.ConnectorTypeDingTalk)
|
||||
if err != nil {
|
||||
t.Fatalf("DingTalk connector is not registered: %v", err)
|
||||
}
|
||||
if connector.Type() != types.ConnectorTypeDingTalk {
|
||||
t.Fatalf("connector.Type() = %q", connector.Type())
|
||||
}
|
||||
}
|
||||
|
||||
func TestConnectorRegistryIncludesSeafile(t *testing.T) {
|
||||
registry, err := initConnectorRegistry()
|
||||
if err != nil {
|
||||
t.Fatalf("initConnectorRegistry() error = %v", err)
|
||||
}
|
||||
connector, err := registry.Get(types.ConnectorTypeSeafile)
|
||||
if err != nil {
|
||||
t.Fatalf("Seafile connector is not registered: %v", err)
|
||||
}
|
||||
if connector.Type() != types.ConnectorTypeSeafile {
|
||||
t.Fatalf("connector.Type() = %q", connector.Type())
|
||||
}
|
||||
if _, ok := connector.(datasource.FullStreamingConnector); !ok {
|
||||
t.Fatal("Seafile connector must implement datasource.FullStreamingConnector")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,391 @@
|
||||
package container
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"net"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
esv7 "github.com/elastic/go-elasticsearch/v7"
|
||||
"github.com/elastic/go-elasticsearch/v8"
|
||||
"github.com/go-sql-driver/mysql" // 通过 database/sql 注册 mysql 驱动给 Doris 使用
|
||||
"github.com/milvus-io/milvus/client/v2/milvusclient"
|
||||
"github.com/qdrant/go-client/qdrant"
|
||||
"github.com/weaviate/weaviate-go-client/v5/weaviate"
|
||||
"github.com/weaviate/weaviate-go-client/v5/weaviate/auth"
|
||||
wgrpc "github.com/weaviate/weaviate-go-client/v5/weaviate/grpc"
|
||||
"google.golang.org/grpc"
|
||||
"gorm.io/gorm"
|
||||
|
||||
dorisRepo "academy/internal/application/repository/retriever/doris"
|
||||
elasticsearchRepoV7 "academy/internal/application/repository/retriever/elasticsearch/v7"
|
||||
elasticsearchRepoV8 "academy/internal/application/repository/retriever/elasticsearch/v8"
|
||||
milvusRepo "academy/internal/application/repository/retriever/milvus"
|
||||
openSearchRepo "academy/internal/application/repository/retriever/opensearch"
|
||||
postgresRepo "academy/internal/application/repository/retriever/postgres"
|
||||
qdrantRepo "academy/internal/application/repository/retriever/qdrant"
|
||||
sqliteRetrieverRepo "academy/internal/application/repository/retriever/sqlite"
|
||||
tencentVectorDBRepo "academy/internal/application/repository/retriever/tencentvectordb"
|
||||
weaviateRepo "academy/internal/application/repository/retriever/weaviate"
|
||||
"academy/internal/application/service/retriever"
|
||||
"academy/internal/config"
|
||||
"academy/internal/types"
|
||||
"academy/internal/types/interfaces"
|
||||
"academy/internal/utils"
|
||||
"github.com/tencent/vectordatabase-sdk-go/tcvectordb"
|
||||
)
|
||||
|
||||
// NewEngineFactory returns an EngineFactory function closed over db, cfg, and
|
||||
// an audit sink (built from the AuditLogService). Registered in dig and
|
||||
// injected into VectorStoreService for dynamic registry updates. The
|
||||
// EngineFactory type itself is unchanged — the audit sink is captured in the
|
||||
// closure rather than added to the signature.
|
||||
func NewEngineFactory(db *gorm.DB, cfg *config.Config, auditSvc interfaces.AuditLogService) interfaces.EngineFactory {
|
||||
sink := newAuditSinkAdapter(auditSvc)
|
||||
return func(ctx context.Context, store types.VectorStore) (interfaces.RetrieveEngineService, error) {
|
||||
return createEngineServiceFromStore(ctx, store, db, cfg, sink)
|
||||
}
|
||||
}
|
||||
|
||||
// createEngineServiceFromStore creates a RetrieveEngineService from a VectorStore's config.
|
||||
// This is the DB store counterpart of the env-based initialization in initRetrieveEngineRegistry.
|
||||
// auditSink may be nil (audit becomes a no-op).
|
||||
func createEngineServiceFromStore(
|
||||
ctx context.Context,
|
||||
store types.VectorStore,
|
||||
db *gorm.DB,
|
||||
cfg *config.Config,
|
||||
auditSink openSearchRepo.AuditSink,
|
||||
) (interfaces.RetrieveEngineService, error) {
|
||||
if err := validateRuntimeVectorStoreAddresses(store); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
switch store.EngineType {
|
||||
case types.PostgresRetrieverEngineType:
|
||||
return createPostgresEngine(store, db)
|
||||
case types.ElasticsearchRetrieverEngineType:
|
||||
return createElasticsearchEngine(store, cfg)
|
||||
case types.QdrantRetrieverEngineType:
|
||||
return createQdrantEngine(store)
|
||||
case types.MilvusRetrieverEngineType:
|
||||
return createMilvusEngine(ctx, store)
|
||||
case types.WeaviateRetrieverEngineType:
|
||||
return createWeaviateEngine(store)
|
||||
case types.DorisRetrieverEngineType:
|
||||
return createDorisEngine(store)
|
||||
case types.SQLiteRetrieverEngineType:
|
||||
return createSQLiteEngine(store, db)
|
||||
case types.TencentVectorDBRetrieverEngineType:
|
||||
return createTencentVectorDBEngine(store)
|
||||
case types.OpenSearchRetrieverEngineType:
|
||||
return createOpenSearchEngine(ctx, store, auditSink)
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported engine type: %s", store.EngineType)
|
||||
}
|
||||
}
|
||||
|
||||
// validateRuntimeVectorStoreAddresses is the final guard for persisted or
|
||||
// imported vector-store rows. Create/test handlers validate the same fields at
|
||||
// the input boundary, but runtime construction must not assume every stored row
|
||||
// was written through those handlers.
|
||||
func validateRuntimeVectorStoreAddresses(store types.VectorStore) error {
|
||||
cc := store.ConnectionConfig
|
||||
check := func(label, endpoint string) error {
|
||||
endpoint = strings.TrimSpace(endpoint)
|
||||
if endpoint == "" {
|
||||
return nil
|
||||
}
|
||||
if err := utils.ValidateURLForSSRF(endpoint); err != nil {
|
||||
return fmt.Errorf("%s failed SSRF validation: %w", label, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
switch store.EngineType {
|
||||
case types.PostgresRetrieverEngineType, types.SQLiteRetrieverEngineType:
|
||||
return nil
|
||||
case types.ElasticsearchRetrieverEngineType,
|
||||
types.OpenSearchRetrieverEngineType,
|
||||
types.MilvusRetrieverEngineType,
|
||||
types.TencentVectorDBRetrieverEngineType,
|
||||
types.DorisRetrieverEngineType:
|
||||
return check("vector store address", cc.Addr)
|
||||
case types.QdrantRetrieverEngineType:
|
||||
endpoint := cc.Host
|
||||
if endpoint != "" && cc.Port != 0 {
|
||||
endpoint = net.JoinHostPort(strings.Trim(cc.Host, "[]"), strconv.Itoa(cc.Port))
|
||||
}
|
||||
return check("qdrant address", endpoint)
|
||||
case types.WeaviateRetrieverEngineType:
|
||||
if err := check("weaviate HTTP address", cc.Host); err != nil {
|
||||
return err
|
||||
}
|
||||
return check("weaviate gRPC address", cc.GrpcAddress)
|
||||
default:
|
||||
return fmt.Errorf("vector store engine %q has no SSRF address policy", store.EngineType)
|
||||
}
|
||||
}
|
||||
|
||||
// createOpenSearchEngine builds an OpenSearch k-NN retrieve engine. Mirrors
|
||||
// createElasticsearchV8Engine but uses the driver's TLS-hardened client
|
||||
// constructor and injects the audit sink. NewRepository probes the cluster
|
||||
// (version + k-NN plugin), so an unreachable cluster fails here at
|
||||
// registration rather than on first query.
|
||||
func createOpenSearchEngine(
|
||||
ctx context.Context, store types.VectorStore, auditSink openSearchRepo.AuditSink,
|
||||
) (interfaces.RetrieveEngineService, error) {
|
||||
client, err := openSearchRepo.NewOpenSearchClient(&store.ConnectionConfig)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create opensearch client: %w", err)
|
||||
}
|
||||
// Env stores share the cluster without a per-store index prefix; DB stores
|
||||
// fold their (>=16-char) ID into the index name. NewRepository enforces the
|
||||
// length rule, so map env-store IDs to "".
|
||||
storeID := store.ID
|
||||
if types.IsEnvStoreID(storeID) {
|
||||
storeID = ""
|
||||
}
|
||||
repo, err := openSearchRepo.NewRepository(ctx, client, storeID, &store.IndexConfig,
|
||||
openSearchRepo.WithAuditSink(auditSink))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create opensearch repository: %w", err)
|
||||
}
|
||||
return retriever.NewKVHybridRetrieveEngine(repo, types.OpenSearchRetrieverEngineType), nil
|
||||
}
|
||||
|
||||
func createPostgresEngine(store types.VectorStore, db *gorm.DB) (interfaces.RetrieveEngineService, error) {
|
||||
if store.ConnectionConfig.UseDefaultConnection {
|
||||
repo := postgresRepo.NewPostgresRetrieveEngineRepository(db)
|
||||
return retriever.NewKVHybridRetrieveEngine(repo, types.PostgresRetrieverEngineType), nil
|
||||
}
|
||||
// Phase 1: only UseDefaultConnection is supported.
|
||||
// Custom connections require connection pool management and migration handling.
|
||||
return nil, fmt.Errorf("custom postgres connections not yet supported; use use_default_connection=true")
|
||||
}
|
||||
|
||||
func createSQLiteEngine(_ types.VectorStore, db *gorm.DB) (interfaces.RetrieveEngineService, error) {
|
||||
repo := sqliteRetrieverRepo.NewSQLiteRetrieveEngineRepository(db)
|
||||
return retriever.NewKVHybridRetrieveEngine(repo, types.SQLiteRetrieverEngineType), nil
|
||||
}
|
||||
|
||||
func createElasticsearchEngine(store types.VectorStore, cfg *config.Config) (interfaces.RetrieveEngineService, error) {
|
||||
cc := store.ConnectionConfig
|
||||
// Version-based v7/v8 SDK selection.
|
||||
// Version is auto-detected by PR2's TestConnection and saved to connection_config.
|
||||
// Empty version defaults to v8 (latest SDK).
|
||||
if isESv7(cc.Version) {
|
||||
return createElasticsearchV7Engine(store, cfg)
|
||||
}
|
||||
return createElasticsearchV8Engine(store, cfg)
|
||||
}
|
||||
|
||||
// isESv7 checks if the detected ES version is 7.x.
|
||||
func isESv7(version string) bool {
|
||||
return strings.HasPrefix(version, "7.")
|
||||
}
|
||||
|
||||
func createElasticsearchV8Engine(store types.VectorStore, cfg *config.Config) (interfaces.RetrieveEngineService, error) {
|
||||
cc := store.ConnectionConfig
|
||||
if err := utils.ValidateURLForSSRF(cc.Addr); err != nil {
|
||||
return nil, fmt.Errorf("elasticsearch address failed SSRF validation: %w", err)
|
||||
}
|
||||
client, err := elasticsearch.NewTypedClient(elasticsearch.Config{
|
||||
Addresses: []string{cc.Addr},
|
||||
Username: cc.Username,
|
||||
Password: cc.Password,
|
||||
Transport: &utils.SSRFValidatingRoundTripper{
|
||||
Base: utils.NewSSRFSafeTransport(utils.DefaultSSRFSafeHTTPClientConfig()),
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create elasticsearch v8 client: %w", err)
|
||||
}
|
||||
repo := elasticsearchRepoV8.NewElasticsearchEngineRepository(client, cfg, &store.IndexConfig)
|
||||
return retriever.NewKVHybridRetrieveEngine(repo, types.ElasticsearchRetrieverEngineType), nil
|
||||
}
|
||||
|
||||
func createElasticsearchV7Engine(store types.VectorStore, cfg *config.Config) (interfaces.RetrieveEngineService, error) {
|
||||
cc := store.ConnectionConfig
|
||||
if err := utils.ValidateURLForSSRF(cc.Addr); err != nil {
|
||||
return nil, fmt.Errorf("elasticsearch address failed SSRF validation: %w", err)
|
||||
}
|
||||
client, err := esv7.NewClient(esv7.Config{
|
||||
Addresses: []string{cc.Addr},
|
||||
Username: cc.Username,
|
||||
Password: cc.Password,
|
||||
Transport: &utils.SSRFValidatingRoundTripper{
|
||||
Base: utils.NewSSRFSafeTransport(utils.DefaultSSRFSafeHTTPClientConfig()),
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create elasticsearch v7 client: %w", err)
|
||||
}
|
||||
repo := elasticsearchRepoV7.NewElasticsearchEngineRepository(client, cfg, &store.IndexConfig)
|
||||
return retriever.NewKVHybridRetrieveEngine(repo, types.ElasticsearchRetrieverEngineType), nil
|
||||
}
|
||||
|
||||
func createQdrantEngine(store types.VectorStore) (interfaces.RetrieveEngineService, error) {
|
||||
cc := store.ConnectionConfig
|
||||
port := cc.Port
|
||||
if port == 0 {
|
||||
port = 6334
|
||||
}
|
||||
|
||||
client, err := qdrant.NewClient(&qdrant.Config{
|
||||
Host: cc.Host,
|
||||
Port: port,
|
||||
APIKey: cc.APIKey,
|
||||
UseTLS: cc.UseTLS,
|
||||
GrpcOptions: []grpc.DialOption{grpc.WithContextDialer(utils.SSRFSafeGRPCDialer)},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create qdrant client: %w", err)
|
||||
}
|
||||
repo := qdrantRepo.NewQdrantRetrieveEngineRepository(client, &store.IndexConfig)
|
||||
return retriever.NewKVHybridRetrieveEngine(repo, types.QdrantRetrieverEngineType), nil
|
||||
}
|
||||
|
||||
func createMilvusEngine(ctx context.Context, store types.VectorStore) (interfaces.RetrieveEngineService, error) {
|
||||
milvusCfg := buildMilvusClientConfig(store.ConnectionConfig)
|
||||
client, err := milvusclient.New(ctx, &milvusCfg)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create milvus client: %w", err)
|
||||
}
|
||||
repo := milvusRepo.NewMilvusRetrieveEngineRepository(client, &store.IndexConfig)
|
||||
return retriever.NewKVHybridRetrieveEngine(repo, types.MilvusRetrieverEngineType), nil
|
||||
}
|
||||
|
||||
func buildMilvusClientConfig(cc types.ConnectionConfig) milvusclient.ClientConfig {
|
||||
addr := cc.Addr
|
||||
if addr == "" {
|
||||
addr = "localhost:19530"
|
||||
}
|
||||
|
||||
milvusCfg := milvusclient.ClientConfig{
|
||||
Address: addr,
|
||||
DialOptions: []grpc.DialOption{
|
||||
grpc.WithTimeout(5 * time.Second),
|
||||
grpc.WithContextDialer(utils.SSRFSafeGRPCDialer),
|
||||
},
|
||||
}
|
||||
if cc.Username != "" {
|
||||
milvusCfg.Username = cc.Username
|
||||
}
|
||||
if cc.Password != "" {
|
||||
milvusCfg.Password = cc.Password
|
||||
}
|
||||
if cc.Database != "" {
|
||||
milvusCfg.DBName = cc.Database
|
||||
}
|
||||
return milvusCfg
|
||||
}
|
||||
|
||||
func createWeaviateEngine(store types.VectorStore) (interfaces.RetrieveEngineService, error) {
|
||||
cc := store.ConnectionConfig
|
||||
host := cc.Host
|
||||
if host == "" {
|
||||
host = "weaviate:8080"
|
||||
}
|
||||
grpcAddress := cc.GrpcAddress
|
||||
if grpcAddress == "" {
|
||||
grpcAddress = "weaviate:50051"
|
||||
}
|
||||
scheme := cc.Scheme
|
||||
if scheme == "" {
|
||||
scheme = "http"
|
||||
}
|
||||
|
||||
weaviateCfg := weaviate.Config{
|
||||
Host: host,
|
||||
ConnectionClient: utils.NewSSRFSafeHTTPClient(utils.DefaultSSRFSafeHTTPClientConfig()),
|
||||
GrpcConfig: &wgrpc.Config{
|
||||
Host: grpcAddress,
|
||||
},
|
||||
Scheme: scheme,
|
||||
}
|
||||
// Unlike the env path (which checks WEAVIATE_AUTH_ENABLED), the factory uses
|
||||
// APIKey directly — if a user provides it, they intend to use it.
|
||||
if cc.APIKey != "" {
|
||||
weaviateCfg.AuthConfig = auth.ApiKey{Value: cc.APIKey}
|
||||
}
|
||||
|
||||
client, err := weaviate.NewClient(weaviateCfg)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create weaviate client: %w", err)
|
||||
}
|
||||
repo := weaviateRepo.NewWeaviateRetrieveEngineRepository(client, &store.IndexConfig)
|
||||
return retriever.NewKVHybridRetrieveEngine(repo, types.WeaviateRetrieverEngineType), nil
|
||||
}
|
||||
|
||||
// createDorisEngine 创建 Apache Doris 检索引擎服务。
|
||||
//
|
||||
// Doris 同时使用两个端口:
|
||||
// - MySQL 协议(默认 9030)走 database/sql 做主链路读写;
|
||||
// - HTTP(默认 FE 8030)走 Stream Load 做 partial update。
|
||||
//
|
||||
// Addr 字段承担 host:9030 的 MySQL 端点;HTTPPort + Addr 的 host 部分组成 HTTP base URL。
|
||||
func createDorisEngine(store types.VectorStore) (interfaces.RetrieveEngineService, error) {
|
||||
cc := store.ConnectionConfig
|
||||
if cc.Addr == "" {
|
||||
return nil, fmt.Errorf("doris connection requires addr (host:port)")
|
||||
}
|
||||
if cc.Database == "" {
|
||||
return nil, fmt.Errorf("doris connection requires database")
|
||||
}
|
||||
|
||||
mc := mysql.NewConfig()
|
||||
mc.User = cc.Username
|
||||
mc.Passwd = cc.Password
|
||||
utils.RegisterMySQLSSRFDialer()
|
||||
mc.Net = utils.MySQLSSRFNetwork
|
||||
mc.Addr = cc.Addr
|
||||
mc.DBName = cc.Database
|
||||
mc.Params = map[string]string{"charset": "utf8mb4"}
|
||||
mc.ParseTime = true
|
||||
mc.Loc = time.Local
|
||||
db, err := sql.Open("mysql", mc.FormatDSN())
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create doris client: %w", err)
|
||||
}
|
||||
db.SetMaxOpenConns(20)
|
||||
db.SetMaxIdleConns(5)
|
||||
db.SetConnMaxLifetime(time.Hour)
|
||||
|
||||
httpPort := cc.HTTPPort
|
||||
if httpPort <= 0 {
|
||||
httpPort = 8030
|
||||
}
|
||||
httpBase := "http://" + hostFromAddr(cc.Addr) + ":" + strconv.Itoa(httpPort)
|
||||
|
||||
repo := dorisRepo.NewDorisRetrieveEngineRepository(
|
||||
db, httpBase, cc.Username, cc.Password, cc.Database, &store.IndexConfig,
|
||||
)
|
||||
return retriever.NewKVHybridRetrieveEngine(repo, types.DorisRetrieverEngineType), nil
|
||||
}
|
||||
|
||||
// hostFromAddr 从 "host:port" 中拆出 host 部分;Addr 没有冒号时整段当作 host。
|
||||
func hostFromAddr(addr string) string {
|
||||
if i := strings.LastIndex(addr, ":"); i > 0 {
|
||||
return addr[:i]
|
||||
}
|
||||
return addr
|
||||
}
|
||||
|
||||
func createTencentVectorDBEngine(store types.VectorStore) (interfaces.RetrieveEngineService, error) {
|
||||
cc := store.ConnectionConfig
|
||||
client, err := tcvectordb.NewRpcClient(cc.Addr, cc.Username, cc.APIKey, &tcvectordb.ClientOption{
|
||||
ReadConsistency: tcvectordb.EventualConsistency,
|
||||
Timeout: 10 * time.Second,
|
||||
Transport: &utils.SSRFValidatingRoundTripper{
|
||||
Base: utils.NewSSRFSafeTransport(utils.DefaultSSRFSafeHTTPClientConfig()),
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create tencent vectordb client: %w", err)
|
||||
}
|
||||
repo := tencentVectorDBRepo.NewTencentVectorDBRetrieveEngineRepository(client, cc.Database, &store.IndexConfig)
|
||||
return retriever.NewKVHybridRetrieveEngine(repo, types.TencentVectorDBRetrieverEngineType), nil
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
package container
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"academy/internal/config"
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
// osClusterHandler simulates an OpenSearch cluster for the driver's
|
||||
// construction probe: GET / (version) + /_cat/plugins (k-NN on every node).
|
||||
func osClusterHandler(distribution, number string, knnInstalled bool) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
if r.URL.Path == "/_cat/plugins" {
|
||||
if knnInstalled {
|
||||
_, _ = w.Write([]byte(`[{"name":"node-1","component":"opensearch-knn"}]`))
|
||||
} else {
|
||||
_, _ = w.Write([]byte(`[{"name":"node-1","component":"opensearch-sql"}]`))
|
||||
}
|
||||
return
|
||||
}
|
||||
_, _ = w.Write([]byte(`{"version":{"distribution":"` + distribution + `","number":"` + number + `"}}`))
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateOpenSearchEngine_WiresClientAndRepo(t *testing.T) {
|
||||
ts := httptest.NewServer(osClusterHandler("opensearch", "3.3.2", true))
|
||||
defer ts.Close()
|
||||
|
||||
store := types.VectorStore{
|
||||
ID: "", // env-style (no index prefix)
|
||||
EngineType: types.OpenSearchRetrieverEngineType,
|
||||
ConnectionConfig: types.ConnectionConfig{Addr: ts.URL},
|
||||
}
|
||||
svc, err := createOpenSearchEngine(context.Background(), store, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("createOpenSearchEngine: %v", err)
|
||||
}
|
||||
if svc == nil {
|
||||
t.Fatal("want non-nil engine service")
|
||||
}
|
||||
if svc.EngineType() != types.OpenSearchRetrieverEngineType {
|
||||
t.Errorf("engine type: want opensearch, got %s", svc.EngineType())
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateOpenSearchEngine_RejectsBadCluster(t *testing.T) {
|
||||
// Elasticsearch distribution must be rejected at construction.
|
||||
ts := httptest.NewServer(osClusterHandler("elasticsearch", "8.10.4", true))
|
||||
defer ts.Close()
|
||||
_, err := createOpenSearchEngine(context.Background(),
|
||||
types.VectorStore{EngineType: types.OpenSearchRetrieverEngineType,
|
||||
ConnectionConfig: types.ConnectionConfig{Addr: ts.URL}}, nil)
|
||||
if err == nil {
|
||||
t.Error("elasticsearch cluster should be rejected at engine creation")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateEngineServiceFromStore_OpenSearchCaseReached(t *testing.T) {
|
||||
ts := httptest.NewServer(osClusterHandler("opensearch", "2.11.0", true))
|
||||
defer ts.Close()
|
||||
svc, err := createEngineServiceFromStore(context.Background(),
|
||||
types.VectorStore{EngineType: types.OpenSearchRetrieverEngineType,
|
||||
ConnectionConfig: types.ConnectionConfig{Addr: ts.URL}},
|
||||
nil, &config.Config{}, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("createEngineServiceFromStore (opensearch case): %v", err)
|
||||
}
|
||||
if svc == nil || svc.EngineType() != types.OpenSearchRetrieverEngineType {
|
||||
t.Errorf("opensearch case not wired correctly: %v", svc)
|
||||
}
|
||||
}
|
||||
|
||||
// TestInitRetrieveEngineRegistry_OpenSearchEnvPath exercises the
|
||||
// RETRIEVE_DRIVER=opensearch env-path registration block end to end.
|
||||
func TestInitRetrieveEngineRegistry_OpenSearchEnvPath(t *testing.T) {
|
||||
ts := httptest.NewServer(osClusterHandler("opensearch", "3.3.2", true))
|
||||
defer ts.Close()
|
||||
|
||||
// In-memory DB: the vector_stores table is absent, so loadDBStores logs
|
||||
// and returns (non-fatal) — only the env-path block matters here.
|
||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
||||
if err != nil {
|
||||
t.Fatalf("open in-mem db: %v", err)
|
||||
}
|
||||
|
||||
t.Setenv("RETRIEVE_DRIVER", "opensearch")
|
||||
t.Setenv("OPENSEARCH_ADDR", ts.URL)
|
||||
|
||||
// nil store repository and engine factory: this exercises the env-driver
|
||||
// path, which never rebuilds a database-backed store.
|
||||
registry, err := initRetrieveEngineRegistry(db, &config.Config{}, &fakeAuditSvc{}, nil, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("initRetrieveEngineRegistry: %v", err)
|
||||
}
|
||||
if _, err := registry.GetRetrieveEngineService(types.OpenSearchRetrieverEngineType); err != nil {
|
||||
t.Errorf("opensearch engine not registered via env path: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package container
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
func TestBuildMilvusClientConfig_UsesDatabaseName(t *testing.T) {
|
||||
cfg := buildMilvusClientConfig(types.ConnectionConfig{
|
||||
Addr: "milvus.example.com:19530",
|
||||
Username: "tester",
|
||||
Password: "secret",
|
||||
Database: "regdi_ram_haom1",
|
||||
})
|
||||
|
||||
if cfg.Address != "milvus.example.com:19530" {
|
||||
t.Fatalf("expected address to be preserved, got %q", cfg.Address)
|
||||
}
|
||||
if cfg.Username != "tester" {
|
||||
t.Fatalf("expected username to be preserved, got %q", cfg.Username)
|
||||
}
|
||||
if cfg.Password != "secret" {
|
||||
t.Fatalf("expected password to be preserved, got %q", cfg.Password)
|
||||
}
|
||||
if cfg.DBName != "regdi_ram_haom1" {
|
||||
t.Fatalf("expected DBName to be propagated, got %q", cfg.DBName)
|
||||
}
|
||||
if len(cfg.DialOptions) != 2 {
|
||||
t.Fatalf("expected timeout and SSRF-safe dial options, got %d", len(cfg.DialOptions))
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildMilvusClientConfig_DefaultsAddressWhenMissing(t *testing.T) {
|
||||
cfg := buildMilvusClientConfig(types.ConnectionConfig{})
|
||||
|
||||
if cfg.Address != "localhost:19530" {
|
||||
t.Fatalf("expected default address localhost:19530, got %q", cfg.Address)
|
||||
}
|
||||
if cfg.DBName != "" {
|
||||
t.Fatalf("expected empty DBName by default, got %q", cfg.DBName)
|
||||
}
|
||||
if len(cfg.DialOptions) != 2 {
|
||||
t.Fatalf("expected timeout and SSRF-safe dial options, got %d", len(cfg.DialOptions))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package container
|
||||
|
||||
import (
|
||||
"io"
|
||||
stdlog "log"
|
||||
"time"
|
||||
|
||||
gormlogger "gorm.io/gorm/logger"
|
||||
)
|
||||
|
||||
// gormSlowSQLThreshold is GORM's default slow-query threshold. Statements
|
||||
// faster than this are not logged at Warn.
|
||||
const gormSlowSQLThreshold = 200 * time.Millisecond
|
||||
|
||||
// newGormLogger is the application database logger. It matches GORM's
|
||||
// default slow-SQL threshold (200ms), Warn level, and record-not-found
|
||||
// handling. ParameterizedQueries is set so slow-query logs keep the SQL
|
||||
// text and timing but omit bound values such as chunk text and vectors.
|
||||
func newGormLogger(w io.Writer) gormlogger.Interface {
|
||||
return gormlogger.New(stdlog.New(w, "\r\n", stdlog.LstdFlags), gormlogger.Config{
|
||||
SlowThreshold: gormSlowSQLThreshold,
|
||||
LogLevel: gormlogger.Warn,
|
||||
IgnoreRecordNotFoundError: false,
|
||||
Colorful: true,
|
||||
ParameterizedQueries: true,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package container
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// TestNewGormLoggerSlowSQLOmitsBoundParameters is the regression test for
|
||||
// issue #4543: a slow statement must still log SQL text and timing, but the
|
||||
// bound chunk text and embedding vector must not appear in the log line.
|
||||
//
|
||||
// The production break this catches is ParameterizedQueries left false (or the
|
||||
// logger omitted), which makes GORM inline every bound value before Trace.
|
||||
func TestNewGormLoggerSlowSQLOmitsBoundParameters(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{
|
||||
Logger: newGormLogger(&buf),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("gorm.Open: %v", err)
|
||||
}
|
||||
// GORM's default slow threshold is 200ms. Sleep inside the callback so the
|
||||
// measured statement is slow without depending on the host database.
|
||||
if err := db.Callback().Raw().Before("gorm:raw").Register("test:slow", func(*gorm.DB) {
|
||||
time.Sleep(250 * time.Millisecond)
|
||||
}); err != nil {
|
||||
t.Fatalf("register slow callback: %v", err)
|
||||
}
|
||||
|
||||
const chunk = "SECRET_CHUNK_TEXT_do_not_log_9f3a7c1e"
|
||||
vector := "[" + strings.Repeat("0.123456789,", 32) + "0.5]"
|
||||
if err := db.Exec("SELECT ?, ?", chunk, vector).Error; err != nil {
|
||||
t.Fatalf("exec: %v", err)
|
||||
}
|
||||
|
||||
logged := buf.String()
|
||||
if strings.Contains(logged, chunk) {
|
||||
t.Fatalf("slow SQL log included bound chunk text:\n%s", logged)
|
||||
}
|
||||
if strings.Contains(logged, "0.123456789") {
|
||||
t.Fatalf("slow SQL log included embedding vector values:\n%s", logged)
|
||||
}
|
||||
if !strings.Contains(logged, "SLOW SQL") {
|
||||
t.Fatalf("expected a slow SQL log entry, got %q", logged)
|
||||
}
|
||||
if !strings.Contains(logged, "SELECT") {
|
||||
t.Fatalf("slow SQL log should still include the SQL text, got %q", logged)
|
||||
}
|
||||
if !strings.Contains(logged, "?") {
|
||||
t.Fatalf("slow SQL log should keep placeholders, got %q", logged)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
//go:build desktop
|
||||
|
||||
package container
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
|
||||
"gorm.io/gorm"
|
||||
|
||||
"academy/internal/handler/session"
|
||||
"academy/internal/localsandbox"
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
type hostProjectLookupImpl struct {
|
||||
db *gorm.DB
|
||||
approved func() []string
|
||||
}
|
||||
|
||||
func newHostProjectLookup(db *gorm.DB, approved func() []string) localsandbox.ProjectLookup {
|
||||
return &hostProjectLookupImpl{db: db, approved: approved}
|
||||
}
|
||||
|
||||
func hostProjectLookup(db *gorm.DB, dirs session.HostProjectDirsLoader) localsandbox.ProjectLookup {
|
||||
return newHostProjectLookup(db, dirs)
|
||||
}
|
||||
|
||||
func (l *hostProjectLookupImpl) ProjectDirForSession(ctx context.Context, sessionID string) (string, bool, error) {
|
||||
sessionID = strings.TrimSpace(sessionID)
|
||||
if l == nil || l.db == nil || sessionID == "" {
|
||||
return "", false, nil
|
||||
}
|
||||
var sess types.Session
|
||||
err := l.db.WithContext(ctx).
|
||||
Select("host_workspace_dir").
|
||||
Where("id = ?", sessionID).
|
||||
First(&sess).Error
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return "", false, nil
|
||||
}
|
||||
return "", false, err
|
||||
}
|
||||
raw := strings.TrimSpace(sess.HostWorkspaceDir)
|
||||
if raw == "" {
|
||||
return "", false, nil
|
||||
}
|
||||
dir, ok := session.MatchApprovedDir(raw, l.approvedList())
|
||||
if !ok {
|
||||
return "", false, localsandbox.ErrProjectDirRevoked
|
||||
}
|
||||
return dir, true, nil
|
||||
}
|
||||
|
||||
func (l *hostProjectLookupImpl) approvedList() []string {
|
||||
if l == nil || l.approved == nil {
|
||||
return nil
|
||||
}
|
||||
return l.approved()
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
//go:build desktop
|
||||
|
||||
package container
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"academy/internal/localsandbox"
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
func hostProjectLookupTestDB(t *testing.T) *gorm.DB {
|
||||
t.Helper()
|
||||
db, err := gorm.Open(sqlite.Open("file:"+t.Name()+"?mode=memory&cache=shared"), &gorm.Config{})
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, db.Migrator().DropTable(&types.Session{}))
|
||||
require.NoError(t, db.AutoMigrate(&types.Session{}))
|
||||
return db
|
||||
}
|
||||
|
||||
func insertHostSession(t *testing.T, db *gorm.DB, id, dir string) {
|
||||
t.Helper()
|
||||
require.NoError(t, db.Session(&gorm.Session{SkipHooks: true}).Create(&types.Session{
|
||||
ID: id,
|
||||
TenantID: 1,
|
||||
HostWorkspaceDir: dir,
|
||||
}).Error)
|
||||
}
|
||||
|
||||
// A stored directory that is no longer approved must not be honoured: the user
|
||||
// removed it from the list precisely to revoke access.
|
||||
func TestProjectLookupFailsClosedWhenDirectoryRevoked(t *testing.T) {
|
||||
db := hostProjectLookupTestDB(t)
|
||||
insertHostSession(t, db, "sess-1", "/Users/dev/Old Project")
|
||||
|
||||
lookup := newHostProjectLookup(db, func() []string {
|
||||
return []string{"/Users/dev/My Project"}
|
||||
})
|
||||
dir, ok, err := lookup.ProjectDirForSession(context.Background(), "sess-1")
|
||||
require.ErrorIs(t, err, localsandbox.ErrProjectDirRevoked)
|
||||
require.False(t, ok)
|
||||
require.Empty(t, dir)
|
||||
}
|
||||
|
||||
func TestProjectLookupReturnsStoredDirectoryWhenStillApproved(t *testing.T) {
|
||||
db := hostProjectLookupTestDB(t)
|
||||
insertHostSession(t, db, "sess-1", "/Users/dev/My Project")
|
||||
|
||||
lookup := newHostProjectLookup(db, func() []string {
|
||||
return []string{"/Users/dev/My Project"}
|
||||
})
|
||||
dir, ok, err := lookup.ProjectDirForSession(context.Background(), "sess-1")
|
||||
require.NoError(t, err)
|
||||
require.True(t, ok)
|
||||
require.Equal(t, "/Users/dev/My Project", dir)
|
||||
}
|
||||
|
||||
func TestProjectLookupEmptyHostWorkspaceDirIsUnbound(t *testing.T) {
|
||||
db := hostProjectLookupTestDB(t)
|
||||
insertHostSession(t, db, "sess-1", "")
|
||||
|
||||
lookup := newHostProjectLookup(db, func() []string {
|
||||
return []string{"/Users/dev/My Project"}
|
||||
})
|
||||
dir, ok, err := lookup.ProjectDirForSession(context.Background(), "sess-1")
|
||||
require.NoError(t, err)
|
||||
require.False(t, ok)
|
||||
require.Empty(t, dir)
|
||||
}
|
||||
|
||||
func TestProjectLookupReturnsFalseForUnknownSession(t *testing.T) {
|
||||
db := hostProjectLookupTestDB(t)
|
||||
lookup := newHostProjectLookup(db, func() []string {
|
||||
return []string{"/Users/dev/My Project"}
|
||||
})
|
||||
dir, ok, err := lookup.ProjectDirForSession(context.Background(), "missing")
|
||||
require.NoError(t, err)
|
||||
require.False(t, ok)
|
||||
require.Empty(t, dir)
|
||||
}
|
||||
|
||||
func TestProjectLookupPropagatesDatabaseErrors(t *testing.T) {
|
||||
db := hostProjectLookupTestDB(t)
|
||||
projectDir := t.TempDir()
|
||||
insertHostSession(t, db, "sess-1", projectDir)
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
lookup := newHostProjectLookup(db, func() []string {
|
||||
return []string{projectDir}
|
||||
})
|
||||
dir, ok, err := lookup.ProjectDirForSession(ctx, "sess-1")
|
||||
require.ErrorIs(t, err, context.Canceled)
|
||||
require.False(t, ok)
|
||||
require.Empty(t, dir)
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
//go:build !desktop
|
||||
|
||||
package container
|
||||
|
||||
import (
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"go.uber.org/dig"
|
||||
|
||||
"academy/internal/application/service"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func moduleRoot(t *testing.T) string {
|
||||
t.Helper()
|
||||
dir, err := os.Getwd()
|
||||
require.NoError(t, err)
|
||||
for {
|
||||
if _, err := os.Stat(filepath.Join(dir, "go.mod")); err == nil {
|
||||
return dir
|
||||
}
|
||||
parent := filepath.Dir(dir)
|
||||
if parent == dir {
|
||||
t.Fatal("go.mod not found")
|
||||
}
|
||||
dir = parent
|
||||
}
|
||||
}
|
||||
|
||||
// The host OS sandbox is a desktop-only compile. cmd/server (standard and
|
||||
// make build-lite) must not even link the package.
|
||||
func TestCmdServerDoesNotDependOnLocalSandbox(t *testing.T) {
|
||||
cmd := exec.Command("go", "list", "-deps", "academy/cmd/server")
|
||||
cmd.Dir = moduleRoot(t)
|
||||
out, err := cmd.CombinedOutput()
|
||||
require.NoError(t, err, string(out))
|
||||
require.NotContains(t, string(out), "internal/localsandbox",
|
||||
"localsandbox must stay behind the desktop build tag")
|
||||
}
|
||||
|
||||
func TestStubHostWiringRegistersWithoutLocalSandbox(t *testing.T) {
|
||||
c := dig.New()
|
||||
require.NoError(t, c.Provide(func() *gorm.DB { return nil }))
|
||||
require.NoError(t, c.Provide(provideHostApprovalModeLoader))
|
||||
require.NoError(t, c.Provide(provideHostProjectDirsLoader))
|
||||
require.NoError(t, c.Provide(hostProjectLookup))
|
||||
require.NoError(t, c.Provide(hostModeLookup))
|
||||
require.NoError(t, c.Provide(provideHostSandboxManager))
|
||||
require.NoError(t, c.Invoke(func(host service.HostSandboxManager) {
|
||||
require.Nil(t, host.Manager)
|
||||
}))
|
||||
}
|
||||
|
||||
func TestContainerPackageImportListOmitsLocalSandbox(t *testing.T) {
|
||||
cmd := exec.Command(
|
||||
"go", "list", "-f", "{{join .Imports \"\\n\"}}",
|
||||
"academy/internal/container",
|
||||
)
|
||||
cmd.Dir = moduleRoot(t)
|
||||
out, err := cmd.CombinedOutput()
|
||||
require.NoError(t, err, string(out))
|
||||
for _, line := range strings.Split(string(out), "\n") {
|
||||
require.NotContains(t, line, "internal/localsandbox")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
package container
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"academy/internal/application/service"
|
||||
"academy/internal/logger"
|
||||
"academy/internal/types"
|
||||
"academy/internal/types/interfaces"
|
||||
"github.com/hibiken/asynq"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// pendingWikiScope is the minimum routing information needed to recreate an
|
||||
// ephemeral wiki trigger from the durable task_pending_ops queue.
|
||||
type pendingWikiScope struct {
|
||||
TenantID uint64 `gorm:"column:tenant_id"`
|
||||
TaskType string `gorm:"column:task_type"`
|
||||
ScopeID string `gorm:"column:scope_id"`
|
||||
}
|
||||
|
||||
// recoverPendingWikiTasks recreates one trigger per pending wiki queue lane.
|
||||
//
|
||||
// task_pending_ops is deliberately durable, but the trigger that wakes its
|
||||
// consumer is not durable in Lite mode (SyncTaskExecutor is process-local) and
|
||||
// may also be absent after an interrupted Redis enqueue. Running this after all
|
||||
// handlers are registered closes that gap. Duplicate triggers are harmless:
|
||||
// ingest claims/peeks disjoint rows and finalize coalesces its pending lane.
|
||||
func recoverPendingWikiTasks(db *gorm.DB, task interfaces.TaskEnqueuer) {
|
||||
if db == nil || task == nil {
|
||||
return
|
||||
}
|
||||
ctx := context.Background()
|
||||
// The outer parentheses matter: the cleanup below negates this whole
|
||||
// predicate with NOT, and `NOT EXISTS(...) AND EXISTS(...)` would parse
|
||||
// as `(NOT EXISTS(...)) AND EXISTS(...)` — silently matching nothing.
|
||||
const activeKnowledgeBase = `(EXISTS (
|
||||
SELECT 1 FROM knowledge_bases kb
|
||||
WHERE kb.id = task_pending_ops.scope_id
|
||||
AND kb.tenant_id = task_pending_ops.tenant_id
|
||||
AND kb.deleted_at IS NULL
|
||||
) AND EXISTS (
|
||||
SELECT 1 FROM tenants t
|
||||
WHERE t.id = task_pending_ops.tenant_id
|
||||
AND t.deleted_at IS NULL
|
||||
))`
|
||||
wikiTaskTypes := []string{types.TypeWikiIngest, types.TypeWikiFinalize}
|
||||
|
||||
// Durable rows for a deleted/missing KB — or a soft-deleted tenant —
|
||||
// must not recreate ephemeral triggers at startup. Fail closed if this
|
||||
// cleanup cannot be verified.
|
||||
cleanup := db.WithContext(ctx).
|
||||
Where("scope = ? AND task_type IN ?", types.TaskScopeKnowledgeBase, wikiTaskTypes).
|
||||
Where("NOT " + activeKnowledgeBase).
|
||||
Delete(&types.TaskPendingOp{})
|
||||
if cleanup.Error != nil {
|
||||
logger.Warnf(ctx, "[WikiRecovery] failed to clear deleted KB queues: %v", cleanup.Error)
|
||||
return
|
||||
}
|
||||
if cleanup.RowsAffected > 0 {
|
||||
logger.Infof(ctx,
|
||||
"[WikiRecovery] removed %d pending row(s) for deleted knowledge bases or tenants",
|
||||
cleanup.RowsAffected)
|
||||
}
|
||||
|
||||
var scopes []pendingWikiScope
|
||||
if err := db.WithContext(ctx).
|
||||
Model(&types.TaskPendingOp{}).
|
||||
Distinct("tenant_id", "task_type", "scope_id").
|
||||
Where("scope = ? AND task_type IN ?", types.TaskScopeKnowledgeBase, wikiTaskTypes).
|
||||
Where(activeKnowledgeBase).
|
||||
Find(&scopes).Error; err != nil {
|
||||
logger.Warnf(ctx, "[WikiRecovery] failed to list pending queues: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
recovered := 0
|
||||
for _, scope := range scopes {
|
||||
if scope.ScopeID == "" {
|
||||
continue
|
||||
}
|
||||
// The batch plans its taxonomy in the trigger's language; take it
|
||||
// from the queued ops rather than defaulting to the server's.
|
||||
payload, err := json.Marshal(service.WikiIngestPayload{
|
||||
TenantID: scope.TenantID,
|
||||
KnowledgeBaseID: scope.ScopeID,
|
||||
Language: service.WikiPendingLanguage(ctx, db, scope.TenantID, scope.ScopeID),
|
||||
})
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "[WikiRecovery] marshal trigger for KB %s failed: %v", scope.ScopeID, err)
|
||||
continue
|
||||
}
|
||||
opts := []asynq.Option{
|
||||
asynq.Queue(types.QueueWiki),
|
||||
asynq.MaxRetry(10), // keep aligned with the wiki ingest retry policy
|
||||
asynq.Timeout(60 * time.Minute),
|
||||
}
|
||||
if scope.TaskType == types.TypeWikiFinalize {
|
||||
opts[2] = asynq.Timeout(30 * time.Minute)
|
||||
// Match scheduleFinalize so simultaneous replica startups collapse
|
||||
// into the same per-KB finalize trigger.
|
||||
opts = append(opts, asynq.TaskID("wiki-finalize-"+scope.ScopeID))
|
||||
}
|
||||
trigger := asynq.NewTask(scope.TaskType, payload, opts...)
|
||||
if _, err := task.Enqueue(trigger); err != nil {
|
||||
if errors.Is(err, asynq.ErrTaskIDConflict) || errors.Is(err, asynq.ErrDuplicateTask) {
|
||||
recovered++
|
||||
continue
|
||||
}
|
||||
logger.Warnf(ctx, "[WikiRecovery] enqueue %s trigger for KB %s failed: %v",
|
||||
scope.TaskType, scope.ScopeID, err)
|
||||
continue
|
||||
}
|
||||
recovered++
|
||||
}
|
||||
if recovered > 0 {
|
||||
logger.Infof(ctx, "[WikiRecovery] recreated %d trigger(s) from durable pending queues", recovered)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
package container
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"academy/internal/application/repository"
|
||||
"academy/internal/logger"
|
||||
"academy/internal/types"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
const resetPendingStaleWindow = 30 * time.Minute
|
||||
|
||||
const restartInterruptedMessage = "Task interrupted due to application restart"
|
||||
|
||||
// resetPendingTasks resets the state of any knowledge items or sync logs stuck in processing
|
||||
// due to an unexpected application restart.
|
||||
//
|
||||
// In Lite mode (no REDIS_ADDR) normal queued tasks live in process memory, so
|
||||
// a "processing" row at startup is orphaned unless it has a durable wiki op
|
||||
// that can be re-triggered.
|
||||
//
|
||||
// Distributed mode is intentionally different: Asynq persists queued/retry
|
||||
// tasks, and another replica may still be executing the same knowledge. A
|
||||
// startup hook cannot safely distinguish an orphan from a backlogged task that
|
||||
// has not opened a span yet. HousekeepingService owns that decision because it
|
||||
// checks BOTH recent span activity and the real Asynq queue. Consequently this
|
||||
// hook never resets knowledge/summary rows in distributed mode; it only keeps
|
||||
// the separate sync-log cleanup below.
|
||||
func resetPendingTasks(db *gorm.DB) {
|
||||
distributed := os.Getenv("REDIS_ADDR") != ""
|
||||
ctx := context.Background()
|
||||
spanRepo := repository.NewKnowledgeSpanRepository(db)
|
||||
|
||||
var staleCutoff time.Time
|
||||
if distributed {
|
||||
staleCutoff = time.Now().Add(-resetPendingStaleWindow)
|
||||
}
|
||||
|
||||
// Resolve Lite-mode orphaned knowledge rows first. A finalizing row whose
|
||||
// ONLY remaining slot is backed by a durable wiki op is excluded and resumed
|
||||
// by recoverPendingWikiTasks after handlers are registered. Rows with other
|
||||
// outstanding in-memory subtasks still fail: the wiki op cannot recover them.
|
||||
var stuckKnowledge []types.Knowledge
|
||||
if !distributed {
|
||||
if err := stuckKnowledgeParseQuery(db).
|
||||
Select("id").Find(&stuckKnowledge).Error; err != nil {
|
||||
logger.Warnf(ctx, "resetPendingTasks: list stuck knowledge failed: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// 1. Reset knowledge parsing tasks (including finalizing rows whose
|
||||
// enrichment subtasks were lost with the process).
|
||||
// Update by the resolved ids rather than reusing the GORM chain after
|
||||
// Find() (which makes PostgreSQL emit an invalid UPDATE ... FROM self).
|
||||
stuckIDs := knowledgeIDs(stuckKnowledge)
|
||||
var resetErr error
|
||||
var resetCount int64
|
||||
if len(stuckIDs) > 0 {
|
||||
// Rebuild the query instead of reusing the chain after Find(); reusing it
|
||||
// makes PostgreSQL emit an invalid UPDATE ... FROM self statement.
|
||||
result := stuckKnowledgeParseQuery(db).
|
||||
Where("id IN ?", stuckIDs).
|
||||
Updates(map[string]interface{}{
|
||||
"parse_status": types.ParseStatusFailed,
|
||||
"error_message": restartInterruptedMessage,
|
||||
"pending_subtasks_count": 0,
|
||||
})
|
||||
resetErr = result.Error
|
||||
resetCount = result.RowsAffected
|
||||
}
|
||||
if resetErr != nil {
|
||||
logger.Warnf(context.Background(), "Failed to reset pending knowledge tasks: %v", resetErr)
|
||||
} else if resetCount > 0 {
|
||||
logger.Infof(context.Background(),
|
||||
"Reset %d stuck knowledge parsing tasks to failed state (distributed=%v)",
|
||||
resetCount, distributed)
|
||||
|
||||
// Cancel orphaned trace spans only after the owning knowledge rows are
|
||||
// terminal. This prevents the UI from showing duplicate running
|
||||
// postprocess.* subspans when a later manual retry opens fresh spans.
|
||||
// Re-read the successfully reset ids so a row whose status changed in
|
||||
// the small SELECT/UPDATE gap is not accidentally cancelled.
|
||||
var resetKnowledge []types.Knowledge
|
||||
if err := db.Select("id").
|
||||
Where("id IN ? AND parse_status = ? AND error_message = ?",
|
||||
stuckIDs, types.ParseStatusFailed, restartInterruptedMessage).
|
||||
Find(&resetKnowledge).Error; err != nil {
|
||||
logger.Warnf(ctx, "resetPendingTasks: list reset knowledge failed: %v", err)
|
||||
}
|
||||
for _, k := range resetKnowledge {
|
||||
attempt, err := spanRepo.LatestAttempt(ctx, k.ID)
|
||||
if err != nil || attempt <= 0 {
|
||||
continue
|
||||
}
|
||||
if n, err := spanRepo.CancelAllOpenSpans(ctx, k.ID, attempt,
|
||||
"SERVER_RESTART", restartInterruptedMessage); err != nil {
|
||||
logger.Warnf(ctx, "resetPendingTasks: cancel spans for %s failed: %v", k.ID, err)
|
||||
} else if n > 0 {
|
||||
logger.Infof(ctx, "resetPendingTasks: cancelled %d open span(s) for knowledge %s attempt %d",
|
||||
n, k.ID, attempt)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Lite summary tasks are process-local too. Distributed summary tasks
|
||||
// stay in Asynq and must not be failed merely because this replica started.
|
||||
if !distributed {
|
||||
resultSummary := stuckKnowledgeSummaryQuery(db).Updates(map[string]interface{}{
|
||||
"summary_status": types.SummaryStatusFailed,
|
||||
})
|
||||
if resultSummary.Error != nil {
|
||||
logger.Warnf(context.Background(), "Failed to reset pending summary tasks: %v", resultSummary.Error)
|
||||
} else if resultSummary.RowsAffected > 0 {
|
||||
logger.Infof(context.Background(),
|
||||
"Reset %d stuck summary generation tasks to failed state (distributed=false)",
|
||||
resultSummary.RowsAffected)
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Reset data source sync tasks
|
||||
now := time.Now()
|
||||
resultSync := stuckSyncLogQuery(db, distributed, staleCutoff).Updates(map[string]interface{}{
|
||||
"status": types.SyncLogStatusFailed,
|
||||
"error_message": "Sync interrupted due to application restart",
|
||||
"finished_at": &now,
|
||||
})
|
||||
if resultSync.Error != nil {
|
||||
logger.Warnf(context.Background(), "Failed to reset pending data source sync tasks: %v", resultSync.Error)
|
||||
} else if resultSync.RowsAffected > 0 {
|
||||
logger.Infof(context.Background(),
|
||||
"Reset %d stuck data source sync tasks to failed state (distributed=%v)",
|
||||
resultSync.RowsAffected, distributed)
|
||||
}
|
||||
}
|
||||
|
||||
func stuckKnowledgeParseQuery(db *gorm.DB) *gorm.DB {
|
||||
q := db.Model(&types.Knowledge{}).
|
||||
Where("parse_status IN ?", resettableParseStatuses()).
|
||||
// Wiki ingest ops are persisted independently from the task trigger.
|
||||
// When wiki owns the only outstanding slot, keeping this finalizing row
|
||||
// alive lets startup recreate the trigger and finish cleanly. A count
|
||||
// above one means at least one non-wiki in-memory subtask was also lost.
|
||||
Where(`NOT (parse_status = ? AND pending_subtasks_count = 1 AND EXISTS (
|
||||
SELECT 1 FROM task_pending_ops
|
||||
WHERE task_pending_ops.task_type = ?
|
||||
AND task_pending_ops.scope = ?
|
||||
AND task_pending_ops.dedup_key = knowledges.id
|
||||
AND task_pending_ops.op = ?
|
||||
))`, types.ParseStatusFinalizing, types.TypeWikiIngest,
|
||||
types.TaskScopeKnowledgeBase, "ingest")
|
||||
return q
|
||||
}
|
||||
|
||||
func stuckKnowledgeSummaryQuery(db *gorm.DB) *gorm.DB {
|
||||
return db.Model(&types.Knowledge{}).
|
||||
Where("summary_status IN ?", []string{types.SummaryStatusPending, types.SummaryStatusProcessing})
|
||||
}
|
||||
|
||||
func stuckSyncLogQuery(db *gorm.DB, distributed bool, staleCutoff time.Time) *gorm.DB {
|
||||
q := db.Model(&types.SyncLog{}).
|
||||
Where("status = ?", types.SyncLogStatusRunning)
|
||||
if distributed {
|
||||
q = q.Where("started_at < ?", staleCutoff)
|
||||
}
|
||||
return q
|
||||
}
|
||||
|
||||
func resettableParseStatuses() []string {
|
||||
return []string{
|
||||
types.ParseStatusPending,
|
||||
types.ParseStatusProcessing,
|
||||
types.ParseStatusFinalizing,
|
||||
types.ParseStatusDeleting,
|
||||
}
|
||||
}
|
||||
|
||||
func knowledgeIDs(rows []types.Knowledge) []string {
|
||||
ids := make([]string, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
if row.ID != "" {
|
||||
ids = append(ids, row.ID)
|
||||
}
|
||||
}
|
||||
return ids
|
||||
}
|
||||
@@ -0,0 +1,379 @@
|
||||
package container
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"academy/internal/application/service"
|
||||
"academy/internal/types"
|
||||
"github.com/hibiken/asynq"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
const resetPendingKnowledgeDDL = `
|
||||
CREATE TABLE IF NOT EXISTS knowledges (
|
||||
profile TEXT,
|
||||
id VARCHAR(64) PRIMARY KEY,
|
||||
parse_status VARCHAR(32) NOT NULL DEFAULT 'pending',
|
||||
summary_status VARCHAR(32) NOT NULL DEFAULT 'none',
|
||||
pending_subtasks_count INTEGER NOT NULL DEFAULT 0,
|
||||
error_message TEXT,
|
||||
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
deleted_at DATETIME
|
||||
);
|
||||
`
|
||||
|
||||
const resetPendingSyncLogDDL = `
|
||||
CREATE TABLE IF NOT EXISTS sync_logs (
|
||||
id VARCHAR(64) PRIMARY KEY,
|
||||
data_source_id VARCHAR(64) NOT NULL DEFAULT '',
|
||||
tenant_id INTEGER NOT NULL DEFAULT 0,
|
||||
status VARCHAR(32) NOT NULL,
|
||||
started_at DATETIME,
|
||||
finished_at DATETIME,
|
||||
error_message TEXT,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
`
|
||||
|
||||
const resetPendingSpansDDL = `
|
||||
CREATE TABLE IF NOT EXISTS knowledge_processing_spans (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
knowledge_id VARCHAR(64) NOT NULL,
|
||||
attempt INTEGER NOT NULL DEFAULT 1,
|
||||
span_id VARCHAR(64) NOT NULL,
|
||||
parent_span_id VARCHAR(64),
|
||||
name VARCHAR(255) NOT NULL,
|
||||
kind VARCHAR(16) NOT NULL,
|
||||
status VARCHAR(16) NOT NULL,
|
||||
error_code VARCHAR(64),
|
||||
error_message TEXT,
|
||||
started_at DATETIME,
|
||||
finished_at DATETIME,
|
||||
duration_ms INTEGER,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
UNIQUE (knowledge_id, attempt, span_id)
|
||||
);
|
||||
`
|
||||
|
||||
const resetPendingOpsDDL = `
|
||||
CREATE TABLE IF NOT EXISTS task_pending_ops (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
tenant_id INTEGER NOT NULL DEFAULT 0,
|
||||
task_type VARCHAR(64) NOT NULL,
|
||||
scope VARCHAR(32) NOT NULL,
|
||||
scope_id VARCHAR(64) NOT NULL,
|
||||
op VARCHAR(32) NOT NULL,
|
||||
dedup_key VARCHAR(128) NOT NULL DEFAULT '',
|
||||
payload TEXT NOT NULL DEFAULT '{}',
|
||||
fail_count INTEGER NOT NULL DEFAULT 0,
|
||||
enqueued_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
claimed_at DATETIME
|
||||
);
|
||||
`
|
||||
|
||||
const resetPendingKnowledgeBasesDDL = `
|
||||
CREATE TABLE IF NOT EXISTS knowledge_bases (
|
||||
profile_config TEXT,
|
||||
generated_profile TEXT,
|
||||
id VARCHAR(64) PRIMARY KEY,
|
||||
tenant_id INTEGER NOT NULL DEFAULT 0,
|
||||
deleted_at DATETIME
|
||||
);
|
||||
`
|
||||
|
||||
var resetPendingTenantsDDL = `
|
||||
CREATE TABLE IF NOT EXISTS tenants (
|
||||
id INTEGER PRIMARY KEY,
|
||||
deleted_at DATETIME
|
||||
);
|
||||
`
|
||||
|
||||
func setupResetPendingDB(t *testing.T) *gorm.DB {
|
||||
t.Helper()
|
||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, db.Exec(resetPendingKnowledgeDDL).Error)
|
||||
require.NoError(t, db.Exec(resetPendingSyncLogDDL).Error)
|
||||
require.NoError(t, db.Exec(resetPendingSpansDDL).Error)
|
||||
require.NoError(t, db.Exec(resetPendingOpsDDL).Error)
|
||||
require.NoError(t, db.Exec(resetPendingKnowledgeBasesDDL).Error)
|
||||
require.NoError(t, db.Exec(resetPendingTenantsDDL).Error)
|
||||
// Tenants 7 and 8 are alive; tenant 9 is soft-deleted — its KB-scoped
|
||||
// pending rows must be purged by recovery even though the KB row is
|
||||
// still present (#3593).
|
||||
require.NoError(t, db.Exec(
|
||||
"INSERT INTO tenants (id, deleted_at) VALUES (?, NULL), (?, NULL), (?, ?)",
|
||||
7, 8, 9, time.Now(),
|
||||
).Error)
|
||||
return db
|
||||
}
|
||||
|
||||
func TestResetPendingTasks_KnowledgeFindThenUpdate(t *testing.T) {
|
||||
db := setupResetPendingDB(t)
|
||||
stale := time.Now().Add(-2 * time.Hour)
|
||||
require.NoError(t, db.Exec(
|
||||
`INSERT INTO knowledges (id, parse_status, updated_at) VALUES (?, ?, ?)`,
|
||||
"k-stuck", types.ParseStatusProcessing, stale,
|
||||
).Error)
|
||||
|
||||
os.Unsetenv("REDIS_ADDR")
|
||||
resetPendingTasks(db)
|
||||
|
||||
var status, errMsg string
|
||||
require.NoError(t, db.Raw(
|
||||
`SELECT parse_status, error_message FROM knowledges WHERE id = ?`, "k-stuck",
|
||||
).Row().Scan(&status, &errMsg))
|
||||
assert.Equal(t, types.ParseStatusFailed, status)
|
||||
assert.Contains(t, errMsg, "application restart")
|
||||
}
|
||||
|
||||
func TestResetPendingTasks_KnowledgeFreshInDistributedMode(t *testing.T) {
|
||||
db := setupResetPendingDB(t)
|
||||
fresh := time.Now().Add(-5 * time.Minute)
|
||||
require.NoError(t, db.Exec(
|
||||
`INSERT INTO knowledges (id, parse_status, updated_at) VALUES (?, ?, ?)`,
|
||||
"k-fresh", types.ParseStatusProcessing, fresh,
|
||||
).Error)
|
||||
|
||||
t.Setenv("REDIS_ADDR", "redis:6379")
|
||||
resetPendingTasks(db)
|
||||
|
||||
var status string
|
||||
require.NoError(t, db.Raw(
|
||||
`SELECT parse_status FROM knowledges WHERE id = ?`, "k-fresh",
|
||||
).Row().Scan(&status))
|
||||
assert.Equal(t, types.ParseStatusProcessing, status)
|
||||
}
|
||||
|
||||
func TestResetPendingTasks_DistributedModePreservesEveryStage(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
parseStatus string
|
||||
}{
|
||||
{"pending", types.ParseStatusPending},
|
||||
{"docreader_chunking_embedding", types.ParseStatusProcessing},
|
||||
{"multimodal", types.ParseStatusProcessing},
|
||||
{"postprocess", types.ParseStatusFinalizing},
|
||||
{"wiki", types.ParseStatusFinalizing},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
db := setupResetPendingDB(t)
|
||||
stale := time.Now().Add(-2 * time.Hour)
|
||||
require.NoError(t, db.Exec(
|
||||
`INSERT INTO knowledges (id, parse_status, updated_at) VALUES (?, ?, ?)`,
|
||||
"k-active-span", tc.parseStatus, stale,
|
||||
).Error)
|
||||
|
||||
t.Setenv("REDIS_ADDR", "redis:6379")
|
||||
resetPendingTasks(db)
|
||||
|
||||
var status string
|
||||
require.NoError(t, db.Raw(
|
||||
`SELECT parse_status FROM knowledges WHERE id = ?`, "k-active-span",
|
||||
).Row().Scan(&status))
|
||||
assert.Equal(t, tc.parseStatus, status,
|
||||
"distributed tasks belong to Asynq/housekeeping, not startup reset")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestResetPendingTasks_DistributedSummaryTaskSurvivesRestart(t *testing.T) {
|
||||
db := setupResetPendingDB(t)
|
||||
stale := time.Now().Add(-2 * time.Hour)
|
||||
require.NoError(t, db.Exec(
|
||||
`INSERT INTO knowledges (id, parse_status, summary_status, updated_at)
|
||||
VALUES (?, ?, ?, ?)`,
|
||||
"k-summary", types.ParseStatusCompleted, types.SummaryStatusProcessing, stale,
|
||||
).Error)
|
||||
|
||||
t.Setenv("REDIS_ADDR", "redis:6379")
|
||||
resetPendingTasks(db)
|
||||
|
||||
var status string
|
||||
require.NoError(t, db.Raw(
|
||||
`SELECT summary_status FROM knowledges WHERE id = ?`, "k-summary",
|
||||
).Row().Scan(&status))
|
||||
assert.Equal(t, types.SummaryStatusProcessing, status)
|
||||
}
|
||||
|
||||
func TestResetPendingTasks_DurableWikiOpSurvivesLiteRestart(t *testing.T) {
|
||||
db := setupResetPendingDB(t)
|
||||
require.NoError(t, db.Exec(
|
||||
`INSERT INTO knowledges (id, parse_status, pending_subtasks_count)
|
||||
VALUES (?, ?, 1)`, "k-wiki", types.ParseStatusFinalizing,
|
||||
).Error)
|
||||
require.NoError(t, db.Exec(
|
||||
`INSERT INTO task_pending_ops
|
||||
(tenant_id, task_type, scope, scope_id, op, dedup_key, payload)
|
||||
VALUES (7, ?, ?, 'kb-wiki', 'ingest', 'k-wiki', '{}')`,
|
||||
types.TypeWikiIngest, types.TaskScopeKnowledgeBase,
|
||||
).Error)
|
||||
|
||||
os.Unsetenv("REDIS_ADDR")
|
||||
resetPendingTasks(db)
|
||||
|
||||
var status string
|
||||
var pending int
|
||||
require.NoError(t, db.Raw(
|
||||
`SELECT parse_status, pending_subtasks_count FROM knowledges WHERE id = ?`, "k-wiki",
|
||||
).Row().Scan(&status, &pending))
|
||||
assert.Equal(t, types.ParseStatusFinalizing, status)
|
||||
assert.Equal(t, 1, pending, "resumed wiki worker still owns its finalizing slot")
|
||||
}
|
||||
|
||||
func TestResetPendingTasks_LiteWikiDoesNotHideOtherLostSubtasks(t *testing.T) {
|
||||
db := setupResetPendingDB(t)
|
||||
require.NoError(t, db.Exec(
|
||||
`INSERT INTO knowledges (id, parse_status, pending_subtasks_count)
|
||||
VALUES (?, ?, 2)`, "k-wiki-plus-summary", types.ParseStatusFinalizing,
|
||||
).Error)
|
||||
require.NoError(t, db.Exec(
|
||||
`INSERT INTO task_pending_ops
|
||||
(tenant_id, task_type, scope, scope_id, op, dedup_key, payload)
|
||||
VALUES (7, ?, ?, 'kb-wiki', 'ingest', 'k-wiki-plus-summary', '{}')`,
|
||||
types.TypeWikiIngest, types.TaskScopeKnowledgeBase,
|
||||
).Error)
|
||||
|
||||
os.Unsetenv("REDIS_ADDR")
|
||||
resetPendingTasks(db)
|
||||
|
||||
var status string
|
||||
require.NoError(t, db.Raw(
|
||||
`SELECT parse_status FROM knowledges WHERE id = ?`, "k-wiki-plus-summary",
|
||||
).Row().Scan(&status))
|
||||
assert.Equal(t, types.ParseStatusFailed, status,
|
||||
"a durable wiki op cannot recover another lost in-memory subtask")
|
||||
}
|
||||
|
||||
func TestResetPendingTasks_SyncLogStaleRunning(t *testing.T) {
|
||||
db := setupResetPendingDB(t)
|
||||
stale := time.Now().Add(-2 * time.Hour)
|
||||
require.NoError(t, db.Exec(
|
||||
`INSERT INTO sync_logs (id, status, started_at) VALUES (?, ?, ?)`,
|
||||
"sync-1", types.SyncLogStatusRunning, stale,
|
||||
).Error)
|
||||
|
||||
t.Setenv("REDIS_ADDR", "redis:6379")
|
||||
resetPendingTasks(db)
|
||||
|
||||
var status string
|
||||
var finishedAt *time.Time
|
||||
require.NoError(t, db.Raw(
|
||||
`SELECT status, finished_at FROM sync_logs WHERE id = ?`, "sync-1",
|
||||
).Row().Scan(&status, &finishedAt))
|
||||
assert.Equal(t, types.SyncLogStatusFailed, status)
|
||||
require.NotNil(t, finishedAt)
|
||||
}
|
||||
|
||||
func TestResetPendingTasks_SyncLogLiteMode(t *testing.T) {
|
||||
db := setupResetPendingDB(t)
|
||||
os.Unsetenv("REDIS_ADDR")
|
||||
require.NoError(t, db.Exec(
|
||||
`INSERT INTO sync_logs (id, status, started_at) VALUES (?, ?, ?)`,
|
||||
"sync-lite", types.SyncLogStatusRunning, time.Now(),
|
||||
).Error)
|
||||
|
||||
resetPendingTasks(db)
|
||||
|
||||
var status string
|
||||
require.NoError(t, db.Raw(
|
||||
`SELECT status FROM sync_logs WHERE id = ?`, "sync-lite",
|
||||
).Row().Scan(&status))
|
||||
assert.Equal(t, types.SyncLogStatusFailed, status)
|
||||
}
|
||||
|
||||
func TestStuckKnowledgeParseQuery_ReuseAfterFindDoesNotBreakUpdate(t *testing.T) {
|
||||
db := setupResetPendingDB(t)
|
||||
stale := time.Now().Add(-2 * time.Hour)
|
||||
require.NoError(t, db.Exec(
|
||||
`INSERT INTO knowledges (id, parse_status, updated_at) VALUES (?, ?, ?)`,
|
||||
"k-reuse", types.ParseStatusProcessing, stale,
|
||||
).Error)
|
||||
|
||||
var rows []types.Knowledge
|
||||
q := stuckKnowledgeParseQuery(db)
|
||||
require.NoError(t, q.Select("id").Find(&rows).Error)
|
||||
require.Len(t, rows, 1)
|
||||
|
||||
result := stuckKnowledgeParseQuery(db).Updates(map[string]interface{}{
|
||||
"parse_status": types.ParseStatusFailed,
|
||||
})
|
||||
require.NoError(t, result.Error)
|
||||
assert.Equal(t, int64(1), result.RowsAffected)
|
||||
}
|
||||
|
||||
type recordingTaskEnqueuer struct {
|
||||
tasks []*asynq.Task
|
||||
}
|
||||
|
||||
func (r *recordingTaskEnqueuer) Enqueue(task *asynq.Task, _ ...asynq.Option) (*asynq.TaskInfo, error) {
|
||||
r.tasks = append(r.tasks, task)
|
||||
return &asynq.TaskInfo{ID: "test", Type: task.Type()}, nil
|
||||
}
|
||||
|
||||
func TestRecoverPendingWikiTasks_RecreatesOneTriggerPerLaneAndKB(t *testing.T) {
|
||||
db := setupResetPendingDB(t)
|
||||
require.NoError(t, db.Exec(
|
||||
`INSERT INTO knowledge_bases (id, tenant_id, deleted_at)
|
||||
VALUES (?, ?, NULL), (?, ?, NULL), (?, ?, ?), (?, ?, NULL)`,
|
||||
"kb-a", 7, "kb-b", 8, "kb-deleted", 9, time.Now(), "kb-t9", 9,
|
||||
).Error)
|
||||
rows := []struct {
|
||||
tenantID uint64
|
||||
taskType string
|
||||
kbID string
|
||||
dedup string
|
||||
}{
|
||||
{7, types.TypeWikiIngest, "kb-a", "k-1"},
|
||||
{7, types.TypeWikiIngest, "kb-a", "k-2"}, // same lane: one trigger
|
||||
{7, types.TypeWikiFinalize, "kb-a", "slug-a"},
|
||||
{8, types.TypeWikiIngest, "kb-b", "k-3"},
|
||||
{9, types.TypeWikiIngest, "kb-deleted", "k-deleted"},
|
||||
{9, types.TypeWikiIngest, "kb-t9", "k-t9"}, // live KB of a deleted tenant
|
||||
{10, types.TypeWikiFinalize, "kb-missing", "k-missing"},
|
||||
}
|
||||
for _, row := range rows {
|
||||
require.NoError(t, db.Exec(
|
||||
`INSERT INTO task_pending_ops
|
||||
(tenant_id, task_type, scope, scope_id, op, dedup_key, payload)
|
||||
VALUES (?, ?, ?, ?, 'ingest', ?, '{}')`,
|
||||
row.tenantID, row.taskType, types.TaskScopeKnowledgeBase, row.kbID, row.dedup,
|
||||
).Error)
|
||||
}
|
||||
|
||||
recorder := &recordingTaskEnqueuer{}
|
||||
recoverPendingWikiTasks(db, recorder)
|
||||
require.Len(t, recorder.tasks, 3)
|
||||
|
||||
seen := map[string]service.WikiIngestPayload{}
|
||||
for _, task := range recorder.tasks {
|
||||
var payload service.WikiIngestPayload
|
||||
require.NoError(t, json.Unmarshal(task.Payload(), &payload))
|
||||
seen[task.Type()+":"+payload.KnowledgeBaseID] = payload
|
||||
}
|
||||
assert.Equal(t, uint64(7), seen[types.TypeWikiIngest+":kb-a"].TenantID)
|
||||
assert.Equal(t, uint64(7), seen[types.TypeWikiFinalize+":kb-a"].TenantID)
|
||||
assert.Equal(t, uint64(8), seen[types.TypeWikiIngest+":kb-b"].TenantID)
|
||||
|
||||
var orphaned int64
|
||||
require.NoError(t, db.Model(&types.TaskPendingOp{}).
|
||||
Where("scope_id IN ?", []string{"kb-deleted", "kb-missing", "kb-t9"}).
|
||||
Count(&orphaned).Error)
|
||||
assert.Zero(t, orphaned)
|
||||
|
||||
// The live KB of a soft-deleted tenant must be purged too: the KB row
|
||||
// survives the tenant deletion, so the KB-only predicate would keep
|
||||
// re-arming its triggers at every startup (#3593).
|
||||
var remaining int64
|
||||
require.NoError(t, db.Model(&types.TaskPendingOp{}).Count(&remaining).Error)
|
||||
assert.Equal(t, int64(4), remaining)
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package container
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"go.uber.org/dig"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"academy/internal/application/repository"
|
||||
"academy/internal/application/service/retriever"
|
||||
"academy/internal/config"
|
||||
"academy/internal/types/interfaces"
|
||||
)
|
||||
|
||||
// TestRetrieveEngineRegistryWiring checks that the container can still build
|
||||
// the retrieval engine registry, and that what it builds can rebuild a missing
|
||||
// store engine.
|
||||
//
|
||||
// The registry depends on the vector store repository and the engine factory,
|
||||
// and the engine factory must not in turn depend on the registry. A cycle or a
|
||||
// missing provider surfaces only when the process starts, so it is worth
|
||||
// pinning here rather than discovering it at deploy time. The nil check at the
|
||||
// end is the part that matters: a registry resolved without those two
|
||||
// dependencies still satisfies the interface and still serves lookups, so it
|
||||
// would pass every other test while silently never rebuilding anything.
|
||||
func TestRetrieveEngineRegistryWiring(t *testing.T) {
|
||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
||||
if err != nil {
|
||||
t.Fatalf("open in-mem db: %v", err)
|
||||
}
|
||||
|
||||
c := dig.New()
|
||||
provide := func(constructor interface{}) {
|
||||
t.Helper()
|
||||
if err := c.Provide(constructor); err != nil {
|
||||
t.Fatalf("provide: %v", err)
|
||||
}
|
||||
}
|
||||
provide(func() *gorm.DB { return db })
|
||||
provide(func() *config.Config { return &config.Config{} })
|
||||
provide(func() interfaces.AuditLogService { return &fakeAuditSvc{} })
|
||||
provide(repository.NewVectorStoreRepository)
|
||||
provide(NewEngineFactory)
|
||||
provide(initRetrieveEngineRegistry)
|
||||
|
||||
err = c.Invoke(func(registry interfaces.RetrieveEngineRegistry) {
|
||||
concrete, ok := registry.(*retriever.RetrieveEngineRegistry)
|
||||
if !ok {
|
||||
t.Fatalf("expected *retriever.RetrieveEngineRegistry, got %T", registry)
|
||||
}
|
||||
if !concrete.CanRebuildStores() {
|
||||
t.Error("registry was built without the dependencies it needs to rebuild a store engine")
|
||||
}
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("container could not build the registry: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package container
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"go.uber.org/dig"
|
||||
)
|
||||
|
||||
// Resolve the production dependency graph without opening connections or
|
||||
// starting background workers. Handler tests alone do not catch missing DI types.
|
||||
func TestRouterWiring(t *testing.T) {
|
||||
for _, mode := range []struct {
|
||||
name string
|
||||
redisAddr string
|
||||
}{
|
||||
{name: "lite"},
|
||||
{name: "redis", redisAddr: "localhost:6379"},
|
||||
} {
|
||||
t.Run(mode.name, func(t *testing.T) {
|
||||
t.Setenv("REDIS_ADDR", mode.redisAddr)
|
||||
c := BuildContainer(dig.New(dig.DryRun(true)))
|
||||
if err := c.Invoke(func(*gin.Engine) {}); err != nil {
|
||||
t.Fatalf("resolve router dependencies: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
// Package container - workspace sandbox provider wiring.
|
||||
package container
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"academy/internal/application/service/sandboxalloc"
|
||||
apperrors "academy/internal/errors"
|
||||
"academy/internal/logger"
|
||||
"academy/internal/sandbox"
|
||||
"academy/internal/sandbox/admission"
|
||||
"academy/internal/sandbox/allocation"
|
||||
"academy/internal/types"
|
||||
"academy/internal/types/interfaces"
|
||||
)
|
||||
|
||||
// newSandboxManager is deliberately disabled. Every executable backend now
|
||||
// comes from a named workspace configuration resolved at request time.
|
||||
func newSandboxManager(
|
||||
_ *redis.Client,
|
||||
_ interfaces.SessionRepository,
|
||||
) sandbox.Manager {
|
||||
return sandbox.NewDisabledManager()
|
||||
}
|
||||
|
||||
// sandboxRedisNamespace is the Redis key prefix shared by session bindings
|
||||
// and user-machine digests. An empty env var means the historical default.
|
||||
func sandboxRedisNamespace() string {
|
||||
namespace := strings.TrimSpace(os.Getenv("ACADEMY_REDIS_NAMESPACE"))
|
||||
if namespace == "" {
|
||||
namespace = "academy"
|
||||
}
|
||||
return namespace
|
||||
}
|
||||
|
||||
func selectSessionBindingStore(
|
||||
redisClient *redis.Client,
|
||||
requireRedis bool,
|
||||
) (sandbox.SessionSandboxBindingStore, string, error) {
|
||||
namespace := sandboxRedisNamespace()
|
||||
requested := allocation.UserModeRequestedByEnv()
|
||||
if redisClient != nil {
|
||||
store, err := sandbox.NewRedisSessionSandboxBindingStore(redisClient, namespace)
|
||||
if err != nil {
|
||||
return nil, "", fmt.Errorf("build redis binding store: %w", err)
|
||||
}
|
||||
// User mode needs both the env opt-in and Redis; without Redis the
|
||||
// leases that coordinate one machine across replicas do not exist.
|
||||
allocation.SetUserModeAvailable(requested)
|
||||
if requested {
|
||||
logger.Infof(context.Background(), "[sandbox] user-mode allocation enabled (%s)", allocation.UserModeEnvVar)
|
||||
}
|
||||
return store, "redis", nil
|
||||
}
|
||||
allocation.SetUserModeAvailable(false)
|
||||
if requested {
|
||||
logger.Errorf(context.Background(),
|
||||
"[sandbox] %s is set but Redis is not configured; user-mode allocation stays disabled",
|
||||
allocation.UserModeEnvVar)
|
||||
}
|
||||
_ = requireRedis
|
||||
logger.Warnf(context.Background(),
|
||||
"[sandbox] No Redis configured, using in-memory binding store (single-instance)")
|
||||
return sandbox.NewMemorySessionSandboxBindingStore(), "memory", nil
|
||||
}
|
||||
|
||||
// newSessionBindingStore selects the process-wide session→sandbox binding
|
||||
// store. The tenant sandbox resolver and the background activity registry
|
||||
// share it: the registry's Redis hash must use the binding store's client,
|
||||
// namespace and hash tag so the turn-lease scripts can read it. A nil result
|
||||
// disables per-tenant sandbox configs, as a failed selection always has.
|
||||
func newSessionBindingStore(redisClient *redis.Client) sandbox.SessionSandboxBindingStore {
|
||||
ctx := context.Background()
|
||||
store, storeKind, err := selectSessionBindingStore(redisClient, true)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Per-tenant sandbox config disabled: %v", err)
|
||||
return nil
|
||||
}
|
||||
logger.Infof(ctx, "Session sandbox binding store: %s", storeKind)
|
||||
return store
|
||||
}
|
||||
|
||||
// sessionExistenceLookup is the narrow slice of SessionRepository the
|
||||
// session existence checker actually needs. Declaring it here (rather than
|
||||
// depending on interfaces.SessionRepository) keeps the checker easy to test
|
||||
// and lets the container inject a nil repository in Lite mode without
|
||||
// dragging the whole database contract along.
|
||||
type sessionExistenceLookup interface {
|
||||
GetByID(ctx context.Context, tenantID uint64, id string) (*types.Session, error)
|
||||
}
|
||||
|
||||
// sessionExistenceCheckerFor returns a SessionExistenceChecker backed by the
|
||||
// tenant session repository. When the repository is unavailable (Lite mode
|
||||
// without a database) the returned checker is permissive so single-process
|
||||
// deployments still work; multi-instance production paths always resolve a
|
||||
// real repository because the container refuses to boot without one.
|
||||
func sessionExistenceCheckerFor(
|
||||
lookup sessionExistenceLookup,
|
||||
) sandbox.SessionExistenceChecker {
|
||||
if lookup == nil {
|
||||
return sandbox.PermissiveSessionExistenceChecker{}
|
||||
}
|
||||
return &repositorySessionExistenceChecker{lookup: lookup}
|
||||
}
|
||||
|
||||
// repositorySessionExistenceChecker adapts SessionRepository.GetByID onto the
|
||||
// SessionExistenceChecker contract. gorm.ErrRecordNotFound → false, other
|
||||
// errors propagate so the lifecycle coordinator preserves bindings under
|
||||
// transient database failures.
|
||||
type repositorySessionExistenceChecker struct {
|
||||
lookup sessionExistenceLookup
|
||||
}
|
||||
|
||||
func (c *repositorySessionExistenceChecker) SessionExists(
|
||||
ctx context.Context,
|
||||
key sandbox.SessionSandboxKey,
|
||||
) (bool, error) {
|
||||
if c == nil || c.lookup == nil {
|
||||
return true, nil
|
||||
}
|
||||
session, err := c.lookup.GetByID(ctx, key.TenantID, key.SessionID)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) || errors.Is(err, apperrors.ErrSessionNotFound) {
|
||||
return false, nil
|
||||
}
|
||||
return false, fmt.Errorf("session existence check: %w", err)
|
||||
}
|
||||
return session != nil, nil
|
||||
}
|
||||
|
||||
// buildGlobalSandboxConfig returns the process-wide *sandbox.Config that
|
||||
// per-tenant overrides are merged onto.
|
||||
func buildGlobalSandboxConfig() *sandbox.Config {
|
||||
cfg := sandbox.DefaultConfig()
|
||||
cfg.Type = sandbox.SandboxTypeDisabled
|
||||
return cfg
|
||||
}
|
||||
|
||||
// newTenantSandboxResolver wires the workspace-config resolver. The
|
||||
// process-wide manager is disabled; agents without a selected config stay
|
||||
// disabled as well.
|
||||
func newTenantSandboxResolver(
|
||||
defaultManager sandbox.Manager,
|
||||
loader sandbox.TenantSandboxConfigLoader,
|
||||
store sandbox.SessionSandboxBindingStore,
|
||||
sessionRepo interfaces.SessionRepository,
|
||||
bootstrapper sandbox.SessionBootstrapper,
|
||||
alloc *sandboxalloc.Service,
|
||||
reg admission.Registry,
|
||||
) sandbox.TenantSandboxResolver {
|
||||
ctx := context.Background()
|
||||
|
||||
// Tenants may configure any supported backend regardless of process startup
|
||||
// mode. Remote configs use this binding store for session persistence.
|
||||
if store == nil {
|
||||
logger.Warnf(ctx, "Per-tenant sandbox config disabled: no session binding store")
|
||||
return nil
|
||||
}
|
||||
resolver, err := sandbox.NewTenantSandboxResolver(sandbox.TenantSandboxResolverDeps{
|
||||
GlobalConfig: buildGlobalSandboxConfig(),
|
||||
DefaultManager: defaultManager,
|
||||
Loader: loader,
|
||||
Store: store,
|
||||
Checker: sessionExistenceCheckerFor(sessionRepo),
|
||||
Bootstrapper: bootstrapper,
|
||||
Allocations: alloc,
|
||||
Admission: reg,
|
||||
Namespace: sandboxRedisNamespace(),
|
||||
SharedTransport: sandbox.NewGuardedTransport(),
|
||||
})
|
||||
if err != nil {
|
||||
logger.Warnf(ctx,
|
||||
"Failed to initialize tenant sandbox resolver: %v "+
|
||||
"(per-tenant sandbox config disabled)", err)
|
||||
return nil
|
||||
}
|
||||
logger.Infof(ctx, "Tenant sandbox resolver configured")
|
||||
return resolver
|
||||
}
|
||||
|
||||
// newAdmissionRegistry shares Redis with the binding store; the key prefix
|
||||
// matches the user binding keys so both live under one hash tag.
|
||||
func newAdmissionRegistry(redisClient *redis.Client) admission.Registry {
|
||||
if redisClient == nil {
|
||||
return admission.NewMemory()
|
||||
}
|
||||
return admission.NewRedis(redisClient, "academy:sandbox:user:")
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
//go:build desktop
|
||||
|
||||
package container
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"academy/internal/application/service"
|
||||
"academy/internal/localsandbox"
|
||||
"academy/internal/localsandbox/adapter"
|
||||
"academy/internal/localsandbox/skilltree"
|
||||
"academy/internal/logger"
|
||||
"academy/internal/sandbox"
|
||||
)
|
||||
|
||||
// Host adapters must not version the user's workspace. This compile-time check
|
||||
// keeps WorkspaceCheckpointer from committing a real project if the adapter is
|
||||
// ever injected as the process-wide shell runner.
|
||||
var (
|
||||
_ service.WorkspaceVersioning = (*adapter.Adapter)(nil)
|
||||
_ service.HostSkillTree = (*skilltree.Tree)(nil)
|
||||
_ service.HostSkillInstaller = (*adapter.InstallManager)(nil)
|
||||
)
|
||||
|
||||
type hostSandboxDeps struct {
|
||||
newBackend func() (localsandbox.Backend, error)
|
||||
homeDir string
|
||||
appDataDir string
|
||||
// sessionRoot is where auto-allocated session workspaces go. Empty falls
|
||||
// back to ~/Documents/AcademyLite.
|
||||
sessionRoot string
|
||||
skillsRoot string
|
||||
// projects maps a session to a user-approved project directory.
|
||||
// Nil means every session gets an auto-allocated workspace.
|
||||
projects localsandbox.ProjectLookup
|
||||
// modes reports the approval mode. nil means ModeAuto.
|
||||
modes localsandbox.ModeLookup
|
||||
}
|
||||
|
||||
type hostSandboxParts struct {
|
||||
manager sandbox.Manager
|
||||
service *localsandbox.Service
|
||||
builder *localsandbox.PolicyBuilder
|
||||
}
|
||||
|
||||
// buildHostSandbox returns the process-wide host backend parts, or nil when
|
||||
// this machine cannot enforce one. Web/server binaries never compile this
|
||||
// file (see sandbox_host_stub.go); the desktop build tag is the isolation.
|
||||
// Never returns parts that would run commands unsandboxed.
|
||||
func buildHostSandbox(deps hostSandboxDeps) *hostSandboxParts {
|
||||
if deps.newBackend == nil {
|
||||
return nil
|
||||
}
|
||||
backend, err := deps.newBackend()
|
||||
if err != nil || backend == nil {
|
||||
return nil
|
||||
}
|
||||
if err := backend.Available(); err != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
homeDir := strings.TrimSpace(deps.homeDir)
|
||||
appDataDir := strings.TrimSpace(deps.appDataDir)
|
||||
if homeDir == "" || appDataDir == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
sessionRoot := strings.TrimSpace(deps.sessionRoot)
|
||||
if sessionRoot == "" {
|
||||
sessionRoot = defaultHostSessionRoot(homeDir)
|
||||
}
|
||||
|
||||
resolver := localsandbox.NewWorkspaceResolver(localsandbox.DirLayout{
|
||||
SessionRoot: sessionRoot,
|
||||
}, deps.projects)
|
||||
builder := localsandbox.NewPolicyBuilder(homeDir, appDataDir).WithSkillsRoot(deps.skillsRoot)
|
||||
svc := localsandbox.NewService(backend, resolver, builder, deps.modes)
|
||||
return &hostSandboxParts{manager: adapter.New(svc), service: svc, builder: builder}
|
||||
}
|
||||
|
||||
// buildHostSandboxManager returns the process-wide host backend, or nil when
|
||||
// this machine cannot enforce one.
|
||||
func buildHostSandboxManager(deps hostSandboxDeps) sandbox.Manager {
|
||||
if parts := buildHostSandbox(deps); parts != nil {
|
||||
return parts.manager
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// hostModeLookup reads the machine-local approval mode from desktop prefs.
|
||||
// A nil loader means ModeAuto.
|
||||
func hostModeLookup(load HostApprovalModeLoader) localsandbox.ModeLookup {
|
||||
if load == nil {
|
||||
return nil
|
||||
}
|
||||
return prefsModeLookup{load: load}
|
||||
}
|
||||
|
||||
// prefsModeLookup reads the machine-local approval mode. The session
|
||||
// argument is unused: approval mode is process-wide, not per session.
|
||||
//
|
||||
// The stored value comes from a file the user can hand-edit. Unknown values
|
||||
// become Auto. Known-but-unshipped modes are left intact so Service can refuse
|
||||
// them rather than silently widening access.
|
||||
type prefsModeLookup struct {
|
||||
load HostApprovalModeLoader
|
||||
}
|
||||
|
||||
func (p prefsModeLookup) ModeForSession(context.Context, string) localsandbox.ApprovalMode {
|
||||
if p.load == nil {
|
||||
return localsandbox.ModeAuto
|
||||
}
|
||||
return localsandbox.ParseApprovalMode(p.load())
|
||||
}
|
||||
|
||||
func provideHostSandboxManager(
|
||||
projects localsandbox.ProjectLookup,
|
||||
modes localsandbox.ModeLookup,
|
||||
) service.HostSandboxManager {
|
||||
out := service.HostSandboxManager{Desktop: true}
|
||||
home, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
logger.Warnf(context.Background(),
|
||||
"[sandbox] host backend disabled: cannot resolve home directory: %v", err)
|
||||
return out
|
||||
}
|
||||
skillsRoot := defaultHostSkillsRoot(home)
|
||||
parts := buildHostSandbox(hostSandboxDeps{
|
||||
newBackend: localsandbox.NewBackend,
|
||||
homeDir: home,
|
||||
appDataDir: hostAppDataDir(home),
|
||||
sessionRoot: "",
|
||||
skillsRoot: skillsRoot,
|
||||
projects: projects,
|
||||
modes: modes,
|
||||
})
|
||||
return finishHostSandbox(parts, skillsRoot)
|
||||
}
|
||||
|
||||
// finishHostSandbox publishes the host backend whenever the OS sandbox is
|
||||
// available. A skill tree that cannot be created hides local skill installs
|
||||
// and leaves chat on the host manager.
|
||||
func finishHostSandbox(parts *hostSandboxParts, skillsRoot string) service.HostSandboxManager {
|
||||
out := service.HostSandboxManager{Desktop: true}
|
||||
if parts == nil {
|
||||
return out
|
||||
}
|
||||
logger.Infof(context.Background(), "[sandbox] host backend enabled")
|
||||
out.Manager = parts.manager
|
||||
tree, err := skilltree.New(skillsRoot)
|
||||
if err != nil {
|
||||
logger.Warnf(context.Background(), "[sandbox] local skills unavailable: %v", err)
|
||||
return out
|
||||
}
|
||||
out.SkillTree = tree
|
||||
out.SkillInstaller = adapter.NewInstallManager(parts.service, parts.builder)
|
||||
return out
|
||||
}
|
||||
|
||||
func defaultHostSessionRoot(homeDir string) string {
|
||||
return filepath.Join(homeDir, "Documents", "AcademyLite")
|
||||
}
|
||||
|
||||
func defaultHostSkillsRoot(homeDir string) string {
|
||||
return filepath.Join(homeDir, ".academy", "skills")
|
||||
}
|
||||
|
||||
func hostAppDataDir(home string) string {
|
||||
if dir, err := os.UserConfigDir(); err == nil && strings.TrimSpace(dir) != "" {
|
||||
return filepath.Join(dir, "Academy Lite")
|
||||
}
|
||||
return filepath.Join(home, "Library", "Application Support", "Academy Lite")
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package container
|
||||
|
||||
import "academy/internal/handler/session"
|
||||
|
||||
// HostApprovalModeLoader reads the desktop approval-mode preference.
|
||||
// Nil (server binaries, tests that do not decorate) means ModeAuto.
|
||||
type HostApprovalModeLoader func() string
|
||||
|
||||
// HostProjectDirsLoader is the approved-directory list from desktop prefs.
|
||||
// Alias of the session-handler type so dig has one provider for both.
|
||||
type HostProjectDirsLoader = session.HostProjectDirsLoader
|
||||
|
||||
func provideHostApprovalModeLoader() HostApprovalModeLoader { return nil }
|
||||
|
||||
func provideHostProjectDirsLoader() session.HostProjectDirsLoader { return nil }
|
||||
@@ -0,0 +1,21 @@
|
||||
//go:build !desktop
|
||||
|
||||
package container
|
||||
|
||||
import "academy/internal/application/service"
|
||||
|
||||
// Dummy dig types so BuildContainer can Provide the same constructor names
|
||||
// without importing localsandbox. The desktop-tagged files replace these.
|
||||
|
||||
type (
|
||||
hostLookupDisabled struct{}
|
||||
hostModeDisabled struct{}
|
||||
)
|
||||
|
||||
func hostProjectLookup() hostLookupDisabled { return hostLookupDisabled{} }
|
||||
|
||||
func hostModeLookup() hostModeDisabled { return hostModeDisabled{} }
|
||||
|
||||
func provideHostSandboxManager() service.HostSandboxManager {
|
||||
return service.HostSandboxManager{}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
//go:build desktop
|
||||
|
||||
package container
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"go.uber.org/dig"
|
||||
|
||||
"academy/internal/application/service"
|
||||
"academy/internal/localsandbox"
|
||||
"academy/internal/sandbox"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
var errUnsupportedForTest = errors.New("unsupported for test")
|
||||
|
||||
type stubBackend struct{}
|
||||
|
||||
func (stubBackend) Name() string { return "stub" }
|
||||
func (stubBackend) Available() error { return nil }
|
||||
func (stubBackend) EnsureReady(context.Context) error { return nil }
|
||||
func (stubBackend) TearDown(context.Context) error { return nil }
|
||||
func (stubBackend) Prepare(context.Context, localsandbox.Policy) (localsandbox.Prepared, error) {
|
||||
return nil, errors.New("unused")
|
||||
}
|
||||
func (stubBackend) Spawn(context.Context, localsandbox.Prepared, localsandbox.Command) (localsandbox.Process, error) {
|
||||
return nil, errors.New("unused")
|
||||
}
|
||||
|
||||
type unavailableBackend struct{ stubBackend }
|
||||
|
||||
func (unavailableBackend) Available() error { return errUnsupportedForTest }
|
||||
|
||||
// An unsupported platform must stay off rather than run unsandboxed.
|
||||
func TestFinishHostSandboxOmitsManagerWhenPartsMissing(t *testing.T) {
|
||||
out := finishHostSandbox(nil, "")
|
||||
require.True(t, out.Desktop)
|
||||
require.Nil(t, out.Manager)
|
||||
require.False(t, out.SkillsAvailable())
|
||||
}
|
||||
|
||||
func TestFinishHostSandboxKeepsChatWhenSkillTreeCannotOpen(t *testing.T) {
|
||||
parts := buildHostSandbox(hostSandboxDeps{
|
||||
newBackend: func() (localsandbox.Backend, error) { return stubBackend{}, nil },
|
||||
homeDir: "/Users/dev",
|
||||
appDataDir: "/Users/dev/App Support/Academy",
|
||||
})
|
||||
require.NotNil(t, parts)
|
||||
require.NotNil(t, parts.manager)
|
||||
|
||||
out := finishHostSandbox(parts, "relative-not-absolute")
|
||||
require.True(t, out.Desktop)
|
||||
require.Equal(t, parts.manager, out.Manager)
|
||||
require.Nil(t, out.SkillTree)
|
||||
require.Nil(t, out.SkillInstaller)
|
||||
require.False(t, out.SkillsAvailable())
|
||||
}
|
||||
|
||||
func TestHostSandboxManagerNilWhenBackendUnavailable(t *testing.T) {
|
||||
require.Nil(t, buildHostSandboxManager(hostSandboxDeps{
|
||||
newBackend: func() (localsandbox.Backend, error) { return nil, errUnsupportedForTest },
|
||||
}))
|
||||
}
|
||||
|
||||
func TestHostSandboxManagerNilWhenAvailableFails(t *testing.T) {
|
||||
require.Nil(t, buildHostSandboxManager(hostSandboxDeps{
|
||||
newBackend: func() (localsandbox.Backend, error) { return unavailableBackend{}, nil },
|
||||
}))
|
||||
}
|
||||
|
||||
func TestDefaultHostSessionRootUsesAcademyLite(t *testing.T) {
|
||||
require.Equal(t, "/Users/dev/Documents/AcademyLite", defaultHostSessionRoot("/Users/dev"))
|
||||
}
|
||||
|
||||
func TestDefaultHostSkillsRootIsDotAcademy(t *testing.T) {
|
||||
require.Equal(t, "/Users/dev/.academy/skills", defaultHostSkillsRoot("/Users/dev"))
|
||||
}
|
||||
|
||||
func TestHostSandboxManagerEnabledWhenBackendAvailable(t *testing.T) {
|
||||
mgr := buildHostSandboxManager(hostSandboxDeps{
|
||||
newBackend: func() (localsandbox.Backend, error) { return stubBackend{}, nil },
|
||||
homeDir: "/Users/dev",
|
||||
appDataDir: "/Users/dev/App Support/Academy",
|
||||
})
|
||||
require.NotNil(t, mgr)
|
||||
require.Equal(t, sandbox.SandboxTypeHost, mgr.GetType())
|
||||
}
|
||||
|
||||
func TestProvideHostSandboxManagerAcceptsNilLookups(t *testing.T) {
|
||||
c := dig.New()
|
||||
require.NoError(t, c.Provide(func() *gorm.DB { return nil }))
|
||||
require.NoError(t, c.Provide(provideHostApprovalModeLoader))
|
||||
require.NoError(t, c.Provide(provideHostProjectDirsLoader))
|
||||
require.NoError(t, c.Provide(hostProjectLookup))
|
||||
require.NoError(t, c.Provide(hostModeLookup))
|
||||
require.NoError(t, c.Provide(provideHostSandboxManager))
|
||||
require.NoError(t, c.Invoke(func(host service.HostSandboxManager) {
|
||||
if host.Manager == nil {
|
||||
return
|
||||
}
|
||||
require.Equal(t, sandbox.SandboxTypeHost, host.Manager.GetType())
|
||||
}))
|
||||
}
|
||||
|
||||
func TestHostModeLookupReadsApprovalModeLoader(t *testing.T) {
|
||||
lookup := hostModeLookup(func() string { return "auto" })
|
||||
require.NotNil(t, lookup)
|
||||
require.Equal(t, localsandbox.ModeAuto, lookup.ModeForSession(context.Background(), "session-1"))
|
||||
}
|
||||
|
||||
func TestHostModeLookupDelegatesToParseApprovalMode(t *testing.T) {
|
||||
lookup := func(stored string) localsandbox.ApprovalMode {
|
||||
return hostModeLookup(func() string { return stored }).ModeForSession(context.Background(), "session-1")
|
||||
}
|
||||
require.Equal(t, localsandbox.ModeAsk, lookup("ask"))
|
||||
require.Equal(t, localsandbox.ModeFull, lookup("full"))
|
||||
require.Equal(t, localsandbox.ModeAuto, lookup("yolo"))
|
||||
require.Equal(t, localsandbox.ModeAuto, lookup(""))
|
||||
}
|
||||
|
||||
func TestHostModeLookupNilLoaderMeansAuto(t *testing.T) {
|
||||
require.Nil(t, hostModeLookup(nil))
|
||||
}
|
||||
|
||||
func TestHostLookupsComeFromProvidedLoaders(t *testing.T) {
|
||||
c := dig.New()
|
||||
require.NoError(t, c.Provide(func() *gorm.DB { return nil }))
|
||||
require.NoError(t, c.Provide(func() HostApprovalModeLoader {
|
||||
return func() string { return "auto" }
|
||||
}))
|
||||
require.NoError(t, c.Provide(func() HostProjectDirsLoader {
|
||||
return func() []string { return []string{"/Users/dev/My Project"} }
|
||||
}))
|
||||
require.NoError(t, c.Provide(hostProjectLookup))
|
||||
require.NoError(t, c.Provide(hostModeLookup))
|
||||
require.NoError(t, c.Invoke(func(modes localsandbox.ModeLookup, projects localsandbox.ProjectLookup) {
|
||||
require.Equal(t, localsandbox.ModeAuto, modes.ModeForSession(context.Background(), "session-1"))
|
||||
require.NotNil(t, projects)
|
||||
}))
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
package container
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strconv"
|
||||
"testing"
|
||||
|
||||
"github.com/alicebob/miniredis/v2"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"academy/internal/sandbox"
|
||||
"academy/internal/sandbox/allocation"
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
func TestSelectSessionBindingStorePrefersRedis(t *testing.T) {
|
||||
mini := miniredis.RunT(t)
|
||||
client := redis.NewClient(&redis.Options{Addr: mini.Addr()})
|
||||
t.Cleanup(func() { _ = client.Close() })
|
||||
|
||||
store, kind, err := selectSessionBindingStore(client, true)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "redis", kind)
|
||||
require.IsType(t, &sandbox.RedisSessionSandboxBindingStore{}, store)
|
||||
}
|
||||
|
||||
func TestSelectSessionBindingStoreUsesMemoryWithoutRedis(t *testing.T) {
|
||||
store, kind, err := selectSessionBindingStore(nil, true)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "memory", kind)
|
||||
require.IsType(t, &sandbox.MemorySessionSandboxBindingStore{}, store)
|
||||
}
|
||||
|
||||
func TestSelectSessionBindingStoreFallsBackToMemoryWhenNotRequired(t *testing.T) {
|
||||
store, kind, err := selectSessionBindingStore(nil, false)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "memory", kind)
|
||||
require.IsType(t, &sandbox.MemorySessionSandboxBindingStore{}, store)
|
||||
}
|
||||
|
||||
func TestSelectSessionBindingStoreUserModeNeedsRedisAndEnv(t *testing.T) {
|
||||
t.Cleanup(func() { allocation.SetUserModeAvailable(false) })
|
||||
|
||||
t.Setenv(allocation.UserModeEnvVar, "enabled")
|
||||
_, _, err := selectSessionBindingStore(nil, true)
|
||||
require.NoError(t, err)
|
||||
require.False(t, allocation.UserModeAvailable(), "env opt-in without Redis must leave the gate closed")
|
||||
|
||||
mini := miniredis.RunT(t)
|
||||
client := redis.NewClient(&redis.Options{Addr: mini.Addr()})
|
||||
t.Cleanup(func() { _ = client.Close() })
|
||||
_, _, err = selectSessionBindingStore(client, true)
|
||||
require.NoError(t, err)
|
||||
require.True(t, allocation.UserModeAvailable(), "env opt-in with Redis opens the gate")
|
||||
|
||||
t.Setenv(allocation.UserModeEnvVar, "")
|
||||
_, _, err = selectSessionBindingStore(client, true)
|
||||
require.NoError(t, err)
|
||||
require.False(t, allocation.UserModeAvailable(), "Redis without the env opt-in must leave the gate closed")
|
||||
}
|
||||
|
||||
// fakeSessionLookup implements the narrow sessionExistenceLookup surface the
|
||||
// checker depends on. Keeping the surface narrow means the test double is a
|
||||
// couple of lines instead of the full 16-method SessionRepository stub.
|
||||
type fakeSessionLookup struct {
|
||||
byID map[string]*types.Session
|
||||
err error
|
||||
}
|
||||
|
||||
func (f *fakeSessionLookup) GetByID(_ context.Context, tenantID uint64, id string) (*types.Session, error) {
|
||||
if f.err != nil {
|
||||
return nil, f.err
|
||||
}
|
||||
if s, ok := f.byID[id+"@"+strconv.FormatUint(tenantID, 10)]; ok {
|
||||
return s, nil
|
||||
}
|
||||
return nil, gorm.ErrRecordNotFound
|
||||
}
|
||||
|
||||
func TestSessionExistenceCheckerBackedByRepository(t *testing.T) {
|
||||
repo := &fakeSessionLookup{
|
||||
byID: map[string]*types.Session{
|
||||
"session-a@42": {ID: "session-a", TenantID: 42},
|
||||
},
|
||||
}
|
||||
checker := sessionExistenceCheckerFor(repo)
|
||||
|
||||
ok, err := checker.SessionExists(context.Background(), sandbox.SessionSandboxKey{TenantID: 42, SessionID: "session-a"})
|
||||
require.NoError(t, err)
|
||||
require.True(t, ok)
|
||||
|
||||
ok, err = checker.SessionExists(context.Background(), sandbox.SessionSandboxKey{TenantID: 42, SessionID: "missing"})
|
||||
require.NoError(t, err)
|
||||
require.False(t, ok)
|
||||
}
|
||||
|
||||
func TestSessionExistenceCheckerPropagatesTransientErrors(t *testing.T) {
|
||||
fault := errors.New("database offline")
|
||||
repo := &fakeSessionLookup{err: fault}
|
||||
checker := sessionExistenceCheckerFor(repo)
|
||||
|
||||
ok, err := checker.SessionExists(context.Background(), sandbox.SessionSandboxKey{TenantID: 42, SessionID: "session-a"})
|
||||
require.ErrorIs(t, err, fault)
|
||||
require.False(t, ok)
|
||||
}
|
||||
|
||||
func TestSessionExistenceCheckerFallsBackToPermissiveWhenLookupNil(t *testing.T) {
|
||||
// Lite deployments (no database) still need to boot; a nil lookup
|
||||
// hands us the permissive checker so the lifecycle coordinator never
|
||||
// blocks resolution on a missing dependency.
|
||||
checker := sessionExistenceCheckerFor(nil)
|
||||
ok, err := checker.SessionExists(context.Background(), sandbox.SessionSandboxKey{TenantID: 42, SessionID: "session-a"})
|
||||
require.NoError(t, err)
|
||||
require.True(t, ok)
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package container
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"academy/internal/types"
|
||||
"academy/internal/utils"
|
||||
)
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
// Engine wiring tests intentionally use loopback httptest servers.
|
||||
utils.SetSSRFWhitelistFromRaw("127.0.0.1,::1,localhost")
|
||||
code := m.Run()
|
||||
utils.SetSSRFWhitelistFromRaw("")
|
||||
os.Exit(code)
|
||||
}
|
||||
|
||||
func TestValidateRuntimeVectorStoreAddressesRejectsUnsafeEndpoints(t *testing.T) {
|
||||
tests := []types.VectorStore{
|
||||
{EngineType: types.QdrantRetrieverEngineType, ConnectionConfig: types.ConnectionConfig{Host: "169.254.169.254", Port: 6334}},
|
||||
{EngineType: types.MilvusRetrieverEngineType, ConnectionConfig: types.ConnectionConfig{Addr: "169.254.169.254:19530"}},
|
||||
{EngineType: types.WeaviateRetrieverEngineType, ConnectionConfig: types.ConnectionConfig{Host: "https://example.com", GrpcAddress: "169.254.169.254:50051"}},
|
||||
{EngineType: types.DorisRetrieverEngineType, ConnectionConfig: types.ConnectionConfig{Addr: "169.254.169.254:9030"}},
|
||||
{EngineType: types.TencentVectorDBRetrieverEngineType, ConnectionConfig: types.ConnectionConfig{Addr: "169.254.169.254:80"}},
|
||||
}
|
||||
for _, store := range tests {
|
||||
if err := validateRuntimeVectorStoreAddresses(store); err == nil {
|
||||
t.Fatalf("expected %s unsafe address to be rejected", store.EngineType)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateRuntimeVectorStoreAddressesAllowsNonNetworkEngines(t *testing.T) {
|
||||
for _, engineType := range []types.RetrieverEngineType{
|
||||
types.PostgresRetrieverEngineType,
|
||||
types.SQLiteRetrieverEngineType,
|
||||
} {
|
||||
if err := validateRuntimeVectorStoreAddresses(types.VectorStore{EngineType: engineType}); err != nil {
|
||||
t.Fatalf("unexpected %s validation error: %v", engineType, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package container
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"academy/internal/types"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func TestMigrateLegacyStorageBackends(t *testing.T) {
|
||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
||||
require.NoError(t, err)
|
||||
// Schema is owned by the SQL migrations in production; provision it here so
|
||||
// the test exercises only the data-migration logic.
|
||||
require.NoError(t, db.Exec(`CREATE TABLE tenants (
|
||||
id INTEGER PRIMARY KEY, name TEXT, storage_engine_config TEXT,
|
||||
default_storage_backend_id TEXT, updated_at DATETIME, deleted_at DATETIME
|
||||
)`).Error)
|
||||
require.NoError(t, db.Exec(`CREATE TABLE knowledge_bases (
|
||||
profile_config TEXT,
|
||||
generated_profile TEXT,
|
||||
id TEXT PRIMARY KEY, tenant_id INTEGER, storage_provider_config TEXT,
|
||||
storage_backend_id TEXT, cos_config TEXT, updated_at DATETIME, deleted_at DATETIME
|
||||
)`).Error)
|
||||
require.NoError(t, db.AutoMigrate(&types.StorageBackend{}))
|
||||
tenantConfig, err := (&types.StorageEngineConfig{DefaultProvider: "local", Local: &types.LocalEngineConfig{PathPrefix: "workspace-a"}}).Value()
|
||||
require.NoError(t, err)
|
||||
providerConfig, err := (types.StorageProviderConfig{Provider: "local"}).Value()
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, db.Exec("INSERT INTO tenants(id, name, storage_engine_config) VALUES (?, ?, ?)", 7, "workspace", tenantConfig).Error)
|
||||
require.NoError(t, db.Exec("INSERT INTO knowledge_bases(id, tenant_id, storage_provider_config, cos_config) VALUES (?, ?, ?, ?)", "kb-a", 7, providerConfig, []byte("{}")).Error)
|
||||
|
||||
migrateLegacyStorageBackends(db)
|
||||
|
||||
var backend types.StorageBackend
|
||||
require.NoError(t, db.Where("tenant_id = ? AND provider = ? AND legacy_alias = ?", 7, "local", true).First(&backend).Error)
|
||||
assert.Equal(t, "workspace-a", backend.Config.PathPrefix)
|
||||
|
||||
var tenantDefault, kbBackend string
|
||||
require.NoError(t, db.Raw("SELECT default_storage_backend_id FROM tenants WHERE id = 7").Scan(&tenantDefault).Error)
|
||||
require.NoError(t, db.Raw("SELECT storage_backend_id FROM knowledge_bases WHERE id = 'kb-a'").Scan(&kbBackend).Error)
|
||||
assert.Equal(t, backend.ID, tenantDefault)
|
||||
assert.Equal(t, backend.ID, kbBackend)
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package container
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
milvusclient "github.com/milvus-io/milvus/client/v2/milvusclient"
|
||||
|
||||
secutils "academy/internal/utils"
|
||||
)
|
||||
|
||||
func whitelistOnly(t *testing.T, whitelist, only string) {
|
||||
t.Helper()
|
||||
t.Setenv("SSRF_WHITELIST", whitelist)
|
||||
t.Setenv("SSRF_WHITELIST_EXTRA", "")
|
||||
t.Setenv("SSRF_DNS_WHITELIST_ONLY", only)
|
||||
secutils.ResetSSRFWhitelistForTest()
|
||||
t.Cleanup(secutils.ResetSSRFWhitelistForTest)
|
||||
}
|
||||
|
||||
// gRPC resolves its own target before any dialer runs, so an env-configured
|
||||
// vector store host can only be judged before the client exists (#3378).
|
||||
// Both helpers must refuse without opening a connection.
|
||||
func TestEnvVectorStoreClientsRefuseNonWhitelistedHost(t *testing.T) {
|
||||
whitelistOnly(t, "qdrant,milvus", "true")
|
||||
|
||||
_, err := newEnvQdrantClient("outside.invalid", 6334, "", false)
|
||||
if !errors.Is(err, secutils.ErrSSRFHostNotWhitelisted) {
|
||||
t.Fatalf("qdrant: expected the whitelist refusal, got %v", err)
|
||||
}
|
||||
|
||||
cfg := &milvusclient.ClientConfig{Address: "outside.invalid:19530"}
|
||||
if _, err := newEnvMilvusClient(context.Background(), cfg); !errors.Is(err, secutils.ErrSSRFHostNotWhitelisted) {
|
||||
t.Fatalf("milvus: expected the whitelist refusal, got %v", err)
|
||||
}
|
||||
|
||||
// The address carries a port the whitelist never matches on; the host
|
||||
// inside it is what must be compared. Past the name check the real client
|
||||
// tries to connect, so this one gets a deadline of its own.
|
||||
dialCtx, cancel := context.WithTimeout(context.Background(), time.Second)
|
||||
defer cancel()
|
||||
cfg = &milvusclient.ClientConfig{Address: "milvus:19530"}
|
||||
if _, err := newEnvMilvusClient(dialCtx, cfg); errors.Is(err, secutils.ErrSSRFHostNotWhitelisted) {
|
||||
t.Fatalf("a whitelisted host must pass the name check, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnvVectorStoreClientsIgnoreTheWhitelistWhenTheModeIsOff(t *testing.T) {
|
||||
whitelistOnly(t, "qdrant", "false")
|
||||
|
||||
_, err := newEnvQdrantClient("outside.invalid", 6334, "", false)
|
||||
if errors.Is(err, secutils.ErrSSRFHostNotWhitelisted) {
|
||||
t.Fatalf("with the mode off nothing is refused for being off-whitelist, got %v", err)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user