refactor(store)!: remove the SQLite task store, the PocketBase event store and the SQLite session store
The State Store, event capture and Gateway conversations already serve from PostgreSQL. This deletes internal/store and internal/infrastructure/edastore, the SQLite gateway session store and openProductionTaskStore, and the -db recovery path on a legacy task file; backup, restore, validate and rollback work on the database database_url names. - The binding-secret cipher moves to internal/infrastructure/bindingcipher and ToolCall to internal/infrastructure/postgres. - NewSessionStoreMemory is now a pure in-memory store that passes the shared SessionStore conformance suite. - Tests run against PostgreSQL through internal/infrastructure/postgres/pgstore; legacyimport/legacyfixture writes the legacy files the import and the boot gate read. - The cron dialect is owned in internal/domain/scheduling, so github.com/pocketbase/pocketbase and pocketbase/dbx leave go.mod. modernc.org/sqlite stays for the one-time import (legacyread). - The UI and Messaging architecture gates ban the Postgres and legacy readers in place of internal/store.
This commit is contained in:
1 parent
dda12dcdba
commit
ae552db7e0
90 files changed
+1022
-1453
No files matched your search
@@ -0,0 +1,10 @@
|
||||
package agentworker
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgtest"
|
||||
)
|
||||
|
||||
func TestMain(m *testing.M) { os.Exit(pgtest.Main(m)) }
|
||||
@@ -30,11 +30,10 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/forge"
|
||||
"github.com/samcharles93/archie-core/internal/forgerpc"
|
||||
agentnats "github.com/samcharles93/archie-core/internal/infrastructure/agenttransport/nats"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/edastore"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/staterpc"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/workflowsteps"
|
||||
"github.com/samcharles93/archie-core/internal/installtype"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
"github.com/samcharles93/archie-core/internal/taskrun"
|
||||
"github.com/samcharles93/archie-core/internal/worktree"
|
||||
"github.com/samcharles93/archie-core/internal/worktreerpc"
|
||||
@@ -370,14 +369,14 @@ func connectTaskRPC(t *testing.T, url string) *natsio.Conn {
|
||||
// on gRPC for its store calls (docs/prds/state-store-contract.md §12 step 4),
|
||||
// so an agentworker test that drives executeTaskRequest needs a real State
|
||||
// Store server rather than the deleted NATS storerpc path.
|
||||
func startStateStoreGRPC(t *testing.T, local *store.Store) string {
|
||||
func startStateStoreGRPC(t *testing.T, local *pgstore.TaskDB) string {
|
||||
t.Helper()
|
||||
listener, err := (&net.ListenConfig{}).Listen(t.Context(), "tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
server := grpc.NewServer()
|
||||
eda := edastore.OpenTest(t)
|
||||
eda := pgstore.EDA(t, nil)
|
||||
staterpc.RegisterServer(server, staterpc.Deps{
|
||||
Tasks: local, Captures: eda, Mappings: eda, Bindings: eda,
|
||||
BindingDispatcher: eda, BindingTaskCreator: local,
|
||||
@@ -393,7 +392,7 @@ func TestRunTaskExecutesBootstrapWorkflowEndToEnd(t *testing.T) {
|
||||
}
|
||||
ctx := t.Context()
|
||||
host := newLocalRemote(t, "acme", "widget")
|
||||
st := store.OpenTest(t)
|
||||
st := pgstore.Open(t)
|
||||
if _, err := st.EnqueueIssue(ctx, "acme", "widget", 1, "feat: bootstrap test", "", "bootstrap", ""); err != nil {
|
||||
t.Fatalf("enqueue: %v", err)
|
||||
}
|
||||
@@ -594,7 +593,7 @@ func TestExecuteTaskRequestUsesInfrastructureRPCDependencies(t *testing.T) {
|
||||
}
|
||||
ctx := t.Context()
|
||||
host := newLocalRemote(t, "acme", "rpc-widget")
|
||||
st := store.OpenTest(t)
|
||||
st := pgstore.Open(t)
|
||||
if _, err := st.EnqueueIssue(ctx, "acme", "rpc-widget", 2, "feat: RPC bootstrap test", "", "bootstrap", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -686,7 +685,7 @@ func TestExecuteTaskRequestForwardsWorkflowEventsOverNATS(t *testing.T) {
|
||||
}
|
||||
ctx := t.Context()
|
||||
host := newLocalRemote(t, "acme", "events-widget")
|
||||
st := store.OpenTest(t)
|
||||
st := pgstore.Open(t)
|
||||
if _, err := st.EnqueueIssue(ctx, "acme", "events-widget", 3, "feat: events bootstrap test", "", "bootstrap", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/edastore"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/bindingcipher"
|
||||
"github.com/samcharles93/archie-core/internal/secret"
|
||||
)
|
||||
|
||||
@@ -13,7 +13,7 @@ import (
|
||||
// config through the secret registry and returns the EDA store's cipher. An unset
|
||||
// encryption_key returns a nil cipher, keeping the legacy plaintext path (the
|
||||
// store's default). See docs/prds/binding-secret-encryption.md.
|
||||
func bindingCipherFromConfig(cfg config.Config, secrets *secret.Registry) (edastore.BindingCipher, error) {
|
||||
func bindingCipherFromConfig(cfg config.Config, secrets *secret.Registry) (bindingcipher.BindingCipher, error) {
|
||||
if cfg.Bindings.EncryptionKey == (secret.SecretRef{}) {
|
||||
return nil, nil
|
||||
}
|
||||
@@ -36,5 +36,5 @@ func bindingCipherFromConfig(cfg config.Config, secrets *secret.Registry) (edast
|
||||
previous = append(previous, v)
|
||||
}
|
||||
}
|
||||
return edastore.NewBindingCipher(active, previous)
|
||||
return bindingcipher.NewBindingCipher(active, previous)
|
||||
}
|
||||
@@ -5,10 +5,11 @@ import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgtest"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
)
|
||||
|
||||
func TestRemoteChatCompositionPreservesChannelTurnLedger(t *testing.T) {
|
||||
@@ -17,10 +18,7 @@ func TestRemoteChatCompositionPreservesChannelTurnLedger(t *testing.T) {
|
||||
DatabaseURL: pgtest.URL(t),
|
||||
Services: config.Services{config.ServiceNameGateway: {Target: "127.0.0.1:1"}},
|
||||
}
|
||||
st, err := store.Open(t.Context(), filepath.Join(t.TempDir(), "state-store.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
st := pgstore.Open(t)
|
||||
t.Cleanup(func() { _ = st.Close() })
|
||||
b := &boot{cfg: cfg, log: slog.Default(), cfgHolder: config.NewHolder(cfg), stateStore: st, personas: gateway.NewPersonaRegistry(gateway.DefaultPersonas())}
|
||||
t.Cleanup(b.cleanup)
|
||||
|
||||
@@ -3,11 +3,11 @@ package archied
|
||||
import (
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
"github.com/samcharles93/archie-core/internal/webui"
|
||||
)
|
||||
|
||||
@@ -49,10 +49,7 @@ func TestPublishedProjectionAgreesWithFrontEndsOnConfiguredChannels(t *testing.T
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
st, err := store.Open(t.Context(), filepath.Join(t.TempDir(), "state.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
st := pgstore.Open(t)
|
||||
t.Cleanup(func() { _ = st.Close() })
|
||||
|
||||
b := &boot{
|
||||
|
||||
@@ -4,12 +4,12 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/configuration"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
"github.com/samcharles93/archie-core/internal/webui"
|
||||
)
|
||||
|
||||
@@ -19,10 +19,7 @@ import (
|
||||
// from its own state rather than from a webui.Server it never serves
|
||||
// (archie-core-ml30).
|
||||
func TestPublishConfigSnapshotRendersTheDaemonsConfiguration(t *testing.T) {
|
||||
st, err := store.Open(t.Context(), filepath.Join(t.TempDir(), "state.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
st := pgstore.Open(t)
|
||||
t.Cleanup(func() { _ = st.Close() })
|
||||
|
||||
cfg := config.Config{
|
||||
@@ -83,10 +80,7 @@ func TestPublishConfigSnapshotRendersTheDaemonsConfiguration(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestPublishedSnapshotCarriesPerIdentityForges(t *testing.T) {
|
||||
st, err := store.Open(t.Context(), filepath.Join(t.TempDir(), "state.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
st := pgstore.Open(t)
|
||||
t.Cleanup(func() { _ = st.Close() })
|
||||
|
||||
b := &boot{
|
||||
@@ -133,10 +127,7 @@ func TestPublishedSnapshotCarriesPerIdentityForges(t *testing.T) {
|
||||
// TestPublishConfigSnapshotWithoutConfiguration: called before the daemon has
|
||||
// a configuration Holder, publishing is a no-op rather than a panic.
|
||||
func TestPublishConfigSnapshotWithoutConfiguration(t *testing.T) {
|
||||
st, err := store.Open(t.Context(), filepath.Join(t.TempDir(), "state.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
st := pgstore.Open(t)
|
||||
t.Cleanup(func() { _ = st.Close() })
|
||||
|
||||
b := &boot{log: slog.New(slog.DiscardHandler), stateStore: st}
|
||||
|
||||
@@ -23,8 +23,8 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/configuration"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/staterpc"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
"github.com/samcharles93/archie-core/internal/webui"
|
||||
)
|
||||
|
||||
@@ -68,7 +68,7 @@ type controlPlaneRestartFixture struct {
|
||||
// reading apply status back.
|
||||
func newControlPlaneRestartFixture(t *testing.T) *controlPlaneRestartFixture {
|
||||
t.Helper()
|
||||
local := store.OpenTest(t)
|
||||
local := pgstore.Open(t)
|
||||
t.Cleanup(func() { _ = local.Close() })
|
||||
|
||||
steps, err := stepVocabulary()
|
||||
|
||||
@@ -15,8 +15,9 @@ import (
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/app/controlplane"
|
||||
pb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/workflowsteps"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
)
|
||||
|
||||
// outageStore is the State Store's resource half with a switch that makes every
|
||||
@@ -32,7 +33,7 @@ import (
|
||||
// lasted longer than the minimum retry interval, which is a failed attempt
|
||||
// whichever way the store failed it.
|
||||
type outageStore struct {
|
||||
*store.Store
|
||||
*pgstore.TaskDB
|
||||
|
||||
mu sync.Mutex
|
||||
failing bool
|
||||
@@ -46,15 +47,15 @@ func (s *outageStore) down(stall time.Duration) {
|
||||
s.failing, s.stall = true, stall
|
||||
}
|
||||
|
||||
func (s *outageStore) Resource(ctx context.Context, kind string) (store.Resource, error) {
|
||||
func (s *outageStore) Resource(ctx context.Context, kind string) (storecontract.Resource, error) {
|
||||
s.mu.Lock()
|
||||
failing, stall := s.failing, s.stall
|
||||
s.mu.Unlock()
|
||||
if failing {
|
||||
time.Sleep(stall)
|
||||
return store.Resource{}, errors.New("state store unreachable")
|
||||
return storecontract.Resource{}, errors.New("state store unreachable")
|
||||
}
|
||||
return s.Store.Resource(ctx, kind)
|
||||
return s.TaskDB.Resource(ctx, kind)
|
||||
}
|
||||
|
||||
// TestWatchRetryGrowsWhileTheStateStoreIsDown is the outage this reconnect
|
||||
@@ -113,7 +114,7 @@ func TestWatchRetryGrowsWhileTheStateStoreIsDown(t *testing.T) {
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
database := &outageStore{Store: store.OpenTest(t)}
|
||||
database := &outageStore{TaskDB: pgstore.Open(t)}
|
||||
defer database.Close()
|
||||
steps, err := workflowsteps.NewManager()
|
||||
if err != nil {
|
||||
|
||||
@@ -7,13 +7,11 @@ import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/legacyimport/legacyfixture"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgtest"
|
||||
)
|
||||
@@ -23,18 +21,7 @@ import (
|
||||
// see legacy data.
|
||||
func seedLegacyConversation(t *testing.T, dbPath string) {
|
||||
t.Helper()
|
||||
legacy, err := gateway.OpenSQLiteSessionStore(conversationDBPath(dbPath))
|
||||
if err != nil {
|
||||
t.Fatalf("open legacy conversation store: %v", err)
|
||||
}
|
||||
defer legacy.Close()
|
||||
if err := legacy.Save(t.Context(), messaging.SessionContext{
|
||||
SessionID: "legacy",
|
||||
Source: messaging.SessionSource{Platform: "telegram", BotUser: "archie"},
|
||||
CreatedAt: time.Now(),
|
||||
}); err != nil {
|
||||
t.Fatalf("seed legacy session: %v", err)
|
||||
}
|
||||
legacyfixture.Exec(t, conversationDBPath(dbPath), legacyfixture.GatewayDDL)
|
||||
}
|
||||
|
||||
func testPool(t *testing.T, url string) *pgxpool.Pool {
|
||||
|
||||
@@ -43,7 +43,6 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/plugin"
|
||||
"github.com/samcharles93/archie-core/internal/secret"
|
||||
"github.com/samcharles93/archie-core/internal/storage"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
"github.com/samcharles93/archie-core/internal/taskstate"
|
||||
"github.com/samcharles93/archie-core/internal/tools"
|
||||
"github.com/samcharles93/archie-core/internal/tools/mcp"
|
||||
@@ -284,10 +283,6 @@ func resolveForge(cfg config.Forge, secrets *secret.Registry, log *slog.Logger)
|
||||
return client, token
|
||||
}
|
||||
|
||||
func openProductionTaskStore(ctx context.Context, path string, opts ...store.OpenOption) (storecontract.TaskStore, error) {
|
||||
return store.Open(ctx, path, opts...)
|
||||
}
|
||||
|
||||
func taskDBPath(configuredPath string) string {
|
||||
return configuredPath + "-tasks.sqlite"
|
||||
}
|
||||
|
||||
@@ -7,13 +7,14 @@ import (
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
|
||||
"github.com/nats-io/nats-server/v2/server"
|
||||
natssrv "github.com/nats-io/nats-server/v2/test"
|
||||
natsio "github.com/nats-io/nats.go"
|
||||
@@ -30,7 +31,6 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
"github.com/samcharles93/archie-core/internal/logging"
|
||||
"github.com/samcharles93/archie-core/internal/secret"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
"github.com/samcharles93/archie-core/internal/tools"
|
||||
"github.com/samcharles93/archie-core/internal/worktree"
|
||||
"github.com/samcharles93/archie-core/internal/worktreerpc"
|
||||
@@ -528,10 +528,7 @@ func TestManualRequeueTaskUsesPersistedStatus(t *testing.T) {
|
||||
tests := []string{workflow.StatusParked, workflow.StatusWaitingHuman}
|
||||
for index, status := range tests {
|
||||
t.Run(status, func(t *testing.T) {
|
||||
st, err := store.Open(t.Context(), filepath.Join(t.TempDir(), "tasks.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
st := pgstore.Open(t)
|
||||
t.Cleanup(func() { _ = st.Close() })
|
||||
if _, err := st.EnqueueIssue(t.Context(), "acme", "widget", index+1, "task", "", "", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -555,10 +552,7 @@ func TestManualRequeueTaskUsesPersistedStatus(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestManualRequeueTaskRejectsOtherStatuses(t *testing.T) {
|
||||
st, err := store.Open(t.Context(), filepath.Join(t.TempDir(), "tasks.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
st := pgstore.Open(t)
|
||||
t.Cleanup(func() { _ = st.Close() })
|
||||
if _, err := st.EnqueueIssue(t.Context(), "acme", "widget", 1, "task", "", "", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -573,10 +567,7 @@ func TestManualRequeueTaskRejectsOtherStatuses(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestChatTaskListerAdapterReadsSQLiteIdentity(t *testing.T) {
|
||||
st, err := store.Open(t.Context(), filepath.Join(t.TempDir(), "tasks.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
st := pgstore.Open(t)
|
||||
t.Cleanup(func() { _ = st.Close() })
|
||||
want, err := st.EnqueueChatTask(t.Context(), "acme", "widget", "identity task", "", "tdd", "reviewer")
|
||||
if err != nil {
|
||||
@@ -827,10 +818,7 @@ func TestChatTaskLogReaderAdapterRoundTrip(t *testing.T) {
|
||||
|
||||
func TestChatTaskCommandsEndToEnd(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
st, err := store.Open(t.Context(), filepath.Join(t.TempDir(), "tasks.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
st := pgstore.Open(t)
|
||||
t.Cleanup(func() {
|
||||
if err := st.Close(); err != nil {
|
||||
t.Errorf("close store: %v", err)
|
||||
|
||||
@@ -5,9 +5,10 @@ import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
"github.com/samcharles93/archie-core/internal/webui"
|
||||
)
|
||||
|
||||
@@ -49,10 +50,7 @@ func TestPingChat_ReportsUnwiredChat(t *testing.T) {
|
||||
// on the store, config, disk, model and gateway in the running daemon -- only
|
||||
// that every subsystem the epic names is actually wired.
|
||||
func TestSetupReadinessProbes_WiresEverySubsystem(t *testing.T) {
|
||||
st, err := store.Open(t.Context(), filepath.Join(t.TempDir(), "test.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
st := pgstore.Open(t)
|
||||
t.Cleanup(func() { _ = st.Close() })
|
||||
|
||||
cfg := config.Config{
|
||||
|
||||
@@ -2,13 +2,13 @@ package archied
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workintake"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
)
|
||||
|
||||
// TestBuildDaemonCarriesWorkflowRoutingBindings pins the composition hop in the
|
||||
@@ -21,10 +21,7 @@ import (
|
||||
// the "tested in isolation, never verified wired" shape this repo has been bitten
|
||||
// by before.
|
||||
func TestBuildDaemonCarriesWorkflowRoutingBindings(t *testing.T) {
|
||||
storeA, err := store.Open(t.Context(), filepath.Join(t.TempDir(), "store-a.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
storeA := pgstore.Open(t)
|
||||
t.Cleanup(func() { _ = storeA.Close() })
|
||||
storeB := openSecondStore(t)
|
||||
|
||||
|
||||
@@ -14,9 +14,10 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/daemon"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
)
|
||||
|
||||
// notifyRecorder captures every record at every level. The other recording
|
||||
@@ -126,10 +127,7 @@ func newNotifyTestBoot(t *testing.T, cadence time.Duration) (*boot, *daemon.Daem
|
||||
t.Helper()
|
||||
cfg := config.Config{PollInterval: config.Duration(cadence)}
|
||||
holder := config.NewHolder(cfg)
|
||||
st, err := store.Open(t.Context(), filepath.Join(t.TempDir(), "tasks.db"))
|
||||
if err != nil {
|
||||
t.Fatalf("open task store: %v", err)
|
||||
}
|
||||
st := pgstore.Open(t)
|
||||
log := slog.New(slog.DiscardHandler)
|
||||
d := &daemon.Daemon{Cfg: holder, Store: st, Log: log}
|
||||
return &boot{cfg: cfg, cfgHolder: holder, d: d, log: log}, d
|
||||
|
||||
@@ -2,47 +2,36 @@ package archied
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/edastore"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
taskactionstore "github.com/samcharles93/archie-core/internal/infrastructure/taskactions"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
)
|
||||
|
||||
// openSecondStore opens a second, independent *store.Store on a fresh temp
|
||||
// openSecondStore opens a second, independent *pgstore.TaskDB on a fresh temp
|
||||
// path so a boot consumer test can prove the composition routes through
|
||||
// b.stateStore rather than b.st: the two differ by identity, so an assertion
|
||||
// that a consumer field holds storeB (not storeA) can only pass if the wiring
|
||||
// reads b.stateStore.
|
||||
// stateStoreAdapter stands in for the real adapter (*staterpc.Client), which
|
||||
// fronts both halves of the contract over one connection: the task store and
|
||||
// the event-capture store. A plain *store.Store no longer satisfies the
|
||||
// the event-capture store. A plain *pgstore.TaskDB no longer satisfies the
|
||||
// event-capture surfaces, so a test that asserts "everything routes through
|
||||
// the adapter" needs something that implements them, exactly as the client
|
||||
// does in production.
|
||||
// edaSide aliases the event-capture store so it can be embedded beside
|
||||
// *store.Store: both are named Store, and Go allows only one embedded field
|
||||
// per name.
|
||||
type edaSide = edastore.Store
|
||||
|
||||
type stateStoreAdapter struct {
|
||||
*store.Store
|
||||
*edaSide
|
||||
*pgstore.TaskDB
|
||||
*postgres.EDA
|
||||
}
|
||||
|
||||
// Close disambiguates the two embedded stores, which both have one.
|
||||
func (a *stateStoreAdapter) Close() error { return a.Store.Close() }
|
||||
|
||||
func openSecondStore(t *testing.T) *stateStoreAdapter {
|
||||
t.Helper()
|
||||
st, err := store.Open(t.Context(), filepath.Join(t.TempDir(), "state-store.db"))
|
||||
if err != nil {
|
||||
t.Fatalf("open second store: %v", err)
|
||||
}
|
||||
st := pgstore.Open(t)
|
||||
t.Cleanup(func() { _ = st.Close() })
|
||||
return &stateStoreAdapter{Store: st, edaSide: edastore.OpenTest(t)}
|
||||
return &stateStoreAdapter{TaskDB: st, EDA: pgstore.EDA(t, nil)}
|
||||
}
|
||||
|
||||
// TestBuildDaemonRoutesTaskStoreThroughStateStore proves the daemon's task
|
||||
@@ -52,10 +41,7 @@ func openSecondStore(t *testing.T) *stateStoreAdapter {
|
||||
// (docs/prds/state-store-contract.md §12 step 6): the daemon's Store field and
|
||||
// its mapping/binding dispatch surfaces all come from the adapter.
|
||||
func TestBuildDaemonRoutesTaskStoreThroughStateStore(t *testing.T) {
|
||||
storeA, err := store.Open(t.Context(), filepath.Join(t.TempDir(), "store-a.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
storeA := pgstore.Open(t)
|
||||
t.Cleanup(func() { _ = storeA.Close() })
|
||||
storeB := openSecondStore(t)
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ package archied
|
||||
|
||||
import (
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/edastore"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/bindingcipher"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres"
|
||||
)
|
||||
|
||||
@@ -19,6 +19,6 @@ type eventCaptureStore interface {
|
||||
|
||||
// openEDAStore serves the event-capture store from the State Store's Postgres
|
||||
// pool, sealing binding secrets with cipher.
|
||||
func (b *boot) openEDAStore(cipher edastore.BindingCipher) {
|
||||
func (b *boot) openEDAStore(cipher bindingcipher.BindingCipher) {
|
||||
b.eda = postgres.NewEDA(b.pg, cipher)
|
||||
}
|
||||
@@ -5,12 +5,12 @@
|
||||
// State Store is up -- is unavailable in exactly the case that needs it
|
||||
// (docs/architecture/safe-change-and-recovery.md).
|
||||
//
|
||||
// With -db an operation works on the legacy SQLite task file; without it, on
|
||||
// the PostgreSQL database database_url names (state_store_recovery_postgres.go).
|
||||
// The ones that write refuse while a serving process owns the store. Backup is
|
||||
// the exception and deliberately so: the update installer cannot stop the
|
||||
// process that runs it, so the snapshot that makes a failed update recoverable
|
||||
// is taken against a serving store through a consistent copy.
|
||||
// Every operation but import works on the PostgreSQL database database_url
|
||||
// names (state_store_recovery_postgres.go). The ones that write refuse while a
|
||||
// serving process owns the store. Backup is the exception and deliberately so:
|
||||
// the update installer cannot stop the process that runs it, so the snapshot
|
||||
// that makes a failed update recoverable is taken against a serving store
|
||||
// through a consistent copy.
|
||||
//
|
||||
// The control-plane server both validate and rollback read through is built by
|
||||
// openStateStoreControlPlane -- the same root helper the served path uses -- so
|
||||
@@ -28,8 +28,8 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/app/controlplane"
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
pb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/configuration"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
)
|
||||
|
||||
// The audit identity every offline rollback records. A rollback is one more
|
||||
@@ -55,9 +55,6 @@ const (
|
||||
type StateStoreRecoveryOptions struct {
|
||||
// Operation is one of backup, restore, validate, rollback.
|
||||
Operation string
|
||||
// DB is the task database file the State Store owns: the configured
|
||||
// db_path with "-tasks.sqlite" appended, not the configured path itself.
|
||||
DB string
|
||||
// Out is the snapshot backup writes.
|
||||
Out string
|
||||
// From is the snapshot restore reads.
|
||||
@@ -88,90 +85,7 @@ func RunStateStoreRecovery(ctx context.Context, options StateStoreRecoveryOption
|
||||
if options.Operation == RecoveryImport {
|
||||
return importLegacy(ctx, options)
|
||||
}
|
||||
// -db names the legacy SQLite task file; without it the command works on
|
||||
// the PostgreSQL database the configuration names.
|
||||
if options.DB == "" {
|
||||
return runPostgresRecovery(ctx, options)
|
||||
}
|
||||
switch options.Operation {
|
||||
case RecoveryBackup:
|
||||
if options.Out == "" {
|
||||
return "", errors.New("backup requires -out")
|
||||
}
|
||||
return summarise(store.Backup(ctx, options.DB, options.Out), "backed up %s to %s", options.DB, options.Out)
|
||||
case RecoveryRestore:
|
||||
if options.From == "" {
|
||||
return "", errors.New("restore requires -from")
|
||||
}
|
||||
return summarise(store.Restore(ctx, options.DB, options.From),
|
||||
"restored %s from %s; start the State Store again", options.DB, options.From)
|
||||
case RecoveryValidate:
|
||||
return validateStore(ctx, options)
|
||||
case RecoveryRollback:
|
||||
if options.Kind == "" {
|
||||
return "", errors.New("rollback requires -kind")
|
||||
}
|
||||
return rollbackResource(ctx, options)
|
||||
default:
|
||||
return "", fmt.Errorf("unknown recovery command %q", options.Operation)
|
||||
}
|
||||
}
|
||||
|
||||
// summarise is an operation's stdout line, or its error.
|
||||
func summarise(err error, format string, args ...any) (string, error) {
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return fmt.Sprintf(format, args...), nil
|
||||
}
|
||||
|
||||
// validateStore answers the question an operator actually has: would archied
|
||||
// start against this file. It runs the checks that stop it, in the order boot
|
||||
// meets them.
|
||||
//
|
||||
// First the file itself, since a database that is corrupt, newer than this
|
||||
// binary, or not a database is one the serving process refuses to open. Then
|
||||
// the writer's own per-resource validation, which is what a hand-edited value
|
||||
// violated. Then boot's gate: the file config with every stored resource
|
||||
// layered onto it, and configuration.Validate -- the check whose failure the
|
||||
// daemon reports as "validate database settings".
|
||||
//
|
||||
// The two validation layers disagree in both directions, and both are reported
|
||||
// rather than merged. The write path is stricter about shape (it rejects
|
||||
// unknown fields boot's decode ignores), while boot is stricter about meaning
|
||||
// (only boot checks dispatch.trigger and a positive poll interval, both of
|
||||
// which the write path's own validators let through). A store either check
|
||||
// refuses is a store somebody has to look at.
|
||||
func validateStore(ctx context.Context, options StateStoreRecoveryOptions) (string, error) {
|
||||
version, err := store.ValidateFile(ctx, options.DB)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
st, err := store.OpenReadOnly(ctx, options.DB)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer func() { _ = st.Close() }()
|
||||
|
||||
server, err := openStateStoreControlPlane(st)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
// Is there a resources table at all? A store written before the control plane
|
||||
// existed has none, and the State Store creates it and seeds every kind from
|
||||
// this same config on its next start -- so there is nothing stored to check
|
||||
// with the writer's validator, and boot's gate is the config check alone.
|
||||
// That is the same stance the layering takes for a kind the table is missing:
|
||||
// what the daemon reads for a kind nothing was ever stored for is the seed.
|
||||
stored, err := st.StoresResources(ctx)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
checked, err := checkBootGate(ctx, server, stored, options)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return fmt.Sprintf("%s is a valid store at schema version %d; %d stored resources validate", options.DB, version, checked), nil
|
||||
return runPostgresRecovery(ctx, options)
|
||||
}
|
||||
|
||||
// checkBootGate runs the writer's per-resource validation over what is stored,
|
||||
@@ -222,32 +136,6 @@ func bootConfig(ctx context.Context, options StateStoreRecoveryOptions) (config.
|
||||
return b.cfg, nil
|
||||
}
|
||||
|
||||
// rollbackResource is the one operation the Web UI cannot be asked to perform
|
||||
// here: the daemon fails closed on the bad value, so the store that would serve
|
||||
// the rollback is the store that will not start. It replays the revision's own
|
||||
// value through the ordinary replace, so no rollback RPC exists or is needed,
|
||||
// and the rollback is audited as one more revision.
|
||||
func rollbackResource(ctx context.Context, options StateStoreRecoveryOptions) (string, error) {
|
||||
// Before the lock and before the open: opening a store creates the file,
|
||||
// and a rollback pointed at a mistyped path must not leave an empty
|
||||
// database where the operator expected theirs.
|
||||
if err := store.RequireDatabase(options.DB); err != nil {
|
||||
return "", err
|
||||
}
|
||||
ownership, err := store.AcquireOwnership(options.DB)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer func() { _ = ownership.Release() }()
|
||||
|
||||
st, err := store.Open(ctx, options.DB)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer func() { _ = st.Close() }()
|
||||
return replayRevision(ctx, st, options)
|
||||
}
|
||||
|
||||
// replayRevision puts back the revision options names through the control
|
||||
// plane's ordinary replace. The caller holds the store's ownership claim.
|
||||
func replayRevision(ctx context.Context, resources controlplane.ResourceStore, options StateStoreRecoveryOptions) (string, error) {
|
||||
@@ -259,7 +147,7 @@ func replayRevision(ctx context.Context, resources controlplane.ResourceStore, o
|
||||
return "", fmt.Errorf("unknown resource kind %q", options.Kind)
|
||||
}
|
||||
current, err := resources.Resource(ctx, options.Kind)
|
||||
if errors.Is(err, store.ErrResourceNotFound) {
|
||||
if errors.Is(err, storecontract.ErrResourceNotFound) {
|
||||
return "", fmt.Errorf("%s has no stored value to roll back", options.Kind)
|
||||
}
|
||||
if err != nil {
|
||||
@@ -287,10 +175,10 @@ func replayRevision(ctx context.Context, resources controlplane.ResourceStore, o
|
||||
|
||||
// revisionToReplay picks the value to put back: the revision the operator
|
||||
// named, or the newest one older than the value the resource carries now.
|
||||
func revisionToReplay(ctx context.Context, st controlplane.ResourceStore, kind string, current, requested int64) (store.Resource, error) {
|
||||
func revisionToReplay(ctx context.Context, st controlplane.ResourceStore, kind string, current, requested int64) (storecontract.Resource, error) {
|
||||
history, err := st.ResourceHistory(ctx, kind, 0)
|
||||
if err != nil {
|
||||
return store.Resource{}, fmt.Errorf("read %s history: %w", kind, err)
|
||||
return storecontract.Resource{}, fmt.Errorf("read %s history: %w", kind, err)
|
||||
}
|
||||
if requested > 0 {
|
||||
for _, revision := range history {
|
||||
@@ -298,16 +186,16 @@ func revisionToReplay(ctx context.Context, st controlplane.ResourceStore, kind s
|
||||
continue
|
||||
}
|
||||
if revision.Version == current {
|
||||
return store.Resource{}, fmt.Errorf("%s revision %d is the current version; there is nothing to roll back to", kind, requested)
|
||||
return storecontract.Resource{}, fmt.Errorf("%s revision %d is the current version; there is nothing to roll back to", kind, requested)
|
||||
}
|
||||
return revision, nil
|
||||
}
|
||||
return store.Resource{}, fmt.Errorf("%s has no revision %d", kind, requested)
|
||||
return storecontract.Resource{}, fmt.Errorf("%s has no revision %d", kind, requested)
|
||||
}
|
||||
for _, revision := range history {
|
||||
if revision.Version < current {
|
||||
return revision, nil
|
||||
}
|
||||
}
|
||||
return store.Resource{}, fmt.Errorf("%s has no earlier revision to roll back to", kind)
|
||||
return storecontract.Resource{}, fmt.Errorf("%s has no earlier revision to roll back to", kind)
|
||||
}
|
||||
@@ -21,7 +21,7 @@ func runPostgresRecovery(ctx context.Context, options StateStoreRecoveryOptions)
|
||||
}
|
||||
url := cfg.DatabaseURL
|
||||
if url == "" {
|
||||
return "", errors.New("database_url is required: the configuration names no PostgreSQL database (pass -db for a legacy SQLite task file)")
|
||||
return "", errors.New("database_url is required: the configuration names no PostgreSQL database")
|
||||
}
|
||||
switch options.Operation {
|
||||
case RecoveryBackup:
|
||||
@@ -70,7 +70,8 @@ func openRecoveryPool(ctx context.Context, url string) (*pgxpool.Pool, int64, er
|
||||
return pool, version, nil
|
||||
}
|
||||
|
||||
// validatePostgres is validateStore for the PostgreSQL database. An
|
||||
// validatePostgres answers whether archied would start against the database:
|
||||
// the stored resources pass the writer's validation and boot's gate. An
|
||||
// unmigrated database holds nothing to check; the State Store migrates and
|
||||
// seeds it on its next start, so only boot's config gate applies.
|
||||
func validatePostgres(ctx context.Context, url string, options StateStoreRecoveryOptions) (string, error) {
|
||||
|
||||
@@ -12,11 +12,10 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
pb "github.com/samcharles93/archie-core/internal/contracts/state/v1"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/edastore"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgtest"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/staterpc"
|
||||
"github.com/samcharles93/archie-core/internal/logging"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
)
|
||||
|
||||
func TestStateStoreServerOptsLoopbackIsInsecure(t *testing.T) {
|
||||
@@ -60,11 +59,7 @@ func TestStateStoreServerOptsMalformedListen(t *testing.T) {
|
||||
// in-process, now extracted into its own process. A read-only StatusCounts
|
||||
// call proves the service is registered and wired to the opened store.
|
||||
func TestServeStateStoreServesContract(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
st, err := store.Open(t.Context(), filepath.Join(dir, "tasks.sqlite"))
|
||||
if err != nil {
|
||||
t.Fatalf("open temp store: %v", err)
|
||||
}
|
||||
st := pgstore.Open(t)
|
||||
defer st.Close()
|
||||
|
||||
b := newBootstrap()
|
||||
@@ -132,31 +127,28 @@ func TestStateStoreDepsServeTaskLogs(t *testing.T) {
|
||||
}
|
||||
|
||||
// TestStateStoreDepsServePlaybookDispatcher verifies stateStoreDeps lifts the
|
||||
// opened *store.Store's PlaybookDispatcher surface onto Deps, so the
|
||||
// opened *pgstore.TaskDB's PlaybookDispatcher surface onto Deps, so the
|
||||
// standalone State Store has a server for the two playbook RPCs. It does not
|
||||
// dial those RPCs here -- it inspects the assembled Deps only. The nil check
|
||||
// is the load-bearing part: a boot without a store must leave
|
||||
// PlaybookDispatcher nil (the server then answers codes.Unavailable) rather
|
||||
// than fabricating a dispatcher.
|
||||
func TestStateStoreDepsServePlaybookDispatcher(t *testing.T) {
|
||||
st, err := store.Open(t.Context(), filepath.Join(t.TempDir(), "tasks.sqlite"))
|
||||
if err != nil {
|
||||
t.Fatalf("open temp store: %v", err)
|
||||
}
|
||||
st := pgstore.Open(t)
|
||||
defer st.Close()
|
||||
|
||||
b := newBootstrap()
|
||||
b.st = st
|
||||
// The playbook ledger moved to the event-capture store with the rest of
|
||||
// the dispatch tables; the task store no longer serves it.
|
||||
eda := edastore.OpenTest(t)
|
||||
eda := pgstore.EDA(t, nil)
|
||||
b.eda = eda
|
||||
deps := b.stateStoreDeps(&staterpc.TaskGrants{})
|
||||
if deps.PlaybookDispatcher == nil {
|
||||
t.Fatal("stateStoreDeps leaves PlaybookDispatcher nil; the standalone State Store is the only production server for the playbook dispatch ledger")
|
||||
}
|
||||
if deps.PlaybookDispatcher != storecontract.PlaybookDispatcher(eda) {
|
||||
t.Fatalf("PlaybookDispatcher = %T, want the opened *edastore.Store", deps.PlaybookDispatcher)
|
||||
t.Fatalf("PlaybookDispatcher = %T, want the opened *postgres.EDA", deps.PlaybookDispatcher)
|
||||
}
|
||||
// A boot without a store must not fabricate one: nil keeps the RPCs honest
|
||||
// as unavailable rather than depending on a nil receiver.
|
||||
|
||||
@@ -7,13 +7,13 @@ import (
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/edastore"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres"
|
||||
)
|
||||
|
||||
// toolCallWriter is the edastore surface the projection writes through. Kept
|
||||
// toolCallWriter is the EDA store surface the projection writes through. Kept
|
||||
// narrow so a test can fail it without touching the real store.
|
||||
type toolCallWriter interface {
|
||||
InsertToolCall(ctx context.Context, tc edastore.ToolCall) error
|
||||
InsertToolCall(ctx context.Context, tc postgres.ToolCall) error
|
||||
}
|
||||
|
||||
// toolCallProjectingTaskStore decorates the State Store's task store so every
|
||||
@@ -69,10 +69,10 @@ func (s *toolCallProjectingTaskStore) InsertEvent(ctx context.Context, e events.
|
||||
// fields stay unwritten -- the event reports neither -- so they are schema
|
||||
// reserved for a producer that one day reports them, not promises this
|
||||
// projection makes.
|
||||
func toolCallFromEvent(e events.Event) edastore.ToolCall {
|
||||
func toolCallFromEvent(e events.Event) postgres.ToolCall {
|
||||
tool, _ := e.Data["tool"].(string)
|
||||
failed, _ := e.Data["failed"].(bool)
|
||||
tc := edastore.ToolCall{
|
||||
tc := postgres.ToolCall{
|
||||
TaskID: e.TaskID,
|
||||
Attempt: e.Attempt,
|
||||
Tool: tool,
|
||||
|
||||
@@ -10,9 +10,9 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/edastore"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/staterpc"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
)
|
||||
|
||||
func toolCallEvent(taskID int64, attempt int) events.Event {
|
||||
@@ -33,8 +33,8 @@ func toolCallEvent(taskID int64, attempt int) events.Event {
|
||||
// tool_calls row, with the row's fields taken from the event -- the tool name
|
||||
// from data, the output summary in result for a succeeded call.
|
||||
func TestInsertEventProjectsToolCall(t *testing.T) {
|
||||
st := store.OpenTest(t)
|
||||
eda := edastore.OpenTest(t)
|
||||
st := pgstore.Open(t)
|
||||
eda := pgstore.EDA(t, nil)
|
||||
ts := newToolCallProjectingTaskStore(st, eda, slog.Default())
|
||||
|
||||
id, err := ts.InsertEvent(t.Context(), toolCallEvent(42, 2))
|
||||
@@ -74,8 +74,8 @@ func TestInsertEventProjectsToolCall(t *testing.T) {
|
||||
// event whose call failed stores its detail under error, not result, so the
|
||||
// transcript can distinguish the two without re-parsing text.
|
||||
func TestInsertEventProjectsFailedToolCall(t *testing.T) {
|
||||
st := store.OpenTest(t)
|
||||
eda := edastore.OpenTest(t)
|
||||
st := pgstore.Open(t)
|
||||
eda := pgstore.EDA(t, nil)
|
||||
ts := newToolCallProjectingTaskStore(st, eda, slog.Default())
|
||||
|
||||
e := toolCallEvent(42, 2)
|
||||
@@ -104,8 +104,8 @@ func TestInsertEventProjectsFailedToolCall(t *testing.T) {
|
||||
// tool_call events reach the collection; the task timeline's other kinds must
|
||||
// not grow tool_calls rows.
|
||||
func TestInsertEventLeavesOtherKindsUnprojected(t *testing.T) {
|
||||
st := store.OpenTest(t)
|
||||
eda := edastore.OpenTest(t)
|
||||
st := pgstore.Open(t)
|
||||
eda := pgstore.EDA(t, nil)
|
||||
ts := newToolCallProjectingTaskStore(st, eda, slog.Default())
|
||||
|
||||
if _, err := ts.InsertEvent(t.Context(), events.Event{
|
||||
@@ -129,7 +129,7 @@ func TestInsertEventLeavesOtherKindsUnprojected(t *testing.T) {
|
||||
// store.
|
||||
type failingToolCallWriter struct{ err error }
|
||||
|
||||
func (f failingToolCallWriter) InsertToolCall(context.Context, edastore.ToolCall) error {
|
||||
func (f failingToolCallWriter) InsertToolCall(context.Context, postgres.ToolCall) error {
|
||||
return f.err
|
||||
}
|
||||
|
||||
@@ -138,7 +138,7 @@ func (f failingToolCallWriter) InsertToolCall(context.Context, edastore.ToolCall
|
||||
// event persistence is the contract, the projection is observability -- and
|
||||
// the failure is recorded, not swallowed silently.
|
||||
func TestInsertEventSucceedsWhenProjectionFails(t *testing.T) {
|
||||
st := store.OpenTest(t)
|
||||
st := pgstore.Open(t)
|
||||
var buf bytes.Buffer
|
||||
ts := newToolCallProjectingTaskStore(st, failingToolCallWriter{
|
||||
err: errors.New("disk on fire"),
|
||||
@@ -172,8 +172,8 @@ func TestInsertEventSucceedsWhenProjectionFails(t *testing.T) {
|
||||
// event-capture store, Tasks is passed through untouched rather than wrapped
|
||||
// around a nil writer.
|
||||
func TestStateStoreDepsProjectToolCalls(t *testing.T) {
|
||||
st := store.OpenTest(t)
|
||||
eda := edastore.OpenTest(t)
|
||||
st := pgstore.Open(t)
|
||||
eda := pgstore.EDA(t, nil)
|
||||
|
||||
b := newBootstrap()
|
||||
b.st = st
|
||||
|
||||
@@ -23,7 +23,7 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/domain/curator"
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
)
|
||||
|
||||
// TestProviderOutcomeRecorderRecordsTheLastCallOnly pins the producer behind
|
||||
@@ -356,7 +356,7 @@ func TestRouterWithHealthAnswersStatus(t *testing.T) {
|
||||
sessions := gateway.NewSessionStoreMemory()
|
||||
t.Cleanup(func() { _ = sessions.Close() })
|
||||
|
||||
st := store.OpenTest(t)
|
||||
st := pgstore.Open(t)
|
||||
router := gateway.NewRouter(st, nil, "web")
|
||||
router.InitSessions(sessions)
|
||||
router.Health = statusHealth{broker: func() (bool, bool) { return true, true }}
|
||||
|
||||
@@ -4,15 +4,16 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/domain/taskactions"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
"github.com/samcharles93/archie-core/internal/taskstate"
|
||||
)
|
||||
|
||||
@@ -35,7 +36,7 @@ func (a testTaskActor) ApplyChatTaskAction(
|
||||
}, nil
|
||||
}
|
||||
|
||||
func newChatTaskActorForTest(t *testing.T, st store.TaskStore, cfg config.Config) chatTaskActorAdapter {
|
||||
func newChatTaskActorForTest(t *testing.T, st storecontract.TaskStore, cfg config.Config) chatTaskActorAdapter {
|
||||
t.Helper()
|
||||
b := &boot{
|
||||
st: st,
|
||||
@@ -48,10 +49,7 @@ func newChatTaskActorForTest(t *testing.T, st store.TaskStore, cfg config.Config
|
||||
|
||||
func TestChatTaskActorAdapterCrossIdentityRefused(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
st, err := store.Open(ctx, filepath.Join(t.TempDir(), "tasks.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
st := pgstore.Open(t)
|
||||
t.Cleanup(func() { _ = st.Close() })
|
||||
|
||||
task, err := st.EnqueueChatTask(ctx, "acme", "widget", "parked job", "", "", "identity-owner")
|
||||
@@ -111,10 +109,7 @@ func TestChatTaskActorAdapterCrossIdentityRefused(t *testing.T) {
|
||||
|
||||
func TestChatTaskActorAdapterRefusesDisallowedStateAction(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
st, err := store.Open(ctx, filepath.Join(t.TempDir(), "tasks.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
st := pgstore.Open(t)
|
||||
t.Cleanup(func() { _ = st.Close() })
|
||||
|
||||
adapter := newChatTaskActorForTest(t, st, config.Config{})
|
||||
@@ -188,15 +183,12 @@ func TestChatTaskActorAdapterRefusesDisallowedStateAction(t *testing.T) {
|
||||
|
||||
func TestChatTaskActorAdapterTaskNotFound(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
st, err := store.Open(ctx, filepath.Join(t.TempDir(), "tasks.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
st := pgstore.Open(t)
|
||||
t.Cleanup(func() { _ = st.Close() })
|
||||
|
||||
adapter := newChatTaskActorForTest(t, st, config.Config{})
|
||||
|
||||
_, err = adapter.ApplyChatTaskAction(ctx, new("archie"), taskactions.Actor{}, 999999, taskstate.ActionAbandon)
|
||||
_, err := adapter.ApplyChatTaskAction(ctx, new("archie"), taskactions.Actor{}, 999999, taskstate.ActionAbandon)
|
||||
if err == nil {
|
||||
t.Fatal("expected error for non-existent task, got nil")
|
||||
}
|
||||
@@ -260,10 +252,7 @@ func TestChatTaskActorAdapterAppliesActionsToStore(t *testing.T) {
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
st, err := store.Open(ctx, filepath.Join(t.TempDir(), "tasks.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
st := pgstore.Open(t)
|
||||
t.Cleanup(func() { _ = st.Close() })
|
||||
|
||||
adapter := newChatTaskActorForTest(t, st, config.Config{MaxRetries: 3})
|
||||
|
||||
@@ -6,14 +6,15 @@ import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
"github.com/samcharles93/archie-core/internal/webui"
|
||||
)
|
||||
|
||||
@@ -44,10 +45,7 @@ func TestDashboardAndChatAgreeOnTerminalStates(t *testing.T) {
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
st, err := store.Open(ctx, filepath.Join(t.TempDir(), "tasks.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
st := pgstore.Open(t)
|
||||
t.Cleanup(func() { _ = st.Close() })
|
||||
|
||||
task, err := st.EnqueueChatTask(ctx, "acme", "widget", "decide on me", "", "", "reviewer")
|
||||
@@ -78,7 +76,7 @@ func TestDashboardAndChatAgreeOnTerminalStates(t *testing.T) {
|
||||
|
||||
// runChatAction performs the approve/cancel action through the chat
|
||||
// controller path and fails the test on error.
|
||||
func runChatAction(t *testing.T, ctx context.Context, st store.TaskStore, action string, taskID int64) {
|
||||
func runChatAction(t *testing.T, ctx context.Context, st storecontract.TaskStore, action string, taskID int64) {
|
||||
t.Helper()
|
||||
controller := gateway.NewStoreTaskController(chatTaskControllerAdapter{
|
||||
taskByID: st.TaskByID,
|
||||
@@ -99,7 +97,7 @@ func runChatAction(t *testing.T, ctx context.Context, st store.TaskStore, action
|
||||
// runDashboardAction performs the approve/cancel action through the
|
||||
// dashboard's HTTP handler and fails the test when the request is
|
||||
// rejected.
|
||||
func runDashboardAction(t *testing.T, ctx context.Context, st store.TaskStore, action string, taskID int64) {
|
||||
func runDashboardAction(t *testing.T, ctx context.Context, st storecontract.TaskStore, action string, taskID int64) {
|
||||
t.Helper()
|
||||
// The dashboard reaches task actions through the Gateway contract, which
|
||||
// in production carries them back to this daemon's own service. Wiring
|
||||
|
||||
@@ -10,8 +10,8 @@ import (
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/configuration"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/gatewayrpc"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/staterpc"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
)
|
||||
|
||||
// isNil reports whether v is nil, including a typed nil func or pointer
|
||||
@@ -61,8 +61,8 @@ func TestComposeUIServerHoldsNoDaemonState(t *testing.T) {
|
||||
if _, ok := srv.Store.(*staterpc.Client); !ok {
|
||||
t.Fatalf("Store = %T, want *staterpc.Client", srv.Store)
|
||||
}
|
||||
if _, ok := srv.Store.(*store.Store); ok {
|
||||
t.Fatal("Store is the concrete *store.Store; the UI process must not open archie.db")
|
||||
if _, ok := srv.Store.(*pgstore.TaskDB); ok {
|
||||
t.Fatal("Store is the concrete *pgstore.TaskDB; the UI process must not open archie.db")
|
||||
}
|
||||
if srv.Chat == nil {
|
||||
t.Fatal("Chat is nil; the UI process must dial the Gateway contract")
|
||||
|
||||
@@ -13,10 +13,9 @@ import (
|
||||
|
||||
"google.golang.org/grpc"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/edastore"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/staterpc"
|
||||
"github.com/samcharles93/archie-core/internal/logging"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
"github.com/samcharles93/archie-core/internal/webui"
|
||||
)
|
||||
|
||||
@@ -153,10 +152,7 @@ func TestRoutesWithoutAContractDegradeExplicitly(t *testing.T) {
|
||||
// all -- the shape every route below has to survive.
|
||||
func composeUIProcess(t *testing.T) (*webui.Server, int64) {
|
||||
t.Helper()
|
||||
st, err := store.Open(t.Context(), filepath.Join(t.TempDir(), "tasks.sqlite"))
|
||||
if err != nil {
|
||||
t.Fatalf("open store: %v", err)
|
||||
}
|
||||
st := pgstore.Open(t)
|
||||
t.Cleanup(func() { _ = st.Close() })
|
||||
|
||||
// The task-log reader lives on the state-directory side of the boundary:
|
||||
@@ -166,7 +162,7 @@ func composeUIProcess(t *testing.T) (*webui.Server, int64) {
|
||||
logs := logging.NewTaskRegistry(filepath.Join(t.TempDir(), "logs", "tasks"), logging.NewFeed(10), logging.TaskSinkOptions{})
|
||||
|
||||
target, stop := serveGRPC(t, func(r grpc.ServiceRegistrar) {
|
||||
eda := edastore.OpenTest(t)
|
||||
eda := pgstore.EDA(t, nil)
|
||||
staterpc.RegisterServer(r, staterpc.Deps{
|
||||
Tasks: st, Captures: eda, BindingDispatcher: eda, ConfigSnapshots: st,
|
||||
TaskLogs: logs, Log: slog.New(slog.DiscardHandler),
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
package archieui
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgtest"
|
||||
)
|
||||
|
||||
func TestMain(m *testing.M) { os.Exit(pgtest.Main(m)) }
|
||||
@@ -18,13 +18,13 @@ import (
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/health"
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/domain/taskactions"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/edastore"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/gatewayrpc"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/staterpc"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
"github.com/samcharles93/archie-core/internal/taskstate"
|
||||
"github.com/samcharles93/archie-core/internal/webui"
|
||||
)
|
||||
@@ -100,10 +100,7 @@ func serveGRPC(t *testing.T, register func(grpc.ServiceRegistrar)) (target strin
|
||||
// every route with no contract behind it degrades exactly as
|
||||
// docs/prds/ui-service-boundary.md:130-131 permits.
|
||||
func TestUIServesDashboardAgainstRemoteContracts(t *testing.T) {
|
||||
st, err := store.Open(t.Context(), filepath.Join(t.TempDir(), "tasks.sqlite"))
|
||||
if err != nil {
|
||||
t.Fatalf("open temp store: %v", err)
|
||||
}
|
||||
st := pgstore.Open(t)
|
||||
defer st.Close()
|
||||
seeded, err := st.EnqueueChatTask(t.Context(), "acme", "widget", "remote summary", "body", "implement", "")
|
||||
if err != nil {
|
||||
@@ -119,7 +116,7 @@ func TestUIServesDashboardAgainstRemoteContracts(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := st.PutConfigSnapshot(t.Context(), store.ConfigSnapshot{
|
||||
if err := st.PutConfigSnapshot(t.Context(), storecontract.ConfigSnapshot{
|
||||
Schema: webui.ConfigViewSchema, Document: published,
|
||||
}); err != nil {
|
||||
t.Fatalf("publish config snapshot: %v", err)
|
||||
@@ -152,7 +149,7 @@ func TestUIServesDashboardAgainstRemoteContracts(t *testing.T) {
|
||||
}
|
||||
|
||||
stateTarget, stopState := serveGRPC(t, func(r grpc.ServiceRegistrar) {
|
||||
eda := edastore.OpenTest(t)
|
||||
eda := pgstore.EDA(t, nil)
|
||||
staterpc.RegisterServer(r, staterpc.Deps{Tasks: st, Captures: eda, BindingDispatcher: eda, ConfigSnapshots: st, Log: slog.New(slog.DiscardHandler)})
|
||||
})
|
||||
defer stopState()
|
||||
|
||||
@@ -13,10 +13,9 @@ import (
|
||||
|
||||
"google.golang.org/grpc"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/edastore"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/staterpc"
|
||||
"github.com/samcharles93/archie-core/internal/logging"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
"github.com/samcharles93/archie-core/internal/webui"
|
||||
)
|
||||
|
||||
@@ -154,10 +153,7 @@ func TestUIProcessReportsMissingTaskLogsHonestly(t *testing.T) {
|
||||
// file, so the dashboard's read has to cross the wire to see anything.
|
||||
func composeUIProcessWithLog(t *testing.T) (*webui.Server, int64, int) {
|
||||
t.Helper()
|
||||
st, err := store.Open(t.Context(), filepath.Join(t.TempDir(), "tasks.sqlite"))
|
||||
if err != nil {
|
||||
t.Fatalf("open store: %v", err)
|
||||
}
|
||||
st := pgstore.Open(t)
|
||||
t.Cleanup(func() { _ = st.Close() })
|
||||
|
||||
task, err := st.EnqueueChatTask(t.Context(), "acme", "widget", "a task", "body", "implement", "")
|
||||
@@ -179,7 +175,7 @@ func composeUIProcessWithLog(t *testing.T) (*webui.Server, int64, int) {
|
||||
}
|
||||
|
||||
target, stop := serveGRPC(t, func(r grpc.ServiceRegistrar) {
|
||||
eda := edastore.OpenTest(t)
|
||||
eda := pgstore.EDA(t, nil)
|
||||
staterpc.RegisterServer(r, staterpc.Deps{
|
||||
Tasks: st, Captures: eda, BindingDispatcher: eda, ConfigSnapshots: st,
|
||||
TaskLogs: logs, Log: slog.New(slog.DiscardHandler),
|
||||
|
||||
@@ -11,9 +11,9 @@ import (
|
||||
"google.golang.org/protobuf/types/known/timestamppb"
|
||||
|
||||
pb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/controlplanerpc"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
)
|
||||
|
||||
// The control-plane wire sentinels cross gRPC matched on (code, canonical
|
||||
@@ -31,9 +31,9 @@ var (
|
||||
// root asserts the State Store against it, so this is the single definition of
|
||||
// what a control-plane backing store must offer.
|
||||
type ResourceStore interface {
|
||||
Resource(context.Context, string) (store.Resource, error)
|
||||
ResourceHistory(context.Context, string, int) ([]store.Resource, error)
|
||||
PutResource(context.Context, store.ResourceWrite) (store.Resource, error)
|
||||
Resource(context.Context, string) (storecontract.Resource, error)
|
||||
ResourceHistory(context.Context, string, int) ([]storecontract.Resource, error)
|
||||
PutResource(context.Context, storecontract.ResourceWrite) (storecontract.Resource, error)
|
||||
}
|
||||
|
||||
// defaultHistoryLimit caps an unbounded request. A settings resource edited
|
||||
@@ -121,7 +121,7 @@ func (s *Server) Command(ctx context.Context, request *pb.CommandRequest) (*pb.C
|
||||
if err != nil {
|
||||
return nil, mapError(err)
|
||||
}
|
||||
resource, err := s.store.PutResource(ctx, store.ResourceWrite{Kind: request.Kind, Value: value, Actor: request.Actor, Source: request.Source, RequestID: request.RequestId, ExpectedVersion: request.ExpectedVersion, At: time.Now().UTC()})
|
||||
resource, err := s.store.PutResource(ctx, storecontract.ResourceWrite{Kind: request.Kind, Value: value, Actor: request.Actor, Source: request.Source, RequestID: request.RequestId, ExpectedVersion: request.ExpectedVersion, At: time.Now().UTC()})
|
||||
if err != nil {
|
||||
return nil, mapError(err)
|
||||
}
|
||||
@@ -142,7 +142,7 @@ func (s *Server) Watch(request *pb.WatchRequest, stream pb.ControlPlaneService_W
|
||||
return err
|
||||
}
|
||||
version = resource.Version
|
||||
} else if err != nil && !errors.Is(err, store.ErrResourceNotFound) {
|
||||
} else if err != nil && !errors.Is(err, storecontract.ErrResourceNotFound) {
|
||||
return mapError(err)
|
||||
}
|
||||
select {
|
||||
@@ -153,7 +153,7 @@ func (s *Server) Watch(request *pb.WatchRequest, stream pb.ControlPlaneService_W
|
||||
}
|
||||
}
|
||||
|
||||
func resourceProto(resource store.Resource) *pb.Resource {
|
||||
func resourceProto(resource storecontract.Resource) *pb.Resource {
|
||||
return &pb.Resource{Kind: resource.Kind, Version: resource.Version, ValueJson: resource.Value, UpdatedAt: timestamp(resource.At)}
|
||||
}
|
||||
|
||||
@@ -168,9 +168,9 @@ func mapError(err error) error {
|
||||
switch {
|
||||
case errors.Is(err, ErrValidation):
|
||||
return status.Error(codes.InvalidArgument, err.Error())
|
||||
case errors.Is(err, store.ErrResourceNotFound):
|
||||
case errors.Is(err, storecontract.ErrResourceNotFound):
|
||||
return status.Error(codes.NotFound, err.Error())
|
||||
case errors.Is(err, store.ErrResourceVersionConflict):
|
||||
case errors.Is(err, storecontract.ErrResourceVersionConflict):
|
||||
return status.Error(codes.Aborted, err.Error())
|
||||
default:
|
||||
return status.Error(codes.Unavailable, err.Error())
|
||||
|
||||
@@ -13,9 +13,10 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
pb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
|
||||
"github.com/samcharles93/archie-core/internal/domain/agent"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/workflowsteps"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
)
|
||||
|
||||
// testSteps builds the production workflow step vocabulary for tests that are
|
||||
@@ -45,7 +46,7 @@ func testServer(t *testing.T, resources ResourceStore) *Server {
|
||||
func TestCatalogCarriesShippedWorkflowDefinitionsForRestore(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
resources := store.OpenTest(t)
|
||||
resources := pgstore.Open(t)
|
||||
defer resources.Close()
|
||||
catalog, err := testServer(t, resources).Catalog(t.Context(), &pb.CatalogRequest{})
|
||||
if err != nil {
|
||||
@@ -72,7 +73,7 @@ func TestCatalogCarriesShippedWorkflowDefinitionsForRestore(t *testing.T) {
|
||||
func TestImportConfigSeedsWorkflowDefinitionsWithoutOverwritingOverride(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
resources := store.OpenTest(t)
|
||||
resources := pgstore.Open(t)
|
||||
defer resources.Close()
|
||||
server := testServer(t, resources)
|
||||
if _, _, err := server.ImportConfig(t.Context(), config.Config{}); err != nil {
|
||||
@@ -94,7 +95,7 @@ func TestImportConfigSeedsWorkflowDefinitionsWithoutOverwritingOverride(t *testi
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := resources.PutResource(t.Context(), store.ResourceWrite{Kind: WorkflowDefinitionsKind, Value: value, ExpectedVersion: resource.Version, Actor: "test", Source: "test", RequestID: "override"}); err != nil {
|
||||
if _, err := resources.PutResource(t.Context(), storecontract.ResourceWrite{Kind: WorkflowDefinitionsKind, Value: value, ExpectedVersion: resource.Version, Actor: "test", Source: "test", RequestID: "override"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, _, err := server.ImportConfig(t.Context(), config.Config{}); err != nil {
|
||||
@@ -112,7 +113,7 @@ func TestImportConfigSeedsWorkflowDefinitionsWithoutOverwritingOverride(t *testi
|
||||
func TestImportConfigSeedsPersonasWithoutOverwritingEdits(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
resources := store.OpenTest(t)
|
||||
resources := pgstore.Open(t)
|
||||
defer resources.Close()
|
||||
server := testServer(t, resources)
|
||||
if _, _, err := server.ImportConfig(t.Context(), config.Config{}); err != nil {
|
||||
@@ -131,7 +132,7 @@ func TestImportConfigSeedsPersonasWithoutOverwritingEdits(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := resources.PutResource(t.Context(), store.ResourceWrite{Kind: PersonasKind, Value: value, ExpectedVersion: resource.Version, Actor: "test", Source: "test", RequestID: "persona-edit"}); err != nil {
|
||||
if _, err := resources.PutResource(t.Context(), storecontract.ResourceWrite{Kind: PersonasKind, Value: value, ExpectedVersion: resource.Version, Actor: "test", Source: "test", RequestID: "persona-edit"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, _, err := server.ImportConfig(t.Context(), config.Config{}); err != nil {
|
||||
@@ -150,7 +151,7 @@ func TestImportConfigSeedsPersonasWithoutOverwritingEdits(t *testing.T) {
|
||||
func TestImportWorkflowExecutionSettingsDoesNotOverwriteExistingValue(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
resources := store.OpenTest(t)
|
||||
resources := pgstore.Open(t)
|
||||
defer resources.Close()
|
||||
server := testServer(t, resources)
|
||||
first := workflow.ExecutionSettings{MaxModelToolSteps: 10, MaxRuntime: time.Minute, MaxConsecutiveGateFailures: 2}
|
||||
@@ -176,7 +177,7 @@ func TestImportWorkflowExecutionSettingsDoesNotOverwriteExistingValue(t *testing
|
||||
func TestRegistryRoutesAndValidatesDefinitions(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
resources := store.OpenTest(t)
|
||||
resources := pgstore.Open(t)
|
||||
defer resources.Close()
|
||||
server := testServer(t, resources)
|
||||
// The image is required, here as in the file document: a seed without one is
|
||||
@@ -212,7 +213,7 @@ func TestRegistryRoutesAndValidatesDefinitions(t *testing.T) {
|
||||
func TestProviderSeedKeepsReferencesAndNeverResolvedSecrets(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
resources := store.OpenTest(t)
|
||||
resources := pgstore.Open(t)
|
||||
defer resources.Close()
|
||||
server := testServer(t, resources)
|
||||
cfg := config.Config{Providers: map[string]config.Provider{"openai": {Class: "openai", APIKeyEnv: "OPENAI_API_KEY", APIKey: config.SecretRef{Engine: "env", Key: "OPENAI_API_KEY"}}}}
|
||||
@@ -239,7 +240,7 @@ func TestProviderSeedKeepsReferencesAndNeverResolvedSecrets(t *testing.T) {
|
||||
func TestHistoryCarriesEveryRevisionWithItsAudit(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
resources := store.OpenTest(t)
|
||||
resources := pgstore.Open(t)
|
||||
defer resources.Close()
|
||||
server := testServer(t, resources)
|
||||
if _, _, err := server.ImportConfig(t.Context(), config.Config{}); err != nil {
|
||||
@@ -288,7 +289,7 @@ func TestHistoryCarriesEveryRevisionWithItsAudit(t *testing.T) {
|
||||
func TestImportConfigSkipsASeedItCannotValidate(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
resources := store.OpenTest(t)
|
||||
resources := pgstore.Open(t)
|
||||
defer resources.Close()
|
||||
server := testServer(t, resources)
|
||||
// Every other field is filled in the way the loader fills it (Validate
|
||||
@@ -307,7 +308,7 @@ func TestImportConfigSkipsASeedItCannotValidate(t *testing.T) {
|
||||
if len(skipped) != 1 || skipped[0].Kind != RepositoryPoliciesKind || skipped[0].Err == nil {
|
||||
t.Fatalf("skipped = %+v, want the repository policies and the reason", skipped)
|
||||
}
|
||||
if _, err := resources.Resource(t.Context(), RepositoryPoliciesKind); !errors.Is(err, store.ErrResourceNotFound) {
|
||||
if _, err := resources.Resource(t.Context(), RepositoryPoliciesKind); !errors.Is(err, storecontract.ErrResourceNotFound) {
|
||||
t.Errorf("repository policies Resource = %v, want ErrResourceNotFound: an invalid seed must not be stored", err)
|
||||
}
|
||||
// Kinds that are fine are still seeded: one skipped kind does not abandon
|
||||
|
||||
@@ -15,8 +15,9 @@ import (
|
||||
"google.golang.org/grpc/test/bufconn"
|
||||
|
||||
pb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
)
|
||||
|
||||
// scriptedWatchClient is the rpc end of a Watch call whose stream is scripted
|
||||
@@ -222,7 +223,7 @@ func TestWatchClientsDeliverNothingForAStreamThatDidNotFail(t *testing.T) {
|
||||
func TestWatchServesOnlyVersionsAfterTheRequestedOne(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
resources := store.OpenTest(t)
|
||||
resources := pgstore.Open(t)
|
||||
defer resources.Close()
|
||||
server := testServer(t, resources)
|
||||
version, err := server.ImportWorkflowExecutionSettings(t.Context(), workflow.ExecutionSettings{MaxModelToolSteps: 10, MaxRuntime: time.Minute, MaxConsecutiveGateFailures: 2})
|
||||
@@ -280,7 +281,7 @@ func TestWatchServesOnlyVersionsAfterTheRequestedOne(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := resources.PutResource(ctx, store.ResourceWrite{Kind: WorkflowExecutionSettingsKind, Value: value, ExpectedVersion: version, Actor: "test", Source: "test", RequestID: "watch-next"}); err != nil {
|
||||
if _, err := resources.PutResource(ctx, storecontract.ResourceWrite{Kind: WorkflowExecutionSettingsKind, Value: value, ExpectedVersion: version, Actor: "test", Source: "test", RequestID: "watch-next"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
select {
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
package controlplane
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgtest"
|
||||
)
|
||||
|
||||
func TestMain(m *testing.M) { os.Exit(pgtest.Main(m)) }
|
||||
@@ -10,7 +10,7 @@ import (
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
pb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
)
|
||||
|
||||
type Definition struct {
|
||||
@@ -96,7 +96,7 @@ func (s *Server) ImportConfig(ctx context.Context, cfg config.Config) (map[strin
|
||||
versions[definition.Kind] = resource.Version
|
||||
continue
|
||||
}
|
||||
if !errors.Is(err, store.ErrResourceNotFound) {
|
||||
if !errors.Is(err, storecontract.ErrResourceNotFound) {
|
||||
return nil, nil, err
|
||||
}
|
||||
value, err := definition.seededValue(cfg)
|
||||
@@ -111,7 +111,7 @@ func (s *Server) ImportConfig(ctx context.Context, cfg config.Config) (map[strin
|
||||
skipped = append(skipped, SeedSkip{Kind: definition.Kind, Err: err})
|
||||
continue
|
||||
}
|
||||
resource, err = s.store.PutResource(ctx, store.ResourceWrite{Kind: definition.Kind, Value: value, Actor: "system:migration", Source: "legacy-config", RequestID: "import:" + definition.Kind, ExpectedVersion: 0, At: time.Now().UTC()})
|
||||
resource, err = s.store.PutResource(ctx, storecontract.ResourceWrite{Kind: definition.Kind, Value: value, Actor: "system:migration", Source: "legacy-config", RequestID: "import:" + definition.Kind, ExpectedVersion: 0, At: time.Now().UTC()})
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("seed %s: %w", definition.Kind, err)
|
||||
}
|
||||
@@ -176,7 +176,7 @@ func (s *Server) ValidateStored(ctx context.Context) (int, error) {
|
||||
var failures []error
|
||||
for _, definition := range s.ordered {
|
||||
resource, err := s.store.Resource(ctx, definition.Kind)
|
||||
if errors.Is(err, store.ErrResourceNotFound) {
|
||||
if errors.Is(err, storecontract.ErrResourceNotFound) {
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
|
||||
@@ -8,8 +8,8 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/controlplanerpc"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
)
|
||||
|
||||
// resourceReader is the one read the layering performs: a resource kind's value
|
||||
@@ -72,10 +72,10 @@ type storeReader struct {
|
||||
|
||||
func (r storeReader) Query(ctx context.Context, kind string, decode func([]byte) error) (int64, bool, error) {
|
||||
resource, err := r.resources.Resource(ctx, kind)
|
||||
if errors.Is(err, store.ErrResourceNotFound) {
|
||||
if errors.Is(err, storecontract.ErrResourceNotFound) {
|
||||
seed, ok := r.seeds[kind]
|
||||
if !ok {
|
||||
return 0, false, fmt.Errorf("read %s: %w", kind, store.ErrResourceNotFound)
|
||||
return 0, false, fmt.Errorf("read %s: %w", kind, storecontract.ErrResourceNotFound)
|
||||
}
|
||||
if err := decode(seed); err != nil {
|
||||
return 0, false, fmt.Errorf("decode %s seed: %w", kind, err)
|
||||
|
||||
@@ -35,8 +35,8 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/app/agentworker"
|
||||
pb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/workflowsteps"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
"github.com/samcharles93/archie-core/internal/taskrun"
|
||||
)
|
||||
|
||||
@@ -191,7 +191,7 @@ func TestEveryProductionResolutionSiteResolvesTheRegisteredStepType(t *testing.T
|
||||
// than dereference it: a nil-pointer panic is the same failure with no clue in
|
||||
// it.
|
||||
func TestNilStepVocabularyFailsClosedAtEveryResolutionSite(t *testing.T) {
|
||||
resources := store.OpenTest(t)
|
||||
resources := pgstore.Open(t)
|
||||
t.Cleanup(func() {
|
||||
if err := resources.Close(); err != nil {
|
||||
t.Errorf("close test store: %v", err)
|
||||
@@ -256,7 +256,7 @@ func requireRefusal(t *testing.T, side, stepType string, err error) {
|
||||
func admitThroughStateStore(t *testing.T, steps *workflow.Manager, stepType string) (before, after int64, err error) {
|
||||
t.Helper()
|
||||
|
||||
resources := store.OpenTest(t)
|
||||
resources := pgstore.Open(t)
|
||||
t.Cleanup(func() {
|
||||
if closeErr := resources.Close(); closeErr != nil {
|
||||
t.Errorf("close test store: %v", closeErr)
|
||||
|
||||
@@ -8,8 +8,8 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
)
|
||||
|
||||
const WorkflowExecutionSettingsKind = "workflow-execution-settings"
|
||||
@@ -27,7 +27,7 @@ func (s *Server) ImportWorkflowExecutionSettings(ctx context.Context, settings w
|
||||
if err == nil {
|
||||
return resource.Version, nil
|
||||
}
|
||||
if !errors.Is(err, store.ErrResourceNotFound) {
|
||||
if !errors.Is(err, storecontract.ErrResourceNotFound) {
|
||||
return 0, err
|
||||
}
|
||||
value, err := encodeSettings(settings)
|
||||
@@ -38,7 +38,7 @@ func (s *Server) ImportWorkflowExecutionSettings(ctx context.Context, settings w
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
resource, err = s.store.PutResource(ctx, store.ResourceWrite{Kind: WorkflowExecutionSettingsKind, Value: value, Actor: "system:migration", Source: "legacy-config", RequestID: "import:" + WorkflowExecutionSettingsKind, ExpectedVersion: 0, At: time.Now().UTC()})
|
||||
resource, err = s.store.PutResource(ctx, storecontract.ResourceWrite{Kind: WorkflowExecutionSettingsKind, Value: value, Actor: "system:migration", Source: "legacy-config", RequestID: "import:" + WorkflowExecutionSettingsKind, ExpectedVersion: 0, At: time.Now().UTC()})
|
||||
return resource.Version, err
|
||||
}
|
||||
|
||||
|
||||
@@ -27,10 +27,10 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/forge"
|
||||
agentnats "github.com/samcharles93/archie-core/internal/infrastructure/agenttransport/nats"
|
||||
arnats "github.com/samcharles93/archie-core/internal/infrastructure/eventbus/nats"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
"github.com/samcharles93/archie-core/internal/logging"
|
||||
"github.com/samcharles93/archie-core/internal/secret"
|
||||
"github.com/samcharles93/archie-core/internal/storage"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
"github.com/samcharles93/archie-core/internal/taskrun"
|
||||
"github.com/samcharles93/archie-core/internal/taskstate"
|
||||
"github.com/samcharles93/archie-core/internal/worktree"
|
||||
@@ -558,7 +558,7 @@ func startEmbeddedNATSForDaemon(t *testing.T) *server.Server {
|
||||
// daemonWithNATS returns the daemon, its store, and the concrete bus
|
||||
// client -- tests that drive core-NATS subscriptions directly need the
|
||||
// connection, which the TaskBus contract deliberately does not expose.
|
||||
func daemonWithNATS(t *testing.T) (*Daemon, *store.Store, *arnats.Client) {
|
||||
func daemonWithNATS(t *testing.T) (*Daemon, *pgstore.TaskDB, *arnats.Client) {
|
||||
t.Helper()
|
||||
srv := startEmbeddedNATSForDaemon(t)
|
||||
client, err := arnats.Connect(context.Background(), arnats.Config{URL: srv.ClientURL(), Subjects: []string{workintake.SubjectTaskWildcard}, FilterSubject: workintake.SubjectTaskWildcard}, slog.New(slog.DiscardHandler))
|
||||
@@ -567,7 +567,7 @@ func daemonWithNATS(t *testing.T) (*Daemon, *store.Store, *arnats.Client) {
|
||||
}
|
||||
t.Cleanup(client.Close)
|
||||
|
||||
s := store.OpenTest(t)
|
||||
s := pgstore.Open(t)
|
||||
d := &Daemon{
|
||||
Cfg: config.NewHolder(config.Config{
|
||||
Dispatch: config.Dispatch{Labels: map[string]string{
|
||||
@@ -1115,10 +1115,10 @@ func (f *testForge) React(context.Context, string, string, int, string) error
|
||||
func (f *testForge) VerifyPush(context.Context, string, string) error { return nil }
|
||||
func (f *testForge) LinkBranch(context.Context, string, string, int, string) error { return nil }
|
||||
|
||||
func testDaemon(t *testing.T, maxRetries, _ int) (*Daemon, *store.Store, *testForge) {
|
||||
func testDaemon(t *testing.T, maxRetries, _ int) (*Daemon, *pgstore.TaskDB, *testForge) {
|
||||
t.Helper()
|
||||
|
||||
s := store.OpenTest(t)
|
||||
s := pgstore.Open(t)
|
||||
fg := &testForge{}
|
||||
|
||||
cfg := config.Config{
|
||||
@@ -1256,9 +1256,9 @@ func TestDaemonStoresIdentityRunners(t *testing.T) {
|
||||
// only ever be acted on through that identity's own forge client and
|
||||
// worktree manager; it must never fall back to the root d.Forge/d.Trees
|
||||
// or leak into the other identity's client.
|
||||
func twoIdentityDaemon(t *testing.T) (d *Daemon, s *store.Store, rootFg, archieFg, winterFg *testForge) {
|
||||
func twoIdentityDaemon(t *testing.T) (d *Daemon, s *pgstore.TaskDB, rootFg, archieFg, winterFg *testForge) {
|
||||
t.Helper()
|
||||
s = store.OpenTest(t)
|
||||
s = pgstore.Open(t)
|
||||
rootFg = &testForge{}
|
||||
archieFg = &testForge{}
|
||||
winterFg = &testForge{}
|
||||
@@ -1439,7 +1439,7 @@ func TestStartupSweepsEveryConfiguredForge(t *testing.T) {
|
||||
|
||||
d := &Daemon{
|
||||
Cfg: config.NewHolder(config.Config{Repos: tc.rootRepos}),
|
||||
Store: store.OpenTest(t),
|
||||
Store: pgstore.Open(t),
|
||||
Forge: rootFg,
|
||||
Log: slog.New(slog.DiscardHandler),
|
||||
Identities: runners,
|
||||
@@ -1499,7 +1499,7 @@ func TestStartupSweepIsolatesAStalledForge(t *testing.T) {
|
||||
siblingFg := &sweepForge{}
|
||||
d := &Daemon{
|
||||
Cfg: config.NewHolder(config.Config{}),
|
||||
Store: store.OpenTest(t),
|
||||
Store: pgstore.Open(t),
|
||||
Forge: rootFg,
|
||||
Log: slog.New(slog.DiscardHandler),
|
||||
Identities: []*IdentityRunner{{Name: "sibling", Forge: siblingFg}},
|
||||
@@ -2139,7 +2139,7 @@ func TestDispatchCapturesTheAttemptsEffectiveConfig(t *testing.T) {
|
||||
// always fails, so the fail-open policy of the capture can be observed without
|
||||
// breaking everything else the dispatch needs.
|
||||
type failingEventStore struct {
|
||||
*store.Store
|
||||
*pgstore.TaskDB
|
||||
}
|
||||
|
||||
func (f failingEventStore) InsertEvent(context.Context, events.Event) (int64, error) {
|
||||
@@ -2151,7 +2151,7 @@ func (f failingEventStore) InsertEvent(context.Context, events.Event) (int64, er
|
||||
// go out anyway, and nothing may park.
|
||||
func TestCaptureAttemptConfigFailureDoesNotStopTheDispatch(t *testing.T) {
|
||||
d, s, busClient := daemonWithNATS(t)
|
||||
d.Store = failingEventStore{Store: s}
|
||||
d.Store = failingEventStore{TaskDB: s}
|
||||
ctx := context.Background()
|
||||
|
||||
if _, err := s.EnqueueIssue(ctx, "acme", "widget", 6, "t", "b", "", ""); err != nil {
|
||||
|
||||
@@ -3,16 +3,18 @@ package daemon
|
||||
import (
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/binding"
|
||||
"github.com/samcharles93/archie-core/internal/domain/mapping"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/edastore"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
)
|
||||
|
||||
// Test 30: an armed binding + an authenticated capture creates a task
|
||||
@@ -249,23 +251,20 @@ func TestDispatchBindingsNilDispatcherIsNoOp(t *testing.T) {
|
||||
// production uses (CREATE TABLE + ALTER TABLE migrations), so
|
||||
// binding_id / binding_version / binding_dispatches all exist on the
|
||||
// store by the time a test runs.
|
||||
// dispatchStores pairs the two stores the dispatcher spans: tasks stay on
|
||||
// SQLite, event capture is the PocketBase store. They are embedded so a seed
|
||||
// helper still reads as one handle; the method sets no longer overlap, which
|
||||
// is exactly what the split bought.
|
||||
// dispatchStores pairs the two stores the dispatcher spans: the task store and
|
||||
// the event-capture store, so a seed helper reads as one handle.
|
||||
type dispatchStores struct {
|
||||
*store.Store
|
||||
EdaStore *edastore.Store
|
||||
*pgstore.TaskDB
|
||||
EdaStore *postgres.EDA
|
||||
edaPool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func openDispatchTestStore(t *testing.T) *dispatchStores {
|
||||
t.Helper()
|
||||
s, err := store.Open(t.Context(), filepath.Join(t.TempDir(), "dispatch.db"))
|
||||
if err != nil {
|
||||
t.Fatalf("store.Open: %v", err)
|
||||
}
|
||||
s := pgstore.Open(t)
|
||||
t.Cleanup(func() { _ = s.Close() })
|
||||
return &dispatchStores{Store: s, EdaStore: edastore.OpenTest(t)}
|
||||
pool := pgstore.Pool(t)
|
||||
return &dispatchStores{TaskDB: s, EdaStore: postgres.NewEDA(pool, nil), edaPool: pool}
|
||||
}
|
||||
|
||||
// seedMapping inserts a mapping with the given fields and returns its id.
|
||||
@@ -327,7 +326,7 @@ func seedArmedBindingWithRepo(t *testing.T, s *dispatchStores, source, mappingID
|
||||
// maxEvents=0's "no cap" reading.
|
||||
func seedCapture(t *testing.T, s *dispatchStores, source string, authenticated bool, body string) {
|
||||
t.Helper()
|
||||
_, err := s.EdaStore.InsertCapture(t.Context(), store.CapturedEvent{
|
||||
_, err := s.EdaStore.InsertCapture(t.Context(), storecontract.CapturedEvent{
|
||||
Source: source,
|
||||
Body: body,
|
||||
Authenticated: authenticated,
|
||||
@@ -339,7 +338,7 @@ func seedCapture(t *testing.T, s *dispatchStores, source string, authenticated b
|
||||
}
|
||||
|
||||
// newDispatchDaemon builds a Daemon whose store-related handles all
|
||||
// point at the same *store.Store so dispatchBindings can resolve
|
||||
// point at the same *pgstore.TaskDB so dispatchBindings can resolve
|
||||
// captures through the dispatcher handles and mappings through
|
||||
// d.Mappings. Exactly one repo is configured so resolveBindingRepo's
|
||||
// single-repo fallback accepts the dispatch; with zero or many
|
||||
@@ -377,10 +376,9 @@ func assertDispatchRecorded(t *testing.T, s *dispatchStores, bindingID string, t
|
||||
t.Helper()
|
||||
var gotBindingID string
|
||||
var gotTaskID int64
|
||||
if err := s.EdaStore.App().DB().NewQuery(
|
||||
"SELECT binding, task_id FROM binding_dispatches WHERE binding = {:binding}").
|
||||
Bind(map[string]any{"binding": bindingID}).
|
||||
Row(&gotBindingID, &gotTaskID); err != nil {
|
||||
if err := s.edaPool.QueryRow(t.Context(),
|
||||
"SELECT binding, task_id FROM binding_dispatches WHERE binding = $1", bindingID).
|
||||
Scan(&gotBindingID, &gotTaskID); err != nil {
|
||||
t.Fatalf("binding_dispatches row missing: %v", err)
|
||||
}
|
||||
if gotBindingID != bindingID || gotTaskID != taskID {
|
||||
|
||||
@@ -11,7 +11,7 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workintake"
|
||||
"github.com/samcharles93/archie-core/internal/eventbus"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
"github.com/samcharles93/archie-core/internal/worktree"
|
||||
)
|
||||
|
||||
@@ -36,7 +36,7 @@ var _ eventbus.Message = (*fakeMessage)(nil)
|
||||
// not know must not be written to the store at all. Today it is enqueued and
|
||||
// only fails open later, when forgeFor/repoFor fall back to the root forge.
|
||||
func TestProcessNATSTaskRejectsUnresolvableIdentity(t *testing.T) {
|
||||
s := store.OpenTest(t)
|
||||
s := pgstore.Open(t)
|
||||
d := &Daemon{
|
||||
Store: s,
|
||||
Cfg: config.NewHolder(config.Config{}),
|
||||
@@ -110,7 +110,7 @@ func TestProcessParksTaskWhoseIdentityNoLongerResolves(t *testing.T) {
|
||||
// still has a runner but has been retired may not act, so its tasks park
|
||||
// rather than running under a credential the control plane has retired.
|
||||
func TestProcessParksRetiredIdentity(t *testing.T) {
|
||||
s := store.OpenTest(t)
|
||||
s := pgstore.Open(t)
|
||||
ctx := context.Background()
|
||||
log := slog.New(slog.DiscardHandler)
|
||||
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
package daemon
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgtest"
|
||||
)
|
||||
|
||||
func TestMain(m *testing.M) { os.Exit(pgtest.Main(m)) }
|
||||
@@ -10,7 +10,7 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/domain/eda/module"
|
||||
"github.com/samcharles93/archie-core/internal/domain/eda/playbook"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
)
|
||||
|
||||
// playbookStore loads a single playbook document from a temp directory, so
|
||||
@@ -42,7 +42,7 @@ func routableDefinitions() *workflowDefinitionsStub {
|
||||
}
|
||||
|
||||
// forgeTask enqueues a labelled forge-sourced task and returns its row.
|
||||
func forgeTask(t *testing.T, resources *store.Store, labels string) *workflow.Task {
|
||||
func forgeTask(t *testing.T, resources *pgstore.TaskDB, labels string) *workflow.Task {
|
||||
t.Helper()
|
||||
if _, err := resources.EnqueueIssue(t.Context(), "acme", "widget", 7, "title", "body", labels, ""); err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -60,7 +60,7 @@ func forgeTask(t *testing.T, resources *store.Store, labels string) *workflow.Ta
|
||||
// chosen for the same labels. Bypassing the coordinator pins "tdd" (the
|
||||
// default binding for kind bug) and fails this test.
|
||||
func TestPinWorkflowDefinitionPrefersMatchingPlaybook(t *testing.T) {
|
||||
resources := store.OpenTest(t)
|
||||
resources := pgstore.Open(t)
|
||||
defer resources.Close()
|
||||
task := forgeTask(t, resources, "bug")
|
||||
|
||||
@@ -95,7 +95,7 @@ actions:
|
||||
// an additional routing source, not a replacement. A non-matching playbook
|
||||
// set leaves the existing kind/label bindings in charge.
|
||||
func TestPinWorkflowDefinitionFallsBackWhenNoPlaybookMatches(t *testing.T) {
|
||||
resources := store.OpenTest(t)
|
||||
resources := pgstore.Open(t)
|
||||
defer resources.Close()
|
||||
task := forgeTask(t, resources, "bug")
|
||||
|
||||
@@ -125,7 +125,7 @@ actions:
|
||||
// Silently running the kind binding's choice instead would run the wrong
|
||||
// workflow under a rule the operator wrote.
|
||||
func TestPinWorkflowDefinitionPlaybookWorkflowMustExist(t *testing.T) {
|
||||
resources := store.OpenTest(t)
|
||||
resources := pgstore.Open(t)
|
||||
defer resources.Close()
|
||||
task := forgeTask(t, resources, "bug")
|
||||
|
||||
@@ -155,7 +155,7 @@ actions:
|
||||
// assignment is a decision already made about this task and must not be
|
||||
// re-routed by a playbook trigger that still matches its labels.
|
||||
func TestPinWorkflowDefinitionPreAssignedWorkflowBeatsPlaybook(t *testing.T) {
|
||||
resources := store.OpenTest(t)
|
||||
resources := pgstore.Open(t)
|
||||
defer resources.Close()
|
||||
task := forgeTask(t, resources, "bug")
|
||||
task.Workflow = "tdd"
|
||||
@@ -203,7 +203,7 @@ actions:
|
||||
{name: "condition false leaves the kind binding in charge", labels: "bug", want: "tdd"},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
resources := store.OpenTest(t)
|
||||
resources := pgstore.Open(t)
|
||||
defer resources.Close()
|
||||
task := forgeTask(t, resources, tc.labels)
|
||||
d := &Daemon{
|
||||
@@ -228,7 +228,7 @@ actions:
|
||||
// recognises still triggers a playbook, which is the only way an operator can
|
||||
// bind a workflow to their own taxonomy without a code change.
|
||||
func TestPinWorkflowDefinitionTriggersOnInstanceDefinedLabel(t *testing.T) {
|
||||
resources := store.OpenTest(t)
|
||||
resources := pgstore.Open(t)
|
||||
defer resources.Close()
|
||||
task := forgeTask(t, resources, "ops::security-review,needs-triage")
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/eda/playbook"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
)
|
||||
|
||||
// runRecorder is a playbook set that matches no workflow playbook and records
|
||||
@@ -50,7 +50,7 @@ func TestPinWorkflowDefinitionRunsActionPlaybooks(t *testing.T) {
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
resources := store.OpenTest(t)
|
||||
resources := pgstore.Open(t)
|
||||
defer resources.Close()
|
||||
task := forgeTask(t, resources, "bug")
|
||||
task.Workflow = tt.workflow
|
||||
|
||||
@@ -22,8 +22,8 @@ import (
|
||||
archiecontainer "github.com/samcharles93/archie-core/internal/container"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
agentnats "github.com/samcharles93/archie-core/internal/infrastructure/agenttransport/nats"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
"github.com/samcharles93/archie-core/internal/storage"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
"github.com/samcharles93/archie-core/internal/taskrun"
|
||||
"github.com/samcharles93/archie-core/internal/taskstate"
|
||||
"github.com/samcharles93/archie-core/internal/worktree"
|
||||
@@ -240,7 +240,7 @@ func TestCleanupTerminalTaskWorktreeWithCancelledContext(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel() // cancel context before calling cleanup
|
||||
|
||||
st := store.OpenTest(t)
|
||||
st := pgstore.Open(t)
|
||||
t.Cleanup(func() { _ = st.Close() })
|
||||
|
||||
trees := &worktree.Manager{WorkDir: t.TempDir()}
|
||||
@@ -409,7 +409,7 @@ func TestParkRunningTaskGuardedAndLogging(t *testing.T) {
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
s := store.OpenTest(t)
|
||||
s := pgstore.Open(t)
|
||||
t.Cleanup(func() { _ = s.Close() })
|
||||
|
||||
var buf logBuffer
|
||||
@@ -443,7 +443,7 @@ func TestParkRunningTaskGuardedAndLogging(t *testing.T) {
|
||||
}
|
||||
|
||||
if tt.closeStore {
|
||||
_ = s.Close()
|
||||
s.Pool.Close()
|
||||
}
|
||||
|
||||
d.parkRunningTask(callCtx, task.ID, "simulated park reason", taskstate.ParkTransient)
|
||||
@@ -494,7 +494,7 @@ func TestAcquireTaskContainerFailureParksTaskOnCancelledContext(t *testing.T) {
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
s := store.OpenTest(t)
|
||||
s := pgstore.Open(t)
|
||||
t.Cleanup(func() { _ = s.Close() })
|
||||
|
||||
d := &Daemon{
|
||||
|
||||
@@ -24,8 +24,8 @@ import (
|
||||
archiecontainer "github.com/samcharles93/archie-core/internal/container"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
agentnats "github.com/samcharles93/archie-core/internal/infrastructure/agenttransport/nats"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
"github.com/samcharles93/archie-core/internal/storage"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
"github.com/samcharles93/archie-core/internal/taskrun"
|
||||
"github.com/samcharles93/archie-core/internal/worktree"
|
||||
)
|
||||
@@ -148,7 +148,7 @@ func TestCleanupTerminalTaskWorktreeLifecycle(t *testing.T) {
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
st := store.OpenTest(t)
|
||||
st := pgstore.Open(t)
|
||||
t.Cleanup(func() { _ = st.Close() })
|
||||
|
||||
rootTrees := &worktree.Manager{WorkDir: t.TempDir()}
|
||||
|
||||
@@ -5,7 +5,7 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
)
|
||||
|
||||
type workflowDefinitionsStub struct {
|
||||
@@ -18,7 +18,7 @@ func (s *workflowDefinitionsStub) WorkflowDefinitions(context.Context) (workflow
|
||||
}
|
||||
|
||||
func TestWorkflowDefinitionPinSurvivesActiveOverride(t *testing.T) {
|
||||
resources := store.OpenTest(t)
|
||||
resources := pgstore.Open(t)
|
||||
defer resources.Close()
|
||||
task, err := resources.EnqueueChatTask(t.Context(), "acme", "widget", "custom", "", "custom", "operator")
|
||||
if err != nil {
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
package workflow
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgtest"
|
||||
)
|
||||
|
||||
func TestMain(m *testing.M) { os.Exit(pgtest.Main(m)) }
|
||||
@@ -4,20 +4,20 @@ import (
|
||||
"bytes"
|
||||
"context"
|
||||
"log/slog"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/agentexec"
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
)
|
||||
|
||||
// storeIntegrationRunner is a minimal agentexec.Runner stub, duplicated
|
||||
// here (rather than reused from the in-package tests) because this file
|
||||
// lives in the external workflow_test package: it needs the real
|
||||
// *store.Store as a workflow.Store, and the package under test now owns
|
||||
// *pgstore.TaskDB as a workflow.Store, and the package under test now owns
|
||||
// workflow.Task/Status/Source, which would otherwise cycle back through
|
||||
// internal/store's dependency on internal/domain/workflow.
|
||||
type storeIntegrationRunner struct {
|
||||
@@ -44,10 +44,7 @@ func (r *storeIntegrationRunner) Run(
|
||||
// and the store as park_reason, but never the log. A workflow that ends without
|
||||
// an outcome is the smallest way to reach that path.
|
||||
func TestRunRecordsAParkReasonInTheRunsOwnLog(t *testing.T) {
|
||||
st, err := store.Open(t.Context(), filepath.Join(t.TempDir(), "archie.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
st := pgstore.Open(t)
|
||||
t.Cleanup(func() {
|
||||
if err := st.Close(); err != nil {
|
||||
t.Errorf("close store: %v", err)
|
||||
@@ -82,10 +79,7 @@ func TestRunRecordsAParkReasonInTheRunsOwnLog(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestAgentStagePersistsReturnedNotes(t *testing.T) {
|
||||
st, err := store.Open(t.Context(), filepath.Join(t.TempDir(), "archie.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
st := pgstore.Open(t)
|
||||
t.Cleanup(func() {
|
||||
if err := st.Close(); err != nil {
|
||||
t.Errorf("close store: %v", err)
|
||||
@@ -119,10 +113,7 @@ func TestAgentStagePersistsReturnedNotes(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestRunLeavesInterruptedTaskForCrashRecovery(t *testing.T) {
|
||||
st, err := store.Open(t.Context(), filepath.Join(t.TempDir(), "archie.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
st := pgstore.Open(t)
|
||||
t.Cleanup(func() {
|
||||
if err := st.Close(); err != nil {
|
||||
t.Errorf("close store: %v", err)
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
package edastore
|
||||
// Package bindingcipher seals binding secrets at rest with AES-256-GCM under
|
||||
// a rotatable keyring.
|
||||
package bindingcipher
|
||||
|
||||
import (
|
||||
"crypto/aes"
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
package edastore
|
||||
package bindingcipher
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
@@ -121,110 +120,6 @@ func TestBindingCipherDerivesDistinctKeys(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// openWithCipher builds a store whose binding secrets are encrypted at rest.
|
||||
func openWithCipher(t *testing.T, cipher BindingCipher) *Store {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
s, err := Open(Config{
|
||||
DBPath: filepath.Join(dir, "eda.sqlite"),
|
||||
DataDir: filepath.Join(dir, "pb_data"),
|
||||
Cipher: cipher,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Open() error = %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = s.Close() })
|
||||
return s
|
||||
}
|
||||
|
||||
func sampleBinding() bindingInput {
|
||||
return bindingInput{Name: "n", Source: "sentry", Workflow: "implement", Secret: "supersecretvalue0123"}
|
||||
}
|
||||
|
||||
// TestBindingSecretIsEncryptedAtRest pins that the plaintext secret never
|
||||
// reaches the database file. Reading the column directly is the point: a
|
||||
// round-trip through the store would decrypt and prove nothing.
|
||||
func TestBindingSecretIsEncryptedAtRest(t *testing.T) {
|
||||
cipher, err := NewBindingCipher(testBindingKey, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("NewBindingCipher() error = %v", err)
|
||||
}
|
||||
s := openWithCipher(t, cipher)
|
||||
in := sampleBinding()
|
||||
id := insertBinding(t, s, in)
|
||||
|
||||
var stored string
|
||||
if err := s.App().DB().NewQuery("SELECT secret FROM " + CollBindings + " WHERE id = {:id}").
|
||||
Bind(map[string]any{"id": id}).Row(&stored); err != nil {
|
||||
t.Fatalf("read raw secret: %v", err)
|
||||
}
|
||||
if stored == in.Secret {
|
||||
t.Fatal("secret is stored as plaintext; it must be encrypted at rest")
|
||||
}
|
||||
if !strings.Contains(stored, ":") {
|
||||
t.Errorf("stored secret %q does not look like a cipher envelope", stored)
|
||||
}
|
||||
}
|
||||
|
||||
// TestBindingSecretDecryptsOnRead pins the other half: what was encrypted
|
||||
// comes back as the original plaintext.
|
||||
func TestBindingSecretDecryptsOnRead(t *testing.T) {
|
||||
cipher, _ := NewBindingCipher(testBindingKey, nil)
|
||||
s := openWithCipher(t, cipher)
|
||||
in := sampleBinding()
|
||||
id := insertBinding(t, s, in)
|
||||
|
||||
got, err := s.GetBinding(t.Context(), id)
|
||||
if err != nil {
|
||||
t.Fatalf("GetBinding() error = %v", err)
|
||||
}
|
||||
if got.Secret != in.Secret {
|
||||
t.Errorf("Secret = %q, want %q", got.Secret, in.Secret)
|
||||
}
|
||||
}
|
||||
|
||||
// TestNoCipherKeepsPlaintext pins the behaviour that predates encryption: a
|
||||
// deployment with no configured key still works, storing plaintext.
|
||||
func TestNoCipherKeepsPlaintext(t *testing.T) {
|
||||
s := openWithCipher(t, nil)
|
||||
in := sampleBinding()
|
||||
id := insertBinding(t, s, in)
|
||||
|
||||
var stored string
|
||||
if err := s.App().DB().NewQuery("SELECT secret FROM " + CollBindings + " WHERE id = {:id}").
|
||||
Bind(map[string]any{"id": id}).Row(&stored); err != nil {
|
||||
t.Fatalf("read raw secret: %v", err)
|
||||
}
|
||||
if stored != in.Secret {
|
||||
t.Errorf("stored secret = %q, want the plaintext %q with no cipher configured", stored, in.Secret)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRotatedKeyStillReadsOldRows pins key rotation: a secret written under
|
||||
// the previous key must stay readable once a new active key is installed,
|
||||
// otherwise a rotation silently bricks every armed binding.
|
||||
func TestRotatedKeyStillReadsOldRows(t *testing.T) {
|
||||
const oldKey = "fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210"
|
||||
oldCipher, _ := NewBindingCipher(oldKey, nil)
|
||||
s := openWithCipher(t, oldCipher)
|
||||
in := sampleBinding()
|
||||
id := insertBinding(t, s, in)
|
||||
|
||||
rotated, err := NewBindingCipher(testBindingKey, []string{oldKey})
|
||||
if err != nil {
|
||||
t.Fatalf("NewBindingCipher(rotated) error = %v", err)
|
||||
}
|
||||
s.cipher = rotated
|
||||
|
||||
got, err := s.GetBinding(t.Context(), id)
|
||||
if err != nil {
|
||||
t.Fatalf("GetBinding() after rotation error = %v", err)
|
||||
}
|
||||
if got.Secret != in.Secret {
|
||||
t.Errorf("Secret after rotation = %q, want %q: the previous key must still decrypt", got.Secret, in.Secret)
|
||||
}
|
||||
}
|
||||
|
||||
// tamperEnvelope flips one byte inside the ciphertext region so Decrypt must
|
||||
// fail authentication rather than return altered plaintext.
|
||||
func tamperEnvelope(t *testing.T, envelope string) string {
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
package captureintake
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgtest"
|
||||
)
|
||||
|
||||
func TestMain(m *testing.M) { os.Exit(pgtest.Main(m)) }
|
||||
@@ -14,9 +14,10 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/binding"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/edastore"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
"github.com/samcharles93/archie-core/internal/webhookguard"
|
||||
)
|
||||
|
||||
@@ -39,7 +40,7 @@ type testReceiver struct {
|
||||
*Receiver
|
||||
// store is the event-capture store the receiver writes through, kept so a
|
||||
// test asserts on persisted rows rather than on a mock's recollection.
|
||||
store *edastore.Store
|
||||
store *postgres.EDA
|
||||
}
|
||||
|
||||
// Handler serves the receiver's route the way its host process mounts it,
|
||||
@@ -60,7 +61,7 @@ func captureTestServerWithoutStore(t *testing.T) testReceiver {
|
||||
|
||||
func captureTestServer(t *testing.T) testReceiver {
|
||||
t.Helper()
|
||||
s := edastore.OpenTest(t)
|
||||
s := pgstore.EDA(t, nil)
|
||||
return testReceiver{
|
||||
Receiver: &Receiver{
|
||||
Log: slog.New(slog.DiscardHandler),
|
||||
@@ -131,7 +132,7 @@ func (s *stubBindingStore) RecordDispatch(
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *stubBindingStore) ListUndispatchedCaptures(_ context.Context, _ []string, _ int) ([]store.CapturedEvent, error) {
|
||||
func (s *stubBindingStore) ListUndispatchedCaptures(_ context.Context, _ []string, _ int) ([]storecontract.CapturedEvent, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
@@ -420,10 +421,10 @@ func TestHandleCaptureWithoutCapturesConfiguredIs503(t *testing.T) {
|
||||
// captureInsertErrorStore forces InsertCapture to fail so the handler's
|
||||
// error path is exercised without relying on a real storage failure.
|
||||
type captureInsertErrorStore struct {
|
||||
store.CaptureStore
|
||||
storecontract.CaptureStore
|
||||
}
|
||||
|
||||
func (captureInsertErrorStore) InsertCapture(context.Context, store.CapturedEvent, time.Duration, int) (string, error) {
|
||||
func (captureInsertErrorStore) InsertCapture(context.Context, storecontract.CapturedEvent, time.Duration, int) (string, error) {
|
||||
return "", errors.New("boom")
|
||||
}
|
||||
|
||||
|
||||
@@ -15,9 +15,9 @@ import (
|
||||
"google.golang.org/grpc/test/bufconn"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/domain/taskactions"
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
"github.com/samcharles93/archie-core/internal/taskstate"
|
||||
)
|
||||
|
||||
@@ -213,7 +213,7 @@ func TestTaskActionErrorsKeepTheirSentinelOverGRPC(t *testing.T) {
|
||||
}{
|
||||
{name: "not found", err: fmt.Errorf("task 7: %w", taskactions.ErrNotFound)},
|
||||
{name: "conflict", err: fmt.Errorf("%w: action \"approve\" is not available while task is parked", taskactions.ErrConflict)},
|
||||
{name: "stale transition", err: fmt.Errorf("stop task 7: %w", store.ErrStaleTransition)},
|
||||
{name: "stale transition", err: fmt.Errorf("stop task 7: %w", storecontract.ErrStaleTransition)},
|
||||
{name: "unavailable", err: taskactions.ErrUnavailable},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
// Package legacyfixture writes the legacy SQLite files an existing install
|
||||
// holds, for tests of the one-time import and the boot gate that requires it.
|
||||
package legacyfixture
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
_ "modernc.org/sqlite"
|
||||
)
|
||||
|
||||
// StateStoreDDL, EDADDL and GatewayDDL apply the legacy schemas as their production openers leave
|
||||
// them, columns added by ALTER TABLE included, with values in the layouts the
|
||||
// production writers used.
|
||||
const StateStoreDDL = `
|
||||
CREATE TABLE tasks (id INTEGER PRIMARY KEY AUTOINCREMENT, owner TEXT NOT NULL, repo TEXT NOT NULL,
|
||||
issue_number INTEGER NOT NULL, title TEXT DEFAULT '', body TEXT DEFAULT '', labels TEXT DEFAULT '',
|
||||
status TEXT DEFAULT 'queued', workflow TEXT DEFAULT '', stage TEXT DEFAULT '', branch TEXT DEFAULT '',
|
||||
plan TEXT DEFAULT '', notes TEXT DEFAULT '', pr_number INTEGER DEFAULT 0, tokens_used INTEGER DEFAULT 0,
|
||||
iterations INTEGER DEFAULT 0, attempt INTEGER DEFAULT 0, park_reason TEXT DEFAULT '',
|
||||
watch_comment_id INTEGER DEFAULT 0, park_class TEXT DEFAULT 'needs_human', remediation_rounds INTEGER DEFAULT 0,
|
||||
retry_count INTEGER DEFAULT 0, source TEXT DEFAULT 'forge', identity TEXT DEFAULT '', binding_id TEXT DEFAULT '',
|
||||
binding_version INTEGER DEFAULT 0, review_payload TEXT DEFAULT '', workflow_definition_version INTEGER DEFAULT 0,
|
||||
workflow_definition_digest TEXT DEFAULT '', workflow_definition_yaml TEXT DEFAULT '',
|
||||
created_at TEXT DEFAULT (datetime('now')), updated_at TEXT DEFAULT (datetime('now')));
|
||||
ALTER TABLE tasks ADD COLUMN review_cursor INTEGER NOT NULL DEFAULT 0;
|
||||
CREATE TABLE transitions (id INTEGER PRIMARY KEY AUTOINCREMENT, task_id INTEGER NOT NULL,
|
||||
at TEXT DEFAULT (datetime('now')), from_status TEXT NOT NULL, to_status TEXT NOT NULL, detail TEXT DEFAULT '');
|
||||
CREATE TABLE events (id INTEGER PRIMARY KEY AUTOINCREMENT, at TEXT NOT NULL, kind TEXT NOT NULL,
|
||||
task_id INTEGER DEFAULT 0, repo TEXT DEFAULT '', issue INTEGER DEFAULT 0, workflow TEXT DEFAULT '',
|
||||
stage TEXT DEFAULT '', attempt INTEGER DEFAULT 0, actor_id TEXT DEFAULT '', actor_kind TEXT DEFAULT '',
|
||||
principal_id TEXT DEFAULT '', detail TEXT DEFAULT '', data TEXT DEFAULT '{}');
|
||||
CREATE TABLE resources (kind TEXT PRIMARY KEY, value BLOB NOT NULL, version INTEGER NOT NULL, updated_at TEXT NOT NULL);
|
||||
CREATE TABLE resource_history (id INTEGER PRIMARY KEY AUTOINCREMENT, kind TEXT NOT NULL, value BLOB NOT NULL,
|
||||
version INTEGER NOT NULL, actor TEXT NOT NULL, source TEXT NOT NULL, request_id TEXT NOT NULL,
|
||||
expected_version INTEGER NOT NULL, current_version INTEGER NOT NULL, at TEXT NOT NULL);
|
||||
CREATE TABLE channel_status (id TEXT PRIMARY KEY, name TEXT DEFAULT '', state TEXT DEFAULT '', detail TEXT DEFAULT '',
|
||||
configured INTEGER NOT NULL DEFAULT 0, reload_supported INTEGER NOT NULL DEFAULT 0, observed_at TEXT NOT NULL);
|
||||
CREATE TABLE apply_status (process TEXT NOT NULL, kind TEXT NOT NULL, applied_version INTEGER DEFAULT 0,
|
||||
error TEXT DEFAULT '', reported_at TEXT NOT NULL, PRIMARY KEY (process, kind));
|
||||
CREATE TABLE config_snapshot (id INTEGER PRIMARY KEY CHECK (id = 1), schema TEXT DEFAULT '', document TEXT DEFAULT '',
|
||||
published_at TEXT NOT NULL);
|
||||
CREATE TABLE identities (id TEXT PRIMARY KEY, kind TEXT NOT NULL, display_name TEXT NOT NULL, lifecycle TEXT NOT NULL,
|
||||
version INTEGER NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL);
|
||||
CREATE TABLE identity_aliases (alias TEXT PRIMARY KEY COLLATE NOCASE, identity_id TEXT NOT NULL REFERENCES identities(id));
|
||||
CREATE TABLE identity_events (id INTEGER PRIMARY KEY AUTOINCREMENT, identity_id TEXT NOT NULL, event_type TEXT NOT NULL,
|
||||
from_lifecycle TEXT NOT NULL, to_lifecycle TEXT NOT NULL, display_name TEXT NOT NULL, actor_id TEXT NOT NULL,
|
||||
source TEXT NOT NULL, request_id TEXT NOT NULL UNIQUE, at TEXT NOT NULL);
|
||||
CREATE TABLE identity_subjects (issuer TEXT NOT NULL, subject TEXT NOT NULL,
|
||||
identity_id TEXT NOT NULL REFERENCES identities(id), bound_at TEXT NOT NULL, PRIMARY KEY (issuer, subject));
|
||||
|
||||
INSERT INTO tasks (id, owner, repo, issue_number, review_cursor, created_at, updated_at) VALUES
|
||||
(1, 'o', 'r', 7, 3, '2026-01-01 00:00:00', '2026-01-01 00:00:01'),
|
||||
(4, 'o', 'r', 1000000000000000, 0, '2026-01-02 00:00:00', '2026-01-02 00:00:00'),
|
||||
(9, 'o', 'r', 8, 0, '2026-01-02 00:00:00', '2026-01-02 00:00:00');
|
||||
DELETE FROM tasks WHERE id = 9;
|
||||
INSERT INTO transitions (task_id, at, from_status, to_status) VALUES (1, '2026-01-01 00:00:00', 'queued', 'running');
|
||||
INSERT INTO events (id, at, kind, data) VALUES
|
||||
(1, '2026-01-01T00:00:00.000000100Z', 'a', 'null'),
|
||||
(2, '2026-01-01T00:00:01.000000000Z', 'b', '{"k":1}'),
|
||||
(5, '2026-01-01T00:00:00.500000000Z', 'c', '{}');
|
||||
INSERT INTO resources VALUES ('config', X'00ff10', 2, '2026-01-01T00:00:00.123456789Z');
|
||||
INSERT INTO resource_history (kind, value, version, actor, source, request_id, expected_version, current_version, at)
|
||||
VALUES ('config', X'00ff10', 2, 'sam', 'ui', 'req-1', 1, 1, '2026-01-01T00:00:00Z');
|
||||
INSERT INTO channel_status VALUES ('tg', 'Telegram', 'up', '', 1, 0, '2026-01-01T00:00:00Z');
|
||||
INSERT INTO apply_status VALUES ('daemon', 'config', 2, '', '2026-01-01T00:00:00Z');
|
||||
INSERT INTO config_snapshot VALUES (1, 's', '{}', '2026-01-01T00:00:00Z');
|
||||
INSERT INTO identities VALUES ('id-1', 'agent', 'Archie', 'active', 1, '2026-01-01T00:00:00Z', '2026-01-01T00:00:00Z');
|
||||
INSERT INTO identity_aliases VALUES ('archie', 'id-1');
|
||||
INSERT INTO identity_events (identity_id, event_type, from_lifecycle, to_lifecycle, display_name, actor_id, source, request_id, at)
|
||||
VALUES ('id-1', 'created', '', 'active', 'Archie', 'sam', 'boot', 'rq-1', '2026-01-01T00:00:00Z');
|
||||
INSERT INTO identity_subjects VALUES ('https://issuer', 'sub-1', 'id-1', '2026-01-01T00:00:00Z');
|
||||
`
|
||||
|
||||
// Secret is an encrypted binding secret envelope; it must arrive unchanged.
|
||||
const Secret = "arcie-binding:v1:0123456789abcdef:AbC-_dEf012"
|
||||
|
||||
const EDADDL = `
|
||||
CREATE TABLE captures (id TEXT PRIMARY KEY NOT NULL, authenticated BOOLEAN DEFAULT FALSE NOT NULL,
|
||||
body TEXT DEFAULT '' NOT NULL, content_type TEXT DEFAULT '' NOT NULL, headers JSON DEFAULT NULL,
|
||||
received_at TEXT DEFAULT '' NOT NULL, remote_addr TEXT DEFAULT '' NOT NULL, source TEXT DEFAULT '' NOT NULL);
|
||||
CREATE TABLE mappings (id TEXT PRIMARY KEY NOT NULL, created_at TEXT DEFAULT '' NOT NULL, fields JSON DEFAULT NULL,
|
||||
name TEXT DEFAULT '' NOT NULL, source_hint TEXT DEFAULT '' NOT NULL, updated_at TEXT DEFAULT '' NOT NULL);
|
||||
CREATE TABLE bindings (id TEXT PRIMARY KEY NOT NULL, created_at TEXT DEFAULT '' NOT NULL, mapping TEXT DEFAULT '' NOT NULL,
|
||||
name TEXT DEFAULT '' NOT NULL, owner TEXT DEFAULT '' NOT NULL, repo TEXT DEFAULT '' NOT NULL,
|
||||
secret TEXT DEFAULT '' NOT NULL, source TEXT DEFAULT '' NOT NULL, status TEXT DEFAULT '' NOT NULL,
|
||||
updated_at TEXT DEFAULT '' NOT NULL, version NUMERIC DEFAULT 0 NOT NULL, workflow TEXT DEFAULT '' NOT NULL);
|
||||
CREATE TABLE binding_dispatches (id TEXT PRIMARY KEY NOT NULL, binding TEXT DEFAULT '' NOT NULL,
|
||||
binding_version NUMERIC DEFAULT 0 NOT NULL, capture TEXT DEFAULT '' NOT NULL, dispatched_at TEXT DEFAULT '' NOT NULL,
|
||||
task_id NUMERIC DEFAULT 0 NOT NULL);
|
||||
CREATE UNIQUE INDEX idx_binding_dispatch_once ON binding_dispatches (binding, capture);
|
||||
CREATE TABLE playbook_dispatches (id TEXT PRIMARY KEY NOT NULL, action_id TEXT DEFAULT '' NOT NULL,
|
||||
dispatched_at TEXT DEFAULT '' NOT NULL, event_id TEXT DEFAULT '' NOT NULL, playbook_id TEXT DEFAULT '' NOT NULL,
|
||||
playbook_version TEXT DEFAULT '' NOT NULL);
|
||||
CREATE TABLE tool_calls (id TEXT PRIMARY KEY NOT NULL, args JSON DEFAULT NULL, attempt NUMERIC DEFAULT 0 NOT NULL,
|
||||
called_at TEXT DEFAULT '' NOT NULL, duration_ms NUMERIC DEFAULT 0 NOT NULL, error TEXT DEFAULT '' NOT NULL,
|
||||
result JSON DEFAULT NULL, task_id NUMERIC DEFAULT 0 NOT NULL, tool TEXT DEFAULT '' NOT NULL);
|
||||
|
||||
INSERT INTO captures VALUES ('rcap1', 1, '{}', 'application/json', '{"x":["1"]}', '2026-01-01T00:00:00.000000000Z', '127.0.0.1', 'gh');
|
||||
INSERT INTO captures VALUES ('rcap2', 0, '', '', NULL, '2026-01-01T00:00:01.000000000Z', '', 'gh');
|
||||
INSERT INTO mappings VALUES ('rmap1', '2026-01-01 00:00:00.000Z', '[]', 'm', 'gh', '2026-01-01 00:00:00.000Z');
|
||||
INSERT INTO bindings VALUES ('rbind1', '2026-01-01 00:00:00.000Z', 'rmap1', 'b', 'o', 'r', '` + Secret + `', 'gh', 'armed', '2026-01-01 00:00:00.000Z', 1, 'implement');
|
||||
INSERT INTO binding_dispatches VALUES ('rdisp1', 'rbind1', 1, 'rcap1', '2026-01-01 00:00:00.000Z', 4);
|
||||
INSERT INTO playbook_dispatches VALUES ('rpb1', 'act', '2026-01-01 00:00:00.000Z', 'ev', 'pb', 'v1');
|
||||
INSERT INTO tool_calls VALUES ('rtool1', NULL, 1, '2026-01-01 00:00:00.000Z', 12, '', '"exit 0"', 4, 'bash');
|
||||
`
|
||||
|
||||
const GatewayDDL = `
|
||||
CREATE TABLE sessions (session_id TEXT PRIMARY KEY, platform TEXT NOT NULL DEFAULT '', bot_user TEXT NOT NULL DEFAULT '',
|
||||
channel_id TEXT NOT NULL DEFAULT '', thread_id TEXT NOT NULL DEFAULT '', title TEXT NOT NULL DEFAULT '',
|
||||
parent_session_id TEXT NOT NULL DEFAULT '', branch_name TEXT NOT NULL DEFAULT '',
|
||||
created_at INTEGER NOT NULL DEFAULT 0, last_active_at INTEGER NOT NULL DEFAULT 0);
|
||||
CREATE TABLE messages (id INTEGER PRIMARY KEY AUTOINCREMENT, message_id TEXT NOT NULL, session_id TEXT NOT NULL,
|
||||
source_id TEXT NOT NULL DEFAULT '', sender TEXT NOT NULL DEFAULT '', text TEXT NOT NULL DEFAULT '', ts INTEGER NOT NULL,
|
||||
UNIQUE(session_id, message_id));
|
||||
ALTER TABLE messages ADD COLUMN role TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE messages ADD COLUMN sender_id TEXT NOT NULL DEFAULT '';
|
||||
CREATE VIRTUAL TABLE messages_fts USING fts5(sender, text, content='messages', content_rowid='id');
|
||||
CREATE TRIGGER messages_ai AFTER INSERT ON messages BEGIN
|
||||
INSERT INTO messages_fts(rowid, sender, text) VALUES (new.id, new.sender, new.text);
|
||||
END;
|
||||
CREATE TABLE turns (turn_id TEXT PRIMARY KEY, session_id TEXT NOT NULL, source_id TEXT NOT NULL DEFAULT '',
|
||||
status TEXT NOT NULL, attempt INTEGER NOT NULL DEFAULT 0, owner_id TEXT NOT NULL DEFAULT '',
|
||||
input_message_id TEXT NOT NULL DEFAULT '', assistant_message_id TEXT NOT NULL DEFAULT '',
|
||||
partial_text TEXT NOT NULL DEFAULT '', response_text TEXT NOT NULL DEFAULT '', tool_calls TEXT NOT NULL DEFAULT '[]',
|
||||
error TEXT NOT NULL DEFAULT '', created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL);
|
||||
|
||||
INSERT INTO sessions VALUES ('s1', 'telegram', 'bot', 'c1', '', 'Chat', '', '', 1000, 2000);
|
||||
INSERT INTO messages (message_id, session_id, sender, text, ts, role) VALUES ('m1', 's1', 'sam', 'hello there', 1000, 'user');
|
||||
INSERT INTO messages (message_id, session_id, sender, text, ts, role) VALUES ('m2', 's1', 'archie', 'hi', 1001, 'assistant');
|
||||
INSERT INTO turns VALUES ('t1', 's1', '', 'done', 1, '', 'm1', 'm2', '', 'hi', '[]', '', 1000, 1001);
|
||||
`
|
||||
|
||||
// Install writes the three legacy files the configured db_path names in dir
|
||||
// and returns their paths.
|
||||
func Install(t testing.TB, dbPath string) (stateStore, eda, gateway string) {
|
||||
t.Helper()
|
||||
stateStore, eda, gateway = dbPath+"-tasks.sqlite", dbPath+"-eda.sqlite", dbPath+"-conversations.sqlite"
|
||||
Exec(t, stateStore, StateStoreDDL)
|
||||
Exec(t, eda, EDADDL)
|
||||
Exec(t, gateway, GatewayDDL)
|
||||
return stateStore, eda, gateway
|
||||
}
|
||||
|
||||
// Exec runs stmt against the SQLite file at path, creating it if absent.
|
||||
func Exec(t testing.TB, path, stmt string) {
|
||||
t.Helper()
|
||||
db, err := sql.Open("sqlite", "file:"+path)
|
||||
if err != nil {
|
||||
t.Fatalf("open fixture: %v", err)
|
||||
}
|
||||
defer func() { _ = db.Close() }()
|
||||
if _, err := db.ExecContext(t.Context(), stmt); err != nil {
|
||||
t.Fatalf("fixture %s: %v", filepath.Base(path), err)
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,6 @@ package legacyimport
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
@@ -11,175 +10,34 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
_ "modernc.org/sqlite"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/legacyimport/legacyfixture"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgtest"
|
||||
)
|
||||
|
||||
func TestMain(m *testing.M) { os.Exit(pgtest.Main(m)) }
|
||||
|
||||
// The fixtures apply the legacy schemas as their production openers leave
|
||||
// them, columns added by ALTER TABLE included, with values in the layouts the
|
||||
// production writers used.
|
||||
const stateStoreDDL = `
|
||||
CREATE TABLE tasks (id INTEGER PRIMARY KEY AUTOINCREMENT, owner TEXT NOT NULL, repo TEXT NOT NULL,
|
||||
issue_number INTEGER NOT NULL, title TEXT DEFAULT '', body TEXT DEFAULT '', labels TEXT DEFAULT '',
|
||||
status TEXT DEFAULT 'queued', workflow TEXT DEFAULT '', stage TEXT DEFAULT '', branch TEXT DEFAULT '',
|
||||
plan TEXT DEFAULT '', notes TEXT DEFAULT '', pr_number INTEGER DEFAULT 0, tokens_used INTEGER DEFAULT 0,
|
||||
iterations INTEGER DEFAULT 0, attempt INTEGER DEFAULT 0, park_reason TEXT DEFAULT '',
|
||||
watch_comment_id INTEGER DEFAULT 0, park_class TEXT DEFAULT 'needs_human', remediation_rounds INTEGER DEFAULT 0,
|
||||
retry_count INTEGER DEFAULT 0, source TEXT DEFAULT 'forge', identity TEXT DEFAULT '', binding_id TEXT DEFAULT '',
|
||||
binding_version INTEGER DEFAULT 0, review_payload TEXT DEFAULT '', workflow_definition_version INTEGER DEFAULT 0,
|
||||
workflow_definition_digest TEXT DEFAULT '', workflow_definition_yaml TEXT DEFAULT '',
|
||||
created_at TEXT DEFAULT (datetime('now')), updated_at TEXT DEFAULT (datetime('now')));
|
||||
ALTER TABLE tasks ADD COLUMN review_cursor INTEGER NOT NULL DEFAULT 0;
|
||||
CREATE TABLE transitions (id INTEGER PRIMARY KEY AUTOINCREMENT, task_id INTEGER NOT NULL,
|
||||
at TEXT DEFAULT (datetime('now')), from_status TEXT NOT NULL, to_status TEXT NOT NULL, detail TEXT DEFAULT '');
|
||||
CREATE TABLE events (id INTEGER PRIMARY KEY AUTOINCREMENT, at TEXT NOT NULL, kind TEXT NOT NULL,
|
||||
task_id INTEGER DEFAULT 0, repo TEXT DEFAULT '', issue INTEGER DEFAULT 0, workflow TEXT DEFAULT '',
|
||||
stage TEXT DEFAULT '', attempt INTEGER DEFAULT 0, actor_id TEXT DEFAULT '', actor_kind TEXT DEFAULT '',
|
||||
principal_id TEXT DEFAULT '', detail TEXT DEFAULT '', data TEXT DEFAULT '{}');
|
||||
CREATE TABLE resources (kind TEXT PRIMARY KEY, value BLOB NOT NULL, version INTEGER NOT NULL, updated_at TEXT NOT NULL);
|
||||
CREATE TABLE resource_history (id INTEGER PRIMARY KEY AUTOINCREMENT, kind TEXT NOT NULL, value BLOB NOT NULL,
|
||||
version INTEGER NOT NULL, actor TEXT NOT NULL, source TEXT NOT NULL, request_id TEXT NOT NULL,
|
||||
expected_version INTEGER NOT NULL, current_version INTEGER NOT NULL, at TEXT NOT NULL);
|
||||
CREATE TABLE channel_status (id TEXT PRIMARY KEY, name TEXT DEFAULT '', state TEXT DEFAULT '', detail TEXT DEFAULT '',
|
||||
configured INTEGER NOT NULL DEFAULT 0, reload_supported INTEGER NOT NULL DEFAULT 0, observed_at TEXT NOT NULL);
|
||||
CREATE TABLE apply_status (process TEXT NOT NULL, kind TEXT NOT NULL, applied_version INTEGER DEFAULT 0,
|
||||
error TEXT DEFAULT '', reported_at TEXT NOT NULL, PRIMARY KEY (process, kind));
|
||||
CREATE TABLE config_snapshot (id INTEGER PRIMARY KEY CHECK (id = 1), schema TEXT DEFAULT '', document TEXT DEFAULT '',
|
||||
published_at TEXT NOT NULL);
|
||||
CREATE TABLE identities (id TEXT PRIMARY KEY, kind TEXT NOT NULL, display_name TEXT NOT NULL, lifecycle TEXT NOT NULL,
|
||||
version INTEGER NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL);
|
||||
CREATE TABLE identity_aliases (alias TEXT PRIMARY KEY COLLATE NOCASE, identity_id TEXT NOT NULL REFERENCES identities(id));
|
||||
CREATE TABLE identity_events (id INTEGER PRIMARY KEY AUTOINCREMENT, identity_id TEXT NOT NULL, event_type TEXT NOT NULL,
|
||||
from_lifecycle TEXT NOT NULL, to_lifecycle TEXT NOT NULL, display_name TEXT NOT NULL, actor_id TEXT NOT NULL,
|
||||
source TEXT NOT NULL, request_id TEXT NOT NULL UNIQUE, at TEXT NOT NULL);
|
||||
CREATE TABLE identity_subjects (issuer TEXT NOT NULL, subject TEXT NOT NULL,
|
||||
identity_id TEXT NOT NULL REFERENCES identities(id), bound_at TEXT NOT NULL, PRIMARY KEY (issuer, subject));
|
||||
|
||||
INSERT INTO tasks (id, owner, repo, issue_number, review_cursor, created_at, updated_at) VALUES
|
||||
(1, 'o', 'r', 7, 3, '2026-01-01 00:00:00', '2026-01-01 00:00:01'),
|
||||
(4, 'o', 'r', 1000000000000000, 0, '2026-01-02 00:00:00', '2026-01-02 00:00:00'),
|
||||
(9, 'o', 'r', 8, 0, '2026-01-02 00:00:00', '2026-01-02 00:00:00');
|
||||
DELETE FROM tasks WHERE id = 9;
|
||||
INSERT INTO transitions (task_id, at, from_status, to_status) VALUES (1, '2026-01-01 00:00:00', 'queued', 'running');
|
||||
INSERT INTO events (id, at, kind, data) VALUES
|
||||
(1, '2026-01-01T00:00:00.000000100Z', 'a', 'null'),
|
||||
(2, '2026-01-01T00:00:01.000000000Z', 'b', '{"k":1}'),
|
||||
(5, '2026-01-01T00:00:00.500000000Z', 'c', '{}');
|
||||
INSERT INTO resources VALUES ('config', X'00ff10', 2, '2026-01-01T00:00:00.123456789Z');
|
||||
INSERT INTO resource_history (kind, value, version, actor, source, request_id, expected_version, current_version, at)
|
||||
VALUES ('config', X'00ff10', 2, 'sam', 'ui', 'req-1', 1, 1, '2026-01-01T00:00:00Z');
|
||||
INSERT INTO channel_status VALUES ('tg', 'Telegram', 'up', '', 1, 0, '2026-01-01T00:00:00Z');
|
||||
INSERT INTO apply_status VALUES ('daemon', 'config', 2, '', '2026-01-01T00:00:00Z');
|
||||
INSERT INTO config_snapshot VALUES (1, 's', '{}', '2026-01-01T00:00:00Z');
|
||||
INSERT INTO identities VALUES ('id-1', 'agent', 'Archie', 'active', 1, '2026-01-01T00:00:00Z', '2026-01-01T00:00:00Z');
|
||||
INSERT INTO identity_aliases VALUES ('archie', 'id-1');
|
||||
INSERT INTO identity_events (identity_id, event_type, from_lifecycle, to_lifecycle, display_name, actor_id, source, request_id, at)
|
||||
VALUES ('id-1', 'created', '', 'active', 'Archie', 'sam', 'boot', 'rq-1', '2026-01-01T00:00:00Z');
|
||||
INSERT INTO identity_subjects VALUES ('https://issuer', 'sub-1', 'id-1', '2026-01-01T00:00:00Z');
|
||||
`
|
||||
|
||||
// secret is an encrypted binding secret envelope; it must arrive unchanged.
|
||||
const secret = "arcie-binding:v1:0123456789abcdef:AbC-_dEf012"
|
||||
|
||||
const edaDDL = `
|
||||
CREATE TABLE captures (id TEXT PRIMARY KEY NOT NULL, authenticated BOOLEAN DEFAULT FALSE NOT NULL,
|
||||
body TEXT DEFAULT '' NOT NULL, content_type TEXT DEFAULT '' NOT NULL, headers JSON DEFAULT NULL,
|
||||
received_at TEXT DEFAULT '' NOT NULL, remote_addr TEXT DEFAULT '' NOT NULL, source TEXT DEFAULT '' NOT NULL);
|
||||
CREATE TABLE mappings (id TEXT PRIMARY KEY NOT NULL, created_at TEXT DEFAULT '' NOT NULL, fields JSON DEFAULT NULL,
|
||||
name TEXT DEFAULT '' NOT NULL, source_hint TEXT DEFAULT '' NOT NULL, updated_at TEXT DEFAULT '' NOT NULL);
|
||||
CREATE TABLE bindings (id TEXT PRIMARY KEY NOT NULL, created_at TEXT DEFAULT '' NOT NULL, mapping TEXT DEFAULT '' NOT NULL,
|
||||
name TEXT DEFAULT '' NOT NULL, owner TEXT DEFAULT '' NOT NULL, repo TEXT DEFAULT '' NOT NULL,
|
||||
secret TEXT DEFAULT '' NOT NULL, source TEXT DEFAULT '' NOT NULL, status TEXT DEFAULT '' NOT NULL,
|
||||
updated_at TEXT DEFAULT '' NOT NULL, version NUMERIC DEFAULT 0 NOT NULL, workflow TEXT DEFAULT '' NOT NULL);
|
||||
CREATE TABLE binding_dispatches (id TEXT PRIMARY KEY NOT NULL, binding TEXT DEFAULT '' NOT NULL,
|
||||
binding_version NUMERIC DEFAULT 0 NOT NULL, capture TEXT DEFAULT '' NOT NULL, dispatched_at TEXT DEFAULT '' NOT NULL,
|
||||
task_id NUMERIC DEFAULT 0 NOT NULL);
|
||||
CREATE UNIQUE INDEX idx_binding_dispatch_once ON binding_dispatches (binding, capture);
|
||||
CREATE TABLE playbook_dispatches (id TEXT PRIMARY KEY NOT NULL, action_id TEXT DEFAULT '' NOT NULL,
|
||||
dispatched_at TEXT DEFAULT '' NOT NULL, event_id TEXT DEFAULT '' NOT NULL, playbook_id TEXT DEFAULT '' NOT NULL,
|
||||
playbook_version TEXT DEFAULT '' NOT NULL);
|
||||
CREATE TABLE tool_calls (id TEXT PRIMARY KEY NOT NULL, args JSON DEFAULT NULL, attempt NUMERIC DEFAULT 0 NOT NULL,
|
||||
called_at TEXT DEFAULT '' NOT NULL, duration_ms NUMERIC DEFAULT 0 NOT NULL, error TEXT DEFAULT '' NOT NULL,
|
||||
result JSON DEFAULT NULL, task_id NUMERIC DEFAULT 0 NOT NULL, tool TEXT DEFAULT '' NOT NULL);
|
||||
|
||||
INSERT INTO captures VALUES ('rcap1', 1, '{}', 'application/json', '{"x":["1"]}', '2026-01-01T00:00:00.000000000Z', '127.0.0.1', 'gh');
|
||||
INSERT INTO captures VALUES ('rcap2', 0, '', '', NULL, '2026-01-01T00:00:01.000000000Z', '', 'gh');
|
||||
INSERT INTO mappings VALUES ('rmap1', '2026-01-01 00:00:00.000Z', '[]', 'm', 'gh', '2026-01-01 00:00:00.000Z');
|
||||
INSERT INTO bindings VALUES ('rbind1', '2026-01-01 00:00:00.000Z', 'rmap1', 'b', 'o', 'r', '` + secret + `', 'gh', 'armed', '2026-01-01 00:00:00.000Z', 1, 'implement');
|
||||
INSERT INTO binding_dispatches VALUES ('rdisp1', 'rbind1', 1, 'rcap1', '2026-01-01 00:00:00.000Z', 4);
|
||||
INSERT INTO playbook_dispatches VALUES ('rpb1', 'act', '2026-01-01 00:00:00.000Z', 'ev', 'pb', 'v1');
|
||||
INSERT INTO tool_calls VALUES ('rtool1', NULL, 1, '2026-01-01 00:00:00.000Z', 12, '', '"exit 0"', 4, 'bash');
|
||||
`
|
||||
|
||||
const gatewayDDL = `
|
||||
CREATE TABLE sessions (session_id TEXT PRIMARY KEY, platform TEXT NOT NULL DEFAULT '', bot_user TEXT NOT NULL DEFAULT '',
|
||||
channel_id TEXT NOT NULL DEFAULT '', thread_id TEXT NOT NULL DEFAULT '', title TEXT NOT NULL DEFAULT '',
|
||||
parent_session_id TEXT NOT NULL DEFAULT '', branch_name TEXT NOT NULL DEFAULT '',
|
||||
created_at INTEGER NOT NULL DEFAULT 0, last_active_at INTEGER NOT NULL DEFAULT 0);
|
||||
CREATE TABLE messages (id INTEGER PRIMARY KEY AUTOINCREMENT, message_id TEXT NOT NULL, session_id TEXT NOT NULL,
|
||||
source_id TEXT NOT NULL DEFAULT '', sender TEXT NOT NULL DEFAULT '', text TEXT NOT NULL DEFAULT '', ts INTEGER NOT NULL,
|
||||
UNIQUE(session_id, message_id));
|
||||
ALTER TABLE messages ADD COLUMN role TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE messages ADD COLUMN sender_id TEXT NOT NULL DEFAULT '';
|
||||
CREATE VIRTUAL TABLE messages_fts USING fts5(sender, text, content='messages', content_rowid='id');
|
||||
CREATE TRIGGER messages_ai AFTER INSERT ON messages BEGIN
|
||||
INSERT INTO messages_fts(rowid, sender, text) VALUES (new.id, new.sender, new.text);
|
||||
END;
|
||||
CREATE TABLE turns (turn_id TEXT PRIMARY KEY, session_id TEXT NOT NULL, source_id TEXT NOT NULL DEFAULT '',
|
||||
status TEXT NOT NULL, attempt INTEGER NOT NULL DEFAULT 0, owner_id TEXT NOT NULL DEFAULT '',
|
||||
input_message_id TEXT NOT NULL DEFAULT '', assistant_message_id TEXT NOT NULL DEFAULT '',
|
||||
partial_text TEXT NOT NULL DEFAULT '', response_text TEXT NOT NULL DEFAULT '', tool_calls TEXT NOT NULL DEFAULT '[]',
|
||||
error TEXT NOT NULL DEFAULT '', created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL);
|
||||
|
||||
INSERT INTO sessions VALUES ('s1', 'telegram', 'bot', 'c1', '', 'Chat', '', '', 1000, 2000);
|
||||
INSERT INTO messages (message_id, session_id, sender, text, ts, role) VALUES ('m1', 's1', 'sam', 'hello there', 1000, 'user');
|
||||
INSERT INTO messages (message_id, session_id, sender, text, ts, role) VALUES ('m2', 's1', 'archie', 'hi', 1001, 'assistant');
|
||||
INSERT INTO turns VALUES ('t1', 's1', '', 'done', 1, '', 'm1', 'm2', '', 'hi', '[]', '', 1000, 1001);
|
||||
`
|
||||
|
||||
// install writes the three legacy files the way an existing install holds
|
||||
// them and returns their paths. mutate runs extra statements against a file
|
||||
// before the import sees it.
|
||||
func install(t *testing.T, mutate map[string]string) Sources {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
src := Sources{
|
||||
StateStore: filepath.Join(dir, "archie.db-tasks.sqlite"),
|
||||
EDA: filepath.Join(dir, "archie.db-eda.sqlite"),
|
||||
Gateway: filepath.Join(dir, "archie.db-conversations.sqlite"),
|
||||
}
|
||||
for path, ddl := range map[string]string{src.StateStore: stateStoreDDL, src.EDA: edaDDL, src.Gateway: gatewayDDL} {
|
||||
sqliteExec(t, path, ddl)
|
||||
}
|
||||
var src Sources
|
||||
src.StateStore, src.EDA, src.Gateway = legacyfixture.Install(t, filepath.Join(t.TempDir(), "archie.db"))
|
||||
for path, stmt := range mutate {
|
||||
switch path {
|
||||
case "state":
|
||||
sqliteExec(t, src.StateStore, stmt)
|
||||
legacyfixture.Exec(t, src.StateStore, stmt)
|
||||
case "eda":
|
||||
sqliteExec(t, src.EDA, stmt)
|
||||
legacyfixture.Exec(t, src.EDA, stmt)
|
||||
case "gateway":
|
||||
sqliteExec(t, src.Gateway, stmt)
|
||||
legacyfixture.Exec(t, src.Gateway, stmt)
|
||||
}
|
||||
}
|
||||
return src
|
||||
}
|
||||
|
||||
func sqliteExec(t *testing.T, path, stmt string) {
|
||||
t.Helper()
|
||||
db, err := sql.Open("sqlite", "file:"+path)
|
||||
if err != nil {
|
||||
t.Fatalf("open fixture: %v", err)
|
||||
}
|
||||
defer func() { _ = db.Close() }()
|
||||
if _, err := db.ExecContext(t.Context(), stmt); err != nil {
|
||||
t.Fatalf("fixture %s: %v", filepath.Base(path), err)
|
||||
}
|
||||
}
|
||||
|
||||
func hashFiles(t *testing.T, dir string) map[string][32]byte {
|
||||
t.Helper()
|
||||
entries, err := os.ReadDir(dir)
|
||||
@@ -297,8 +155,8 @@ func TestImportCopiesEverySourceAndLeavesThemUntouched(t *testing.T) {
|
||||
if !bytes.Equal(value, []byte{0x00, 0xff, 0x10}) {
|
||||
t.Errorf("resource_history.value = %x, want 00ff10", value)
|
||||
}
|
||||
if gotSecret != secret {
|
||||
t.Errorf("binding secret = %q, want %q", gotSecret, secret)
|
||||
if gotSecret != legacyfixture.Secret {
|
||||
t.Errorf("binding secret = %q, want %q", gotSecret, legacyfixture.Secret)
|
||||
}
|
||||
if headers != "" || result != "exit 0" || !configured {
|
||||
t.Errorf("headers %q, result %q, configured %v; want \"\", \"exit 0\", true", headers, result, configured)
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
// Package postgres opens archie's PostgreSQL database and applies its schema
|
||||
// migrations. This file is the PostgreSQL implementation of the EDA
|
||||
// persistence contracts (captures, mappings, bindings and the two dispatch
|
||||
// ledgers) plus the tool_calls transcript, mirroring the PocketBase-backed
|
||||
// internal/infrastructure/edastore.Store it will replace in the cutover wave.
|
||||
// ledgers) plus the tool_calls transcript.
|
||||
package postgres
|
||||
|
||||
import (
|
||||
@@ -20,14 +19,12 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/domain/mapping"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/edastore"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/bindingcipher"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/postgresdb"
|
||||
)
|
||||
|
||||
// EDA is the PostgreSQL implementation of every event-capture contract, plus
|
||||
// the tool_calls transcript the composition projection writes through. It
|
||||
// satisfies the same surface as *edastore.Store, so the cutover wave can swap
|
||||
// one for the other behind storecontract without touching the consumers.
|
||||
// the tool_calls transcript the composition projection writes through.
|
||||
var (
|
||||
_ storecontract.CaptureStore = (*EDA)(nil)
|
||||
_ storecontract.MappingStore = (*EDA)(nil)
|
||||
@@ -40,26 +37,23 @@ var (
|
||||
type EDA struct {
|
||||
pool *pgxpool.Pool
|
||||
q *postgresdb.Queries
|
||||
cipher edastore.BindingCipher
|
||||
cipher bindingcipher.BindingCipher
|
||||
notify func(events.Event)
|
||||
}
|
||||
|
||||
// NewEDA builds an EDA store over pool. A nil cipher keeps binding secrets in
|
||||
// plaintext (the behaviour that predates the option); the caller resolves the
|
||||
// keyring through edastore.NewBindingCipher, exactly as the PocketBase store
|
||||
// does. The pool is owned by the caller, not this store.
|
||||
func NewEDA(pool *pgxpool.Pool, cipher edastore.BindingCipher) *EDA {
|
||||
// plaintext; the caller resolves the keyring through
|
||||
// bindingcipher.NewBindingCipher. The pool is owned by the caller, not this store.
|
||||
func NewEDA(pool *pgxpool.Pool, cipher bindingcipher.BindingCipher) *EDA {
|
||||
return &EDA{pool: pool, q: postgresdb.New(pool), cipher: cipher}
|
||||
}
|
||||
|
||||
// SetNotify wires the change-event callback that the PocketBase store's
|
||||
// Config.Notify provides. It is the same injection point: nil is a silent
|
||||
// no-op, which is what every production construction gets today.
|
||||
// SetNotify wires the change-event callback. nil is a silent no-op, which is
|
||||
// what every production construction gets today.
|
||||
func (s *EDA) SetNotify(fn func(events.Event)) { s.notify = fn }
|
||||
|
||||
// notifyWrite announces one successful write on the bindings or mappings
|
||||
// tables. It mirrors edastore.(*Store).notifyWrite byte-for-byte: the data
|
||||
// carries the record id and action, and consumers refetch the row themselves.
|
||||
// tables. The data carries the record id and action, and consumers refetch the row themselves.
|
||||
func (s *EDA) notifyWrite(kind, subject, action, id string) {
|
||||
if s.notify == nil {
|
||||
return
|
||||
@@ -77,8 +71,7 @@ func newRecordID() string { return uuid.NewString() }
|
||||
// --- captures ---
|
||||
|
||||
// InsertCapture stores one inbound event verbatim. retention and maxEvents are
|
||||
// accepted for contract compatibility and applied as a prune after the insert,
|
||||
// exactly as the PocketBase store does.
|
||||
// applied as a prune after the insert.
|
||||
func (s *EDA) InsertCapture(ctx context.Context, c storecontract.CapturedEvent, retention time.Duration, maxEvents int) (string, error) {
|
||||
received := c.ReceivedAt
|
||||
if received.IsZero() {
|
||||
@@ -208,8 +201,8 @@ func (s *EDA) InsertMapping(ctx context.Context, m mapping.Mapping) (string, err
|
||||
return id, nil
|
||||
}
|
||||
|
||||
// GetMapping returns (nil, nil) for an absent mapping, matching the
|
||||
// PocketBase store's found=false convention the gRPC layer translates.
|
||||
// GetMapping returns (nil, nil) for an absent mapping, the found=false
|
||||
// convention the gRPC layer translates.
|
||||
func (s *EDA) GetMapping(ctx context.Context, id string) (*mapping.Mapping, error) {
|
||||
r, err := s.q.GetMapping(ctx, id)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
@@ -347,8 +340,8 @@ func (s *EDA) InsertBinding(ctx context.Context, b binding.Binding) (string, err
|
||||
return id, nil
|
||||
}
|
||||
|
||||
// GetBinding returns (nil, nil) for an absent binding, matching the
|
||||
// PocketBase store's found=false convention the gRPC layer translates.
|
||||
// GetBinding returns (nil, nil) for an absent binding, the found=false
|
||||
// convention the gRPC layer translates.
|
||||
func (s *EDA) GetBinding(ctx context.Context, id string) (*binding.Binding, error) {
|
||||
r, err := s.q.GetBinding(ctx, id)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
@@ -522,8 +515,21 @@ func ledgerWrite(err error, what string) error {
|
||||
|
||||
// --- tool calls ---
|
||||
|
||||
// ToolCall is one completed tool invocation during an agent stage run, as the
|
||||
// tool_call event projection stores it: a tool's output summary in Result, a
|
||||
// failure's detail in Error.
|
||||
type ToolCall struct {
|
||||
ID string
|
||||
TaskID int64
|
||||
Attempt int
|
||||
Tool string
|
||||
Result string
|
||||
Error string
|
||||
CalledAt time.Time
|
||||
}
|
||||
|
||||
// InsertToolCall appends one row to the tool_calls transcript.
|
||||
func (s *EDA) InsertToolCall(ctx context.Context, tc edastore.ToolCall) error {
|
||||
func (s *EDA) InsertToolCall(ctx context.Context, tc ToolCall) error {
|
||||
calledAt := tc.CalledAt
|
||||
if calledAt.IsZero() {
|
||||
calledAt = time.Now()
|
||||
@@ -543,14 +549,14 @@ func (s *EDA) InsertToolCall(ctx context.Context, tc edastore.ToolCall) error {
|
||||
}
|
||||
|
||||
// TaskToolCalls returns one task's tool calls in call order.
|
||||
func (s *EDA) TaskToolCalls(ctx context.Context, taskID int64) ([]edastore.ToolCall, error) {
|
||||
func (s *EDA) TaskToolCalls(ctx context.Context, taskID int64) ([]ToolCall, error) {
|
||||
rows, err := s.q.TaskToolCalls(ctx, taskID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("edastore: list tool calls: %w", err)
|
||||
}
|
||||
out := make([]edastore.ToolCall, 0, len(rows))
|
||||
out := make([]ToolCall, 0, len(rows))
|
||||
for _, r := range rows {
|
||||
out = append(out, edastore.ToolCall{
|
||||
out = append(out, ToolCall{
|
||||
ID: r.ID,
|
||||
TaskID: r.TaskID,
|
||||
Attempt: int(r.Attempt),
|
||||
|
||||
@@ -12,7 +12,7 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/domain/mapping"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/edastore"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/bindingcipher"
|
||||
)
|
||||
|
||||
const edaTestKey = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
|
||||
@@ -24,7 +24,7 @@ func edaFor(t *testing.T) *EDA {
|
||||
return NewEDA(pool, nil)
|
||||
}
|
||||
|
||||
func edaWithCipher(t *testing.T, cipher edastore.BindingCipher) (*pgxpool.Pool, *EDA) {
|
||||
func edaWithCipher(t *testing.T, cipher bindingcipher.BindingCipher) (*pgxpool.Pool, *EDA) {
|
||||
t.Helper()
|
||||
pool, _ := migrated(t)
|
||||
return pool, NewEDA(pool, cipher)
|
||||
@@ -131,7 +131,7 @@ func TestConcurrentInsertBindingSameSource(t *testing.T) {
|
||||
// untouched, so an edit form that does not echo the secret cannot blank an
|
||||
// armed binding's HMAC key.
|
||||
func TestUpdateBindingEmptySecretPreservesStored(t *testing.T) {
|
||||
cipher, err := edastore.NewBindingCipher(edaTestKey, nil)
|
||||
cipher, err := bindingcipher.NewBindingCipher(edaTestKey, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("NewBindingCipher() error = %v", err)
|
||||
}
|
||||
@@ -173,7 +173,7 @@ func readRawSecret(t *testing.T, pool *pgxpool.Pool, id string) string {
|
||||
// The cipher path must keep decrypt-in-store: what is stored is an envelope,
|
||||
// what reads back is the plaintext HMAC key the intake verifies with.
|
||||
func TestBindingSecretEncryptedAtRestAndDecryptedOnRead(t *testing.T) {
|
||||
cipher, err := edastore.NewBindingCipher(edaTestKey, nil)
|
||||
cipher, err := bindingcipher.NewBindingCipher(edaTestKey, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("NewBindingCipher() error = %v", err)
|
||||
}
|
||||
@@ -200,6 +200,50 @@ func TestBindingSecretEncryptedAtRestAndDecryptedOnRead(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// A deployment with no configured key stores plaintext.
|
||||
func TestNoCipherKeepsPlaintext(t *testing.T) {
|
||||
pool, s := edaWithCipher(t, nil)
|
||||
id, err := s.InsertBinding(t.Context(), binding.Binding{
|
||||
Name: "n", Matcher: binding.Matcher{Source: "src-plain"}, Workflow: "implement",
|
||||
Secret: "supersecretvalue0123",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("InsertBinding() error = %v", err)
|
||||
}
|
||||
if stored := readRawSecret(t, pool, id); stored != "supersecretvalue0123" {
|
||||
t.Errorf("stored secret = %q, want the plaintext with no cipher configured", stored)
|
||||
}
|
||||
}
|
||||
|
||||
// A secret written under the previous key stays readable once a new active
|
||||
// key is installed; otherwise rotation bricks every armed binding.
|
||||
func TestRotatedKeyStillReadsOldRows(t *testing.T) {
|
||||
const oldKey = "fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210"
|
||||
oldCipher, err := bindingcipher.NewBindingCipher(oldKey, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("NewBindingCipher(old) error = %v", err)
|
||||
}
|
||||
pool, s := edaWithCipher(t, oldCipher)
|
||||
id, err := s.InsertBinding(t.Context(), binding.Binding{
|
||||
Name: "n", Matcher: binding.Matcher{Source: "src-rotate"}, Workflow: "implement",
|
||||
Secret: "supersecretvalue0123",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("InsertBinding() error = %v", err)
|
||||
}
|
||||
rotated, err := bindingcipher.NewBindingCipher(edaTestKey, []string{oldKey})
|
||||
if err != nil {
|
||||
t.Fatalf("NewBindingCipher(rotated) error = %v", err)
|
||||
}
|
||||
got, err := NewEDA(pool, rotated).GetBinding(t.Context(), id)
|
||||
if err != nil {
|
||||
t.Fatalf("GetBinding() after rotation error = %v", err)
|
||||
}
|
||||
if got.Secret != "supersecretvalue0123" {
|
||||
t.Errorf("Secret after rotation = %q: the previous key must still decrypt", got.Secret)
|
||||
}
|
||||
}
|
||||
|
||||
// The lifecycle gate survives the port: pending_approval -> armed, and only
|
||||
// from pending_approval.
|
||||
func TestBindingLifecycle(t *testing.T) {
|
||||
@@ -308,13 +352,13 @@ func TestToolCallRoundTrip(t *testing.T) {
|
||||
at := time.Date(2026, 9, 23, 1, 2, 3, 0, time.UTC)
|
||||
|
||||
for range 2 {
|
||||
if err := s.InsertToolCall(t.Context(), edastore.ToolCall{
|
||||
if err := s.InsertToolCall(t.Context(), ToolCall{
|
||||
TaskID: 42, Attempt: 2, Tool: "shell", Result: "all checks passed", CalledAt: at,
|
||||
}); err != nil {
|
||||
t.Fatalf("InsertToolCall() error = %v", err)
|
||||
}
|
||||
}
|
||||
if err := s.InsertToolCall(t.Context(), edastore.ToolCall{
|
||||
if err := s.InsertToolCall(t.Context(), ToolCall{
|
||||
TaskID: 7, Attempt: 1, Tool: "read_file", Error: "no such file", CalledAt: at.Add(time.Second),
|
||||
}); err != nil {
|
||||
t.Fatalf("InsertToolCall(other task) error = %v", err)
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
// Package pgstore opens migrated PostgreSQL stores on a throwaway pgtest
|
||||
// database, for tests outside internal/infrastructure/postgres. A package
|
||||
// using it calls pgtest.Main from TestMain.
|
||||
package pgstore
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/bindingcipher"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgtest"
|
||||
)
|
||||
|
||||
// TaskDB is the State Store's task database: the task, event, status and
|
||||
// identity surface plus the control-plane resources, over one pool.
|
||||
type TaskDB struct {
|
||||
*postgres.Store
|
||||
*postgres.Resources
|
||||
Pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
// Pool opens a pool on a fresh migrated database, closed when t ends.
|
||||
func Pool(t testing.TB) *pgxpool.Pool {
|
||||
t.Helper()
|
||||
return PoolAt(t, pgtest.URL(t))
|
||||
}
|
||||
|
||||
// PoolAt opens a pool on url and migrates it, closed when t ends. Opening a
|
||||
// second pool on the same url is how a test models a restart.
|
||||
func PoolAt(t testing.TB, url string) *pgxpool.Pool {
|
||||
t.Helper()
|
||||
pool, err := postgres.Open(t.Context(), url)
|
||||
if err != nil {
|
||||
t.Fatalf("pgstore: open: %v", err)
|
||||
}
|
||||
t.Cleanup(pool.Close)
|
||||
if err := postgres.Migrate(t.Context(), pool, postgres.Migrations()); err != nil {
|
||||
t.Fatalf("pgstore: migrate: %v", err)
|
||||
}
|
||||
return pool
|
||||
}
|
||||
|
||||
// On returns the task database over pool.
|
||||
func On(pool *pgxpool.Pool) *TaskDB {
|
||||
return &TaskDB{Store: postgres.New(pool), Resources: postgres.NewResources(pool), Pool: pool}
|
||||
}
|
||||
|
||||
// Open returns the task database on a fresh migrated database.
|
||||
func Open(t testing.TB) *TaskDB {
|
||||
t.Helper()
|
||||
return On(Pool(t))
|
||||
}
|
||||
|
||||
// EDA returns the event-capture store on a fresh migrated database. A nil
|
||||
// cipher keeps binding secrets in plaintext.
|
||||
func EDA(t testing.TB, cipher bindingcipher.BindingCipher) *postgres.EDA {
|
||||
t.Helper()
|
||||
return postgres.NewEDA(Pool(t), cipher)
|
||||
}
|
||||
@@ -14,8 +14,7 @@ import (
|
||||
)
|
||||
|
||||
// Resources is the PostgreSQL implementation of the State Store's
|
||||
// control-plane resource document operations. It is separate while the rest
|
||||
// of the transitional SQLite Store is still being ported.
|
||||
// control-plane resource document operations.
|
||||
type Resources struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
)
|
||||
|
||||
// TestEventAttributionSurvivesTheStateStoreBoundary runs the same insert through
|
||||
@@ -28,7 +28,7 @@ func TestEventAttributionSurvivesTheStateStoreBoundary(t *testing.T) {
|
||||
for _, mode := range []string{"local", "grpc"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
local := store.OpenTest(t)
|
||||
local := pgstore.Open(t)
|
||||
var c contract = local
|
||||
if mode == "grpc" {
|
||||
c = remoteTaskStore(t, local, nil, nil)
|
||||
|
||||
@@ -6,16 +6,16 @@ import (
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/binding"
|
||||
"github.com/samcharles93/archie-core/internal/domain/mapping"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/edastore"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
)
|
||||
|
||||
func TestCaptureListsExceedUnaryMessageLimit(t *testing.T) {
|
||||
local := store.OpenTest(t)
|
||||
eda := edastore.OpenTest(t)
|
||||
local := pgstore.Open(t)
|
||||
eda := pgstore.EDA(t, nil)
|
||||
body := strings.Repeat("x", 256<<10)
|
||||
for range 20 {
|
||||
if _, err := eda.InsertCapture(t.Context(), store.CapturedEvent{Source: "large", Body: body, Authenticated: true}, 0, 0); err != nil {
|
||||
if _, err := eda.InsertCapture(t.Context(), storecontract.CapturedEvent{Source: "large", Body: body, Authenticated: true}, 0, 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -49,7 +49,7 @@ func TestCaptureListsExceedUnaryMessageLimit(t *testing.T) {
|
||||
}
|
||||
remote := remoteEDA(t, local, eda)
|
||||
for _, undispatched := range []bool{false, true} {
|
||||
var captures []store.CapturedEvent
|
||||
var captures []storecontract.CapturedEvent
|
||||
var err error
|
||||
if undispatched {
|
||||
captures, err = remote.ListUndispatchedCaptures(t.Context(), []string{"large"}, 20)
|
||||
|
||||
@@ -13,56 +13,57 @@ import (
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/binding"
|
||||
"github.com/samcharles93/archie-core/internal/domain/mapping"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/edastore"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
)
|
||||
|
||||
// contract is the union of every store surface staterpc fronts (minus the
|
||||
// playbook-dispatch ledger, split out below to keep the interface under the
|
||||
// repo's 8-method cap), so the same test battery drives both the local
|
||||
// *store.Store and the remote *Client through one interface value, per
|
||||
// *pgstore.TaskDB and the remote *Client through one interface value, per
|
||||
// docs/prds/state-store-contract.md §11's conformance requirement.
|
||||
type contract interface {
|
||||
store.TaskStore
|
||||
store.BindingTaskCreator
|
||||
store.ConfigSnapshotStore
|
||||
store.ApplyStatusStore
|
||||
storecontract.TaskStore
|
||||
storecontract.BindingTaskCreator
|
||||
storecontract.ConfigSnapshotStore
|
||||
storecontract.ApplyStatusStore
|
||||
}
|
||||
|
||||
// edaContract is the event-capture half, which the PocketBase store serves.
|
||||
// It is a separate interface because no single type implements both halves
|
||||
// any more: that split is the point of the migration, not an accident.
|
||||
type edaContract interface {
|
||||
store.CaptureStore
|
||||
store.MappingStore
|
||||
store.BindingStore
|
||||
store.BindingDispatcher
|
||||
storecontract.CaptureStore
|
||||
storecontract.MappingStore
|
||||
storecontract.BindingStore
|
||||
storecontract.BindingDispatcher
|
||||
}
|
||||
|
||||
// playbookContract is the playbook-dispatch idempotency-ledger surface, split
|
||||
// out from contract so each aggregate stays under the repo's interfacebloat
|
||||
// cap without weakening what the conformance battery proves.
|
||||
type playbookContract interface {
|
||||
store.PlaybookDispatcher
|
||||
storecontract.PlaybookDispatcher
|
||||
}
|
||||
|
||||
// taskLogContract is the task-log read group, driven separately because it is
|
||||
// not a *store.Store surface: the reader is internal/logging's own registry,
|
||||
// not a *pgstore.TaskDB surface: the reader is internal/logging's own registry,
|
||||
// which owns the log format, so the local side of this contract is a registry
|
||||
// rather than a store.
|
||||
type taskLogContract interface {
|
||||
store.TaskLogStore
|
||||
storecontract.TaskLogStore
|
||||
}
|
||||
|
||||
// remoteEDA fronts both stores for a battery that exercises event-capture
|
||||
// surfaces over the wire.
|
||||
func remoteEDA(t *testing.T, local *store.Store, eda *edastore.Store) *Client {
|
||||
func remoteEDA(t *testing.T, local *pgstore.TaskDB, eda *postgres.EDA) *Client {
|
||||
t.Helper()
|
||||
return remoteTaskStore(t, local, nil, eda)
|
||||
}
|
||||
|
||||
func remoteContract(t *testing.T, local *store.Store) contract {
|
||||
func remoteContract(t *testing.T, local *pgstore.TaskDB) contract {
|
||||
t.Helper()
|
||||
return remoteTaskStore(t, local, nil, nil)
|
||||
}
|
||||
@@ -75,7 +76,7 @@ func remoteContract(t *testing.T, local *store.Store) contract {
|
||||
// task store for the task surfaces, the event-capture store for captures,
|
||||
// mappings, bindings and the dispatch ledgers. eda may be nil for a battery
|
||||
// that exercises only task surfaces.
|
||||
func remoteTaskStore(t *testing.T, local *store.Store, logs store.TaskLogStore, eda *edastore.Store) *Client {
|
||||
func remoteTaskStore(t *testing.T, local *pgstore.TaskDB, logs storecontract.TaskLogStore, eda *postgres.EDA) *Client {
|
||||
t.Helper()
|
||||
listener := bufconn.Listen(1 << 20)
|
||||
server := grpc.NewServer()
|
||||
@@ -112,8 +113,8 @@ func TestStateStoreConformance(t *testing.T) {
|
||||
for _, mode := range []string{"local", "grpc"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
local := store.OpenTest(t)
|
||||
eda := edastore.OpenTest(t)
|
||||
local := pgstore.Open(t)
|
||||
eda := pgstore.EDA(t, nil)
|
||||
var c contract = local
|
||||
var ec edaContract = eda
|
||||
var pc playbookContract = eda
|
||||
@@ -168,7 +169,7 @@ func TestStateStoreConformance(t *testing.T) {
|
||||
|
||||
// Stale transition: from no longer matches current status.
|
||||
err = c.Transition(ctx, task.ID, "queued", "merged", "")
|
||||
if !errors.Is(err, store.ErrStaleTransition) {
|
||||
if !errors.Is(err, storecontract.ErrStaleTransition) {
|
||||
t.Fatalf("Transition stale = %v, want ErrStaleTransition", err)
|
||||
}
|
||||
|
||||
@@ -181,7 +182,7 @@ func TestStateStoreConformance(t *testing.T) {
|
||||
if err := c.BeginRemediation(ctx, task.ID, `{"review_id":7}`); err != nil {
|
||||
t.Fatalf("BeginRemediation: %v", err)
|
||||
}
|
||||
if err := c.BeginRemediation(ctx, task.ID, `{"review_id":7}`); !errors.Is(err, store.ErrStaleTransition) {
|
||||
if err := c.BeginRemediation(ctx, task.ID, `{"review_id":7}`); !errors.Is(err, storecontract.ErrStaleTransition) {
|
||||
t.Fatalf("BeginRemediation stale = %v, want ErrStaleTransition", err)
|
||||
}
|
||||
remediated, err := c.TaskByID(ctx, task.ID)
|
||||
@@ -197,7 +198,7 @@ func TestStateStoreConformance(t *testing.T) {
|
||||
if err := c.Transition(ctx, task.ID, "queued", "running", "claimed"); err != nil {
|
||||
t.Fatalf("claim: %v", err)
|
||||
}
|
||||
if err := c.UpdateReviewPayload(ctx, task.ID, `{}`); !errors.Is(err, store.ErrStaleTransition) {
|
||||
if err := c.UpdateReviewPayload(ctx, task.ID, `{}`); !errors.Is(err, storecontract.ErrStaleTransition) {
|
||||
t.Fatalf("UpdateReviewPayload stale = %v, want ErrStaleTransition", err)
|
||||
}
|
||||
|
||||
@@ -309,7 +310,7 @@ func TestStateStoreConformance(t *testing.T) {
|
||||
if parked.Status != "parked" || parked.ParkClass != "transient" || parked.ParkReason != "container pool unavailable" {
|
||||
t.Fatalf("ParkTask row = status:%q class:%q reason:%q", parked.Status, parked.ParkClass, parked.ParkReason)
|
||||
}
|
||||
if err := c.ParkTask(ctx, claimed.ID, "running", "late park", "transient"); !errors.Is(err, store.ErrStaleTransition) {
|
||||
if err := c.ParkTask(ctx, claimed.ID, "running", "late park", "transient"); !errors.Is(err, storecontract.ErrStaleTransition) {
|
||||
t.Fatalf("ParkTask stale = %v, want ErrStaleTransition", err)
|
||||
}
|
||||
// An unclassified park normalizes to needs_human store-side rather
|
||||
@@ -371,11 +372,11 @@ func TestStateStoreConformance(t *testing.T) {
|
||||
t.Fatalf("UpdateMapping: %v", err)
|
||||
}
|
||||
err = ec.UpdateMapping(ctx, mapping.Mapping{ID: "rabsent00000000", Name: "x", Fields: gotMapping.Fields})
|
||||
if !errors.Is(err, store.ErrMappingNotFound) {
|
||||
if !errors.Is(err, storecontract.ErrMappingNotFound) {
|
||||
t.Fatalf("UpdateMapping missing = %v, want ErrMappingNotFound", err)
|
||||
}
|
||||
err = ec.DeleteMapping(ctx, "rabsent00000000")
|
||||
if !errors.Is(err, store.ErrMappingNotFound) {
|
||||
if !errors.Is(err, storecontract.ErrMappingNotFound) {
|
||||
t.Fatalf("DeleteMapping missing = %v, want ErrMappingNotFound", err)
|
||||
}
|
||||
|
||||
@@ -393,7 +394,7 @@ func TestStateStoreConformance(t *testing.T) {
|
||||
Name: "b2", Matcher: binding.Matcher{Source: "sentry"}, MappingID: mappingID,
|
||||
Workflow: "implement", Secret: "0123456789abcdef0123456789abcdef",
|
||||
})
|
||||
if !errors.Is(err, store.ErrBindingOverlap) {
|
||||
if !errors.Is(err, storecontract.ErrBindingOverlap) {
|
||||
t.Fatalf("InsertBinding overlap = %v, want ErrBindingOverlap", err)
|
||||
}
|
||||
missingBinding, err := ec.GetBinding(ctx, "rabsent00000000")
|
||||
@@ -411,16 +412,16 @@ func TestStateStoreConformance(t *testing.T) {
|
||||
t.Fatalf("ApproveBinding from pending_approval = %v", err)
|
||||
}
|
||||
err = ec.ApproveBinding(ctx, bindingID)
|
||||
if !errors.Is(err, store.ErrBindingTransition) {
|
||||
if !errors.Is(err, storecontract.ErrBindingTransition) {
|
||||
t.Fatalf("ApproveBinding when armed = %v, want ErrBindingTransition", err)
|
||||
}
|
||||
err = ec.DeleteBinding(ctx, "rabsent00000000")
|
||||
if !errors.Is(err, store.ErrBindingNotFound) {
|
||||
if !errors.Is(err, storecontract.ErrBindingNotFound) {
|
||||
t.Fatalf("DeleteBinding missing = %v, want ErrBindingNotFound", err)
|
||||
}
|
||||
|
||||
// Capture + dispatch.
|
||||
captureID, err := ec.InsertCapture(ctx, store.CapturedEvent{Source: "sentry", Body: `{"id":1}`, Authenticated: true}, 0, 0)
|
||||
captureID, err := ec.InsertCapture(ctx, storecontract.CapturedEvent{Source: "sentry", Body: `{"id":1}`, Authenticated: true}, 0, 0)
|
||||
if err != nil || captureID == "" {
|
||||
t.Fatalf("InsertCapture: %v %v", captureID, err)
|
||||
}
|
||||
@@ -438,7 +439,7 @@ func TestStateStoreConformance(t *testing.T) {
|
||||
t.Fatalf("RecordDispatch: %v", err)
|
||||
}
|
||||
err = ec.RecordDispatch(ctx, bindingID, 1, captureID, bindingTask.ID)
|
||||
if !errors.Is(err, store.ErrAlreadyDispatched) {
|
||||
if !errors.Is(err, storecontract.ErrAlreadyDispatched) {
|
||||
t.Fatalf("RecordDispatch dup = %v, want ErrAlreadyDispatched", err)
|
||||
}
|
||||
if _, err := ec.ListUndispatchedCaptures(ctx, []string{"sentry"}, 10); err != nil {
|
||||
@@ -466,7 +467,7 @@ func TestStateStoreConformance(t *testing.T) {
|
||||
t.Fatalf("RecordPlaybookDispatch (distinct action_id) = %v, want success", err)
|
||||
}
|
||||
err = pc.RecordPlaybookDispatch(ctx, "pb.yaml", "v1", "archie:acme/widget/7", "notify")
|
||||
if !errors.Is(err, store.ErrAlreadyDispatched) {
|
||||
if !errors.Is(err, storecontract.ErrAlreadyDispatched) {
|
||||
t.Fatalf("RecordPlaybookDispatch dup = %v, want ErrAlreadyDispatched", err)
|
||||
}
|
||||
if err := pc.DeletePlaybookDispatches(ctx, "pb.yaml"); err != nil {
|
||||
@@ -487,7 +488,7 @@ func TestStateStoreConformance(t *testing.T) {
|
||||
func TestConfigSnapshotContract(t *testing.T) {
|
||||
for _, mode := range []string{"local", "grpc"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
local := store.OpenTest(t)
|
||||
local := pgstore.Open(t)
|
||||
var st contract = local
|
||||
if mode == "grpc" {
|
||||
st = remoteContract(t, local)
|
||||
@@ -498,7 +499,7 @@ func TestConfigSnapshotContract(t *testing.T) {
|
||||
t.Fatalf("unpublished snapshot = (found %v, %v), want (false, nil)", found, err)
|
||||
}
|
||||
|
||||
published := store.ConfigSnapshot{
|
||||
published := storecontract.ConfigSnapshot{
|
||||
Schema: "webui.ConfigView/1",
|
||||
Document: []byte(`{"identity":{"bot_user":"archie"},"providers":{"openai":{"api_key_env":"OPENAI_API_KEY","configured":true}}}`),
|
||||
PublishedAt: time.Date(2026, 9, 9, 12, 30, 0, 0, time.UTC),
|
||||
|
||||
@@ -9,7 +9,7 @@ import (
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
)
|
||||
|
||||
// TestUnmapErrorPreservesContextIdentity pins the §6 deadline contract that
|
||||
@@ -34,7 +34,7 @@ func TestUnmapErrorPreservesContextIdentity(t *testing.T) {
|
||||
if !errors.Is(got, tt.want) {
|
||||
t.Fatalf("unmapError(%q) = %v, want errors.Is(err, %v)", tt.err, got, tt.want)
|
||||
}
|
||||
if errors.Is(got, store.ErrStaleTransition) {
|
||||
if errors.Is(got, storecontract.ErrStaleTransition) {
|
||||
t.Fatalf("unmapError(%q) = %v, must not map to a store sentinel", tt.err, got)
|
||||
}
|
||||
})
|
||||
@@ -75,12 +75,12 @@ func TestUnmapErrorSentinelFidelity(t *testing.T) {
|
||||
store error
|
||||
rehyd error
|
||||
}{
|
||||
{name: "stale transition", store: store.ErrStaleTransition, rehyd: store.ErrStaleTransition},
|
||||
{name: "binding not found", store: store.ErrBindingNotFound, rehyd: store.ErrBindingNotFound},
|
||||
{name: "mapping not found", store: store.ErrMappingNotFound, rehyd: store.ErrMappingNotFound},
|
||||
{name: "binding overlap", store: store.ErrBindingOverlap, rehyd: store.ErrBindingOverlap},
|
||||
{name: "binding transition", store: store.ErrBindingTransition, rehyd: store.ErrBindingTransition},
|
||||
{name: "already dispatched", store: store.ErrAlreadyDispatched, rehyd: store.ErrAlreadyDispatched},
|
||||
{name: "stale transition", store: storecontract.ErrStaleTransition, rehyd: storecontract.ErrStaleTransition},
|
||||
{name: "binding not found", store: storecontract.ErrBindingNotFound, rehyd: storecontract.ErrBindingNotFound},
|
||||
{name: "mapping not found", store: storecontract.ErrMappingNotFound, rehyd: storecontract.ErrMappingNotFound},
|
||||
{name: "binding overlap", store: storecontract.ErrBindingOverlap, rehyd: storecontract.ErrBindingOverlap},
|
||||
{name: "binding transition", store: storecontract.ErrBindingTransition, rehyd: storecontract.ErrBindingTransition},
|
||||
{name: "already dispatched", store: storecontract.ErrAlreadyDispatched, rehyd: storecontract.ErrAlreadyDispatched},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
@@ -104,7 +104,7 @@ func TestUnmapErrorDoesNotLeakInternalDetail(t *testing.T) {
|
||||
const detail = "sql: path=/var/lib/archie/archie.db secret=abcdef"
|
||||
internal := mapError(errors.New(detail))
|
||||
got := unmapError(internal)
|
||||
if errors.Is(got, store.ErrStaleTransition) || errors.Is(got, store.ErrBindingNotFound) || errors.Is(got, store.ErrAlreadyDispatched) {
|
||||
if errors.Is(got, storecontract.ErrStaleTransition) || errors.Is(got, storecontract.ErrBindingNotFound) || errors.Is(got, storecontract.ErrAlreadyDispatched) {
|
||||
t.Fatalf("unmapError(internal) = %v, must not map to a store sentinel", got)
|
||||
}
|
||||
if st, ok := status.FromError(got); !ok || st.Code() != codes.Internal {
|
||||
@@ -118,7 +118,7 @@ func TestUnmapErrorDoesNotLeakInternalDetail(t *testing.T) {
|
||||
// status or a store sentinel).
|
||||
raw := errors.New("transport failure")
|
||||
got = unmapError(raw)
|
||||
if errors.Is(got, store.ErrStaleTransition) {
|
||||
if errors.Is(got, storecontract.ErrStaleTransition) {
|
||||
t.Fatalf("unmapError(raw) = %v, must not map to a store sentinel", got)
|
||||
}
|
||||
if !errors.Is(got, raw) {
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
package staterpc
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgtest"
|
||||
)
|
||||
|
||||
func TestMain(m *testing.M) { os.Exit(pgtest.Main(m)) }
|
||||
@@ -14,10 +14,10 @@ import (
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/binding"
|
||||
"github.com/samcharles93/archie-core/internal/domain/mapping"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/edastore"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
)
|
||||
|
||||
// grantsServer wires TaskGrants' Unary/Stream interceptors -- the same
|
||||
@@ -28,14 +28,14 @@ func grantsServer(t *testing.T, adminToken string) (grants *TaskGrants, dial fun
|
||||
t.Helper()
|
||||
grants = &TaskGrants{}
|
||||
listener := bufconn.Listen(1 << 20)
|
||||
local := store.OpenTest(t)
|
||||
local := pgstore.Open(t)
|
||||
server := grpc.NewServer(
|
||||
grpc.ChainUnaryInterceptor(grants.UnaryInterceptor(adminToken)),
|
||||
grpc.ChainStreamInterceptor(grants.StreamInterceptor(adminToken)),
|
||||
)
|
||||
// One event-capture store serves every EDA surface, as the real
|
||||
// composition does: separate instances would not share a database.
|
||||
eda := edastore.OpenTest(t)
|
||||
eda := pgstore.EDA(t, nil)
|
||||
RegisterServer(server, Deps{
|
||||
Tasks: local, ConfigSnapshots: local, ApplyStatus: local,
|
||||
Captures: eda, Mappings: eda, Bindings: eda,
|
||||
@@ -79,7 +79,7 @@ func TestCaptureStreamsCarryTheAdminToken(t *testing.T) {
|
||||
|
||||
body := strings.Repeat("x", 256<<10)
|
||||
for range 20 {
|
||||
if _, err := admin.InsertCapture(ctx, store.CapturedEvent{Source: "large", Body: body, Authenticated: true}, 0, 0); err != nil {
|
||||
if _, err := admin.InsertCapture(ctx, storecontract.CapturedEvent{Source: "large", Body: body, Authenticated: true}, 0, 0); err != nil {
|
||||
t.Fatalf("InsertCapture: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -114,10 +114,10 @@ func TestCaptureStreamsCarryTheAdminToken(t *testing.T) {
|
||||
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
list func(context.Context) ([]store.CapturedEvent, error)
|
||||
list func(context.Context) ([]storecontract.CapturedEvent, error)
|
||||
}{
|
||||
{"ListCaptures", func(ctx context.Context) ([]store.CapturedEvent, error) { return admin.ListCaptures(ctx, 20) }},
|
||||
{"ListUndispatchedCaptures", func(ctx context.Context) ([]store.CapturedEvent, error) {
|
||||
{"ListCaptures", func(ctx context.Context) ([]storecontract.CapturedEvent, error) { return admin.ListCaptures(ctx, 20) }},
|
||||
{"ListUndispatchedCaptures", func(ctx context.Context) ([]storecontract.CapturedEvent, error) {
|
||||
return admin.ListUndispatchedCaptures(ctx, []string{"large"}, 20)
|
||||
}},
|
||||
} {
|
||||
@@ -263,7 +263,7 @@ func TestOnlyAdminPublishesTheConfigSnapshot(t *testing.T) {
|
||||
}
|
||||
worker := dial(t, workerToken)
|
||||
|
||||
snapshot := store.ConfigSnapshot{Schema: "webui.ConfigView/1", Document: []byte(`{}`)}
|
||||
snapshot := storecontract.ConfigSnapshot{Schema: "webui.ConfigView/1", Document: []byte(`{}`)}
|
||||
if err := admin.PutConfigSnapshot(ctx, snapshot); err != nil {
|
||||
t.Fatalf("admin PutConfigSnapshot: %v", err)
|
||||
}
|
||||
@@ -298,7 +298,7 @@ func TestOnlyAdminReportsApplyStatus(t *testing.T) {
|
||||
}
|
||||
worker := dial(t, workerToken)
|
||||
|
||||
status := store.ApplyStatus{Process: "archied", Kind: "tool-settings", AppliedVersion: 2}
|
||||
status := storecontract.ApplyStatus{Process: "archied", Kind: "tool-settings", AppliedVersion: 2}
|
||||
if err := admin.PutApplyStatus(ctx, status); err != nil {
|
||||
t.Fatalf("admin PutApplyStatus: %v", err)
|
||||
}
|
||||
|
||||
@@ -5,8 +5,8 @@ import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
"github.com/samcharles93/archie-core/internal/logging"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
)
|
||||
|
||||
// A decoded task-log page must never carry a nil slice for a collection field.
|
||||
@@ -54,7 +54,7 @@ func TestTaskLogPageCarriesNoNilCollectionFields(t *testing.T) {
|
||||
|
||||
var c taskLogContract = reader
|
||||
if mode == "grpc" {
|
||||
c = remoteTaskStore(t, store.OpenTest(t), reader, nil)
|
||||
c = remoteTaskStore(t, pgstore.Open(t), reader, nil)
|
||||
}
|
||||
|
||||
page, err := c.TaskLog(ctx, taskID, 0, logging.Query{})
|
||||
|
||||
@@ -8,8 +8,8 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
"github.com/samcharles93/archie-core/internal/logging"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
)
|
||||
|
||||
// TestTaskLogContract drives the task-log read group through both adapters,
|
||||
@@ -41,7 +41,7 @@ func TestTaskLogContract(t *testing.T) {
|
||||
|
||||
var c taskLogContract = reader
|
||||
if mode == "grpc" {
|
||||
c = remoteTaskStore(t, store.OpenTest(t), reader, nil)
|
||||
c = remoteTaskStore(t, pgstore.Open(t), reader, nil)
|
||||
}
|
||||
|
||||
t.Run("a page carries the decoded entries and their fields", func(t *testing.T) {
|
||||
@@ -162,7 +162,7 @@ func TestTaskLogContract(t *testing.T) {
|
||||
// that has no log, and the dashboard rendered that as "task logging is
|
||||
// optional and was not enabled for this run".
|
||||
func TestTaskLogContractWithoutAReaderIsUnavailable(t *testing.T) {
|
||||
local := store.OpenTest(t)
|
||||
local := pgstore.Open(t)
|
||||
// remoteContract leaves Deps.TaskLogs nil, which is what a store service
|
||||
// sharing no state directory with the daemon looks like.
|
||||
c := remoteContract(t, local)
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
package taskactions
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgtest"
|
||||
)
|
||||
|
||||
func TestMain(m *testing.M) { os.Exit(pgtest.Main(m)) }
|
||||
@@ -10,9 +10,9 @@ import (
|
||||
natssrv "github.com/nats-io/nats-server/v2/test"
|
||||
"github.com/nats-io/nats.go"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
domain "github.com/samcharles93/archie-core/internal/domain/taskactions"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
"github.com/samcharles93/archie-core/internal/taskstate"
|
||||
)
|
||||
|
||||
@@ -86,10 +86,10 @@ func TestActionErrorKeepsItsSentinelAcrossNATS(t *testing.T) {
|
||||
},
|
||||
{
|
||||
name: "store refused a stale transition",
|
||||
store: stubStore{task: running, err: store.ErrStaleTransition},
|
||||
store: stubStore{task: running, err: storecontract.ErrStaleTransition},
|
||||
cancel: func(int64) bool { return true },
|
||||
action: taskstate.ActionStop,
|
||||
want: store.ErrStaleTransition,
|
||||
want: storecontract.ErrStaleTransition,
|
||||
},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
|
||||
@@ -4,28 +4,23 @@ import (
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/binding"
|
||||
"github.com/samcharles93/archie-core/internal/domain/mapping"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/edastore"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
)
|
||||
|
||||
// bindingTestServer wires a Server backed by a single *store.Store for all
|
||||
// bindingTestServer wires a Server backed by a single *pgstore.TaskDB for all
|
||||
// three dashboards surfaces (Captures, Mappings, Bindings) and seeds the
|
||||
// one workflow binding tests need to pass server-side validation.
|
||||
func bindingTestServer(t *testing.T) *Server {
|
||||
t.Helper()
|
||||
s, err := store.Open(t.Context(), filepath.Join(t.TempDir(), "test.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s := pgstore.Open(t)
|
||||
t.Cleanup(func() { _ = s.Close() })
|
||||
eda := edastore.OpenTest(t)
|
||||
eda := pgstore.EDA(t, nil)
|
||||
return &Server{
|
||||
Store: s,
|
||||
Log: slog.New(slog.DiscardHandler),
|
||||
|
||||
@@ -5,32 +5,28 @@ import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/edastore"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
)
|
||||
|
||||
// captureTestServer builds a Server whose Captures field points at the same
|
||||
// concrete *store.Store as Store, so tests can assert on persisted rows
|
||||
// concrete *pgstore.TaskDB as Store, so tests can assert on persisted rows
|
||||
// through the narrower CaptureStore interface -- Server.Store's static type
|
||||
// (store.TaskStore) does not expose ListCaptures.
|
||||
// (storecontract.TaskStore) does not expose ListCaptures.
|
||||
func captureTestServer(t *testing.T) *Server {
|
||||
t.Helper()
|
||||
s, err := store.Open(t.Context(), filepath.Join(t.TempDir(), "test.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s := pgstore.Open(t)
|
||||
t.Cleanup(func() { _ = s.Close() })
|
||||
return &Server{
|
||||
Store: s,
|
||||
Log: slog.New(slog.DiscardHandler),
|
||||
// Captures come from the event-capture store; the task store no
|
||||
// longer holds them.
|
||||
Captures: edastore.OpenTest(t),
|
||||
Captures: pgstore.EDA(t, nil),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -39,7 +35,7 @@ func captureTestServer(t *testing.T) *Server {
|
||||
// internal/infrastructure/captureintake and is tested there.
|
||||
func seedCapture(t *testing.T, srv *Server, source string) string {
|
||||
t.Helper()
|
||||
id, err := srv.Captures.InsertCapture(t.Context(), store.CapturedEvent{
|
||||
id, err := srv.Captures.InsertCapture(t.Context(), storecontract.CapturedEvent{
|
||||
ReceivedAt: time.Now().UTC(),
|
||||
Source: source,
|
||||
Body: `{"n":1}`,
|
||||
|
||||
@@ -10,9 +10,9 @@ import (
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/channels/status"
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/logging"
|
||||
"github.com/samcharles93/archie-core/internal/secret"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
)
|
||||
|
||||
// fakeSecrets are recognisable strings that must never appear anywhere in
|
||||
@@ -553,7 +553,7 @@ func TestRemoteConfigViewRendersThePublishedSnapshot(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
source := RemoteConfigView(stubSnapshots{snapshot: store.ConfigSnapshot{
|
||||
source := RemoteConfigView(stubSnapshots{snapshot: storecontract.ConfigSnapshot{
|
||||
Schema: ConfigViewSchema,
|
||||
Document: document,
|
||||
}, found: true})
|
||||
@@ -573,7 +573,7 @@ func TestRemoteConfigViewRendersThePublishedSnapshot(t *testing.T) {
|
||||
// TestRemoteConfigViewRefusesAnUnknownSchema: a document whose shape this
|
||||
// build does not know is not something to render half of.
|
||||
func TestRemoteConfigViewRefusesAnUnknownSchema(t *testing.T) {
|
||||
source := RemoteConfigView(stubSnapshots{snapshot: store.ConfigSnapshot{
|
||||
source := RemoteConfigView(stubSnapshots{snapshot: storecontract.ConfigSnapshot{
|
||||
Schema: "webui.ConfigView/99",
|
||||
Document: []byte(`{}`),
|
||||
}, found: true})
|
||||
@@ -600,14 +600,16 @@ func TestConfigWithNoPublishedSnapshotIsEmpty(t *testing.T) {
|
||||
}
|
||||
|
||||
type stubSnapshots struct {
|
||||
snapshot store.ConfigSnapshot
|
||||
snapshot storecontract.ConfigSnapshot
|
||||
found bool
|
||||
err error
|
||||
}
|
||||
|
||||
func (s stubSnapshots) PutConfigSnapshot(context.Context, store.ConfigSnapshot) error { return s.err }
|
||||
func (s stubSnapshots) PutConfigSnapshot(context.Context, storecontract.ConfigSnapshot) error {
|
||||
return s.err
|
||||
}
|
||||
|
||||
func (s stubSnapshots) ConfigSnapshot(context.Context) (store.ConfigSnapshot, bool, error) {
|
||||
func (s stubSnapshots) ConfigSnapshot(context.Context) (storecontract.ConfigSnapshot, bool, error) {
|
||||
return s.snapshot, s.found, s.err
|
||||
}
|
||||
|
||||
|
||||
@@ -6,25 +6,21 @@ import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/mapping"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/edastore"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
)
|
||||
|
||||
// mappingTestServer builds a Server with both Mappings and Captures backed
|
||||
// by the same concrete *store.Store, so preview tests can insert a real
|
||||
// by the same concrete *pgstore.TaskDB, so preview tests can insert a real
|
||||
// capture and resolve a mapping against it end to end.
|
||||
func mappingTestServer(t *testing.T) *Server {
|
||||
t.Helper()
|
||||
s, err := store.Open(t.Context(), filepath.Join(t.TempDir(), "test.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s := pgstore.Open(t)
|
||||
t.Cleanup(func() { _ = s.Close() })
|
||||
eda := edastore.OpenTest(t)
|
||||
eda := pgstore.EDA(t, nil)
|
||||
return &Server{
|
||||
Store: s,
|
||||
Log: slog.New(slog.DiscardHandler),
|
||||
@@ -200,7 +196,7 @@ func TestHandleMappingDelete(t *testing.T) {
|
||||
|
||||
func TestHandleMappingPreviewResolvesAgainstARealCapture(t *testing.T) {
|
||||
srv := mappingTestServer(t)
|
||||
capID, err := srv.Captures.InsertCapture(t.Context(), store.CapturedEvent{
|
||||
capID, err := srv.Captures.InsertCapture(t.Context(), storecontract.CapturedEvent{
|
||||
Source: "sentry",
|
||||
Body: `{"issue":{"title":"bug found"},"count":3}`,
|
||||
}, 0, 0)
|
||||
|
||||
@@ -15,13 +15,13 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/domain/taskactions"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
taskactionstore "github.com/samcharles93/archie-core/internal/infrastructure/taskactions"
|
||||
"github.com/samcharles93/archie-core/internal/logging"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
"github.com/samcharles93/archie-core/internal/taskstate"
|
||||
)
|
||||
|
||||
@@ -185,7 +185,7 @@ type recordingTaskStopper struct {
|
||||
}
|
||||
|
||||
type archiveFailingStore struct {
|
||||
store.TaskStore
|
||||
storecontract.TaskStore
|
||||
err error
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgtest"
|
||||
)
|
||||
|
||||
func TestMain(m *testing.M) { os.Exit(pgtest.Main(m)) }
|
||||
@@ -3,7 +3,7 @@ package webui
|
||||
// Remote-contract coverage for the dashboard data paths. The production UI
|
||||
// process (archie-ui, and the daemon's webui) serves task, capture, mapping
|
||||
// and binding routes against a *staterpc.Client — the remote read contract —
|
||||
// not a concrete *store.Store. Every other webui test feeds a local store
|
||||
// not a concrete *pgstore.TaskDB. Every other webui test feeds a local store
|
||||
// directly, so none of them prove the handlers work once the data crosses the
|
||||
// gRPC wire. These do: they stand up a real SQLite store behind
|
||||
// staterpc.RegisterServer, dial it, and assert the handlers serve correctly.
|
||||
@@ -21,9 +21,8 @@ import (
|
||||
"google.golang.org/grpc"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/edastore"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/staterpc"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
)
|
||||
|
||||
// newRemoteTestServer serves a real SQLite store behind a gRPC listener and
|
||||
@@ -33,10 +32,7 @@ import (
|
||||
// rather than a fake.
|
||||
func newRemoteTestServer(t *testing.T) *Server {
|
||||
t.Helper()
|
||||
st, err := store.Open(t.Context(), t.TempDir()+"/remote.db")
|
||||
if err != nil {
|
||||
t.Fatalf("open temp store: %v", err)
|
||||
}
|
||||
st := pgstore.Open(t)
|
||||
t.Cleanup(func() { _ = st.Close() })
|
||||
|
||||
listener, err := (&net.ListenConfig{}).Listen(t.Context(), "tcp", "127.0.0.1:0")
|
||||
@@ -48,7 +44,7 @@ func newRemoteTestServer(t *testing.T) *Server {
|
||||
// surfaces, the event-capture store serves captures/mappings/bindings.
|
||||
// Leaving one nil makes ListMappings/ListBindings fail closed with
|
||||
// err*Unavailable, which is also the real wiring.
|
||||
eda := edastore.OpenTest(t)
|
||||
eda := pgstore.EDA(t, nil)
|
||||
staterpc.RegisterServer(server, staterpc.Deps{
|
||||
Tasks: st,
|
||||
Captures: eda,
|
||||
|
||||
@@ -12,7 +12,6 @@ import (
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
)
|
||||
|
||||
// testAt is a fixed instant every synthetic event in this file shares, so a
|
||||
@@ -130,7 +129,7 @@ var errWriteFailed = errors.New("write failed")
|
||||
// fakeEventStore serves EventsSince from a fixed, pre-seeded slice, paginating
|
||||
// the same way the real store does: up to limit events after cursor.
|
||||
type fakeEventStore struct {
|
||||
store.TaskStore
|
||||
storecontract.TaskStore
|
||||
all []events.Event
|
||||
}
|
||||
|
||||
|
||||
@@ -20,24 +20,21 @@ import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
)
|
||||
|
||||
func newTestServer(t *testing.T) *Server {
|
||||
t.Helper()
|
||||
s, err := store.Open(t.Context(), filepath.Join(t.TempDir(), "test.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s := pgstore.Open(t)
|
||||
t.Cleanup(func() { _ = s.Close() })
|
||||
srv := &Server{Store: s, Log: slog.New(slog.DiscardHandler)}
|
||||
// Composition always gives the dashboard a Gateway contract; task
|
||||
@@ -51,7 +48,7 @@ func newTestServer(t *testing.T) *Server {
|
||||
// inject errors. Methods that are not overridden delegate to the inner
|
||||
// store via the embedded interface.
|
||||
type stubStore struct {
|
||||
store.TaskStore
|
||||
storecontract.TaskStore
|
||||
workflowStatsErr error
|
||||
stageStatsErr error
|
||||
tokensByDayErr error
|
||||
@@ -75,21 +72,21 @@ func (s *stubStore) Requeue(ctx context.Context, id int64, from, workflow string
|
||||
return s.TaskStore.Requeue(ctx, id, from, workflow)
|
||||
}
|
||||
|
||||
func (s *stubStore) WorkflowStats(ctx context.Context) ([]store.WorkflowStat, error) {
|
||||
func (s *stubStore) WorkflowStats(ctx context.Context) ([]storecontract.WorkflowStat, error) {
|
||||
if s.workflowStatsErr != nil {
|
||||
return nil, s.workflowStatsErr
|
||||
}
|
||||
return s.TaskStore.WorkflowStats(ctx)
|
||||
}
|
||||
|
||||
func (s *stubStore) StageStats(ctx context.Context) ([]store.StageStat, error) {
|
||||
func (s *stubStore) StageStats(ctx context.Context) ([]storecontract.StageStat, error) {
|
||||
if s.stageStatsErr != nil {
|
||||
return nil, s.stageStatsErr
|
||||
}
|
||||
return s.TaskStore.StageStats(ctx)
|
||||
}
|
||||
|
||||
func (s *stubStore) TokensByDay(ctx context.Context, days int) ([]store.DayTokens, error) {
|
||||
func (s *stubStore) TokensByDay(ctx context.Context, days int) ([]storecontract.DayTokens, error) {
|
||||
if s.tokensByDayErr != nil {
|
||||
return nil, s.tokensByDayErr
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user