feat(archied): serve the State Store, event store and Gateway conversations from Postgres
The State Store's task and event-capture stores and the conversation store read by archied and served by archie-gateway now open on database_url. Every serving process refuses to start when legacy SQLite data exists and no import completion is recorded, naming archie-state-store import; a fresh install records completion itself. The Gateway holds its Postgres serve claim for its lifetime and releases it before the pool closes.
This commit is contained in:
18 files changed
+381
-177
No files matched your search
@@ -47,11 +47,11 @@ import (
|
||||
forgewebhook "github.com/samcharles93/archie-core/internal/forge/webhook"
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/configuration"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/edastore"
|
||||
infraembedding "github.com/samcharles93/archie-core/internal/infrastructure/embedding"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/eventbus/nats"
|
||||
infraMemory "github.com/samcharles93/archie-core/internal/infrastructure/memory"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/modelcatalog"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/sessioncurator"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/skillcurator"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/staterpc"
|
||||
@@ -108,13 +108,12 @@ type boot struct {
|
||||
playbooks *playbook.Store
|
||||
|
||||
st storecontract.TaskStore
|
||||
eda *edastore.Store
|
||||
eda eventCaptureStore
|
||||
// pg is the State Store process's process-scoped PostgreSQL pool, opened
|
||||
// and migrated by openStateStorePool. It is the one connection the
|
||||
// standalone archie-state-store binary holds: do not open a second pool
|
||||
// per subsystem. Nil for every process that is not the State Store (the
|
||||
// daemon and gateway dial the State Store over gRPC and never open
|
||||
// Postgres themselves).
|
||||
// per subsystem. Nil for every other process: the daemon and Gateway reach
|
||||
// the State Store over gRPC and hold only the conversation store's pool.
|
||||
pg *pgxpool.Pool
|
||||
// stateStore is the State Store contract adapter every daemon and gateway
|
||||
// store consumer depends on. It is ALWAYS the remote *staterpc.Client
|
||||
@@ -123,7 +122,7 @@ type boot struct {
|
||||
// in-process, per docs/prds/state-store-contract.md §12 step 7). It is set
|
||||
// by openStateStoreAdapter, which requires [services.state].target to be
|
||||
// set. The b.st field remains solely for the standalone archie-state-store
|
||||
// binary, which owns the single SQLite file.
|
||||
// binary, which serves the task store from Postgres.
|
||||
stateStore storecontract.TaskStore
|
||||
// stateStoreGrants issues per-task, scoped State Store credentials for
|
||||
// agent containers (daemon.StateStoreGrantIssuer), wrapping the same
|
||||
@@ -155,6 +154,9 @@ type boot struct {
|
||||
// boot builds both archied and archie-gateway.
|
||||
processName string
|
||||
chatSessionStore gateway.SessionStore
|
||||
// chatPool is the conversation store's pool, which the store owns and
|
||||
// closes; the Gateway also holds its serve claim on it.
|
||||
chatPool *pgxpool.Pool
|
||||
|
||||
catalog modelcatalog.Snapshot
|
||||
catalogModels []string
|
||||
@@ -362,9 +364,8 @@ func (b *boot) openStores(ctx context.Context) error {
|
||||
b.secrets = secrets
|
||||
b.forgeClient, b.token = resolveForge(cfg.Forge, secrets, log)
|
||||
|
||||
// The daemon and gateway no longer open archie.db directly: the single
|
||||
// SQLite file is owned by the standalone archie-state-store process, and
|
||||
// both consumers dial its gRPC State Store contract. openStateStoreAdapter
|
||||
// The daemon and gateway do not serve the State Store's tables: the
|
||||
// standalone archie-state-store process does, and both consumers dial its gRPC State Store contract. openStateStoreAdapter
|
||||
// (called by Run and RunGateway after openStores) resolves b.stateStore as
|
||||
// the remote *staterpc.Client. There is no local store to open here
|
||||
// (docs/prds/state-store-contract.md §12 step 7, no dual-store ownership).
|
||||
@@ -409,11 +410,16 @@ func (b *boot) openStateStoreAdapter() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (b *boot) openChatSessions(_ context.Context) error { //nolint:unparam // context keeps the composition phase contract aligned with other openers
|
||||
chatSessionStore, err := makeTelegramSessionStore(b.cfg) //nolint:contextcheck // SQLite schema initialization is synchronous and has no context-aware API
|
||||
// openChatSessions opens the conversation store on its own pool from
|
||||
// database_url. The daemon reads it (session curator) and the Gateway serves
|
||||
// it; only the Gateway claims serve ownership (claimGatewayOwnership).
|
||||
func (b *boot) openChatSessions(ctx context.Context) error {
|
||||
pool, err := openServicePool(ctx, b.cfg.DatabaseURL, b.cfg.DBPath, "the conversation store")
|
||||
if err != nil {
|
||||
return fmt.Errorf("open conversation store: %w", err)
|
||||
}
|
||||
chatSessionStore := gateway.NewPostgresSessionStore(pool)
|
||||
b.chatPool = pool
|
||||
b.chatSessionStore = chatSessionStore
|
||||
b.addCleanup(func() {
|
||||
if err := chatSessionStore.Close(); err != nil {
|
||||
@@ -423,6 +429,24 @@ func (b *boot) openChatSessions(_ context.Context) error { //nolint:unparam // c
|
||||
return nil
|
||||
}
|
||||
|
||||
// claimGatewayOwnership holds the Gateway's serve claim for the process's
|
||||
// life, so a second Gateway (whose turn recovery would fail this one's
|
||||
// in-flight turns) refuses to start. It runs after openChatSessions, so its
|
||||
// cleanup releases the claim before the conversation store closes the pool.
|
||||
func (b *boot) claimGatewayOwnership(ctx context.Context) error {
|
||||
ownership, err := postgres.AcquireOwnership(ctx, b.chatPool, postgres.OwnerGateway)
|
||||
if err != nil {
|
||||
return fmt.Errorf("claim gateway ownership: %w", err)
|
||||
}
|
||||
releaseCtx := context.WithoutCancel(ctx)
|
||||
b.addCleanup(func() {
|
||||
if err := ownership.Release(releaseCtx); err != nil {
|
||||
b.log.Error("release gateway ownership", "err", err)
|
||||
}
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
// handleRequeue replays a parked/waiting task by id, then signals an
|
||||
// early success exit unless -once keeps the daemon running.
|
||||
func (b *boot) handleRequeue(ctx context.Context, requeue int64, once bool) (bool, error) {
|
||||
@@ -640,7 +664,7 @@ func (b *boot) setupLLMAndChat(ctx context.Context) error {
|
||||
return err
|
||||
}
|
||||
b.addCleanup(cleanup)
|
||||
// Channel routers execute turns locally and need the SQLite TurnLedger.
|
||||
// Channel routers execute turns locally and need the conversation store's TurnLedger.
|
||||
// The remote contract serves web chat; it must not replace their store.
|
||||
b.chat = &webui.ChatService{Contract: contract, Updates: b.updateService}
|
||||
b.setupReadinessProbes()
|
||||
|
||||
@@ -145,11 +145,8 @@ func makeUpdateService(s chatSetup) *releaseupdate.Service {
|
||||
return updates
|
||||
}
|
||||
|
||||
func makeTelegramSessionStore(cfg config.Config) (gateway.SessionStore, error) {
|
||||
return gateway.OpenSQLiteSessionStore(conversationDBPath(cfg.DBPath))
|
||||
}
|
||||
|
||||
// conversationDBPath keeps conversation state in its own SQLite database.
|
||||
// conversationDBPath is the legacy SQLite conversation database the one-time
|
||||
// import reads.
|
||||
func conversationDBPath(taskDBPath string) string {
|
||||
return taskDBPath + "-conversations.sqlite"
|
||||
}
|
||||
|
||||
@@ -7,13 +7,15 @@ import (
|
||||
|
||||
"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) {
|
||||
cfg := config.Config{
|
||||
DBPath: filepath.Join(t.TempDir(), "tasks.db"),
|
||||
Services: config.Services{config.ServiceNameGateway: {Target: "127.0.0.1:1"}},
|
||||
DBPath: filepath.Join(t.TempDir(), "tasks.db"),
|
||||
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 {
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"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/postgres"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgtest"
|
||||
)
|
||||
|
||||
// seedLegacyConversation writes one session into the legacy SQLite
|
||||
// conversation file beside dbPath, which is enough for the cutover gate to
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
|
||||
func testPool(t *testing.T, url string) *pgxpool.Pool {
|
||||
t.Helper()
|
||||
pool, err := postgres.Open(t.Context(), url)
|
||||
if err != nil {
|
||||
t.Fatalf("open pool: %v", err)
|
||||
}
|
||||
t.Cleanup(pool.Close)
|
||||
if err := postgres.Migrate(t.Context(), pool, postgres.Migrations()); err != nil {
|
||||
t.Fatalf("migrate: %v", err)
|
||||
}
|
||||
return pool
|
||||
}
|
||||
|
||||
// TestCutoverGate pins D1.3 in both serving processes: a fresh install boots
|
||||
// and records completion, legacy data without a completed import refuses with
|
||||
// the operator's instruction, and a completed import boots over legacy files.
|
||||
func TestCutoverGate(t *testing.T) {
|
||||
processes := []struct {
|
||||
name string
|
||||
open func(*boot, context.Context) error
|
||||
}{
|
||||
{"state store", func(b *boot, ctx context.Context) error { return b.openStateStorePool(ctx) }},
|
||||
{"gateway", func(b *boot, ctx context.Context) error { return b.openStores(ctx) }},
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
legacy bool
|
||||
complete bool
|
||||
wantErr string
|
||||
}{
|
||||
{name: "fresh install"},
|
||||
{name: "legacy data without import", legacy: true, wantErr: "run `archie-state-store import`"},
|
||||
{name: "legacy data with completed import", legacy: true, complete: true},
|
||||
}
|
||||
for _, p := range processes {
|
||||
for _, tt := range tests {
|
||||
t.Run(p.name+"/"+tt.name, func(t *testing.T) {
|
||||
url := pgtest.URL(t)
|
||||
dbPath := filepath.Join(t.TempDir(), "archie.db")
|
||||
if tt.legacy {
|
||||
seedLegacyConversation(t, dbPath)
|
||||
}
|
||||
pool := testPool(t, url)
|
||||
if tt.complete {
|
||||
if _, err := pool.Exec(t.Context(),
|
||||
"INSERT INTO import_completion (id, sources, report) VALUES (1, 's', 'r')"); err != nil {
|
||||
t.Fatalf("seed completion: %v", err)
|
||||
}
|
||||
}
|
||||
b := newBootstrap()
|
||||
b.cfg = config.Config{DatabaseURL: url, DBPath: dbPath}
|
||||
err := p.open(b, t.Context())
|
||||
b.cleanup()
|
||||
if tt.wantErr != "" {
|
||||
if err == nil || !strings.Contains(err.Error(), tt.wantErr) {
|
||||
t.Fatalf("open = %v, want refusal containing %q", err, tt.wantErr)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("open: %v", err)
|
||||
}
|
||||
done, err := postgres.ImportComplete(t.Context(), pool)
|
||||
if err != nil {
|
||||
t.Fatalf("ImportComplete: %v", err)
|
||||
}
|
||||
if !done {
|
||||
t.Fatal("serving database has no completion record; a later legacy file would block it")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestFreshInstallIgnoresLaterLegacyFile pins the fresh-install record: once a
|
||||
// database started with no legacy data, a stray legacy file does not block it.
|
||||
func TestFreshInstallIgnoresLaterLegacyFile(t *testing.T) {
|
||||
url := pgtest.URL(t)
|
||||
dbPath := filepath.Join(t.TempDir(), "archie.db")
|
||||
first := newBootstrap()
|
||||
first.cfg = config.Config{DatabaseURL: url, DBPath: dbPath}
|
||||
if err := first.openStateStorePool(t.Context()); err != nil {
|
||||
t.Fatalf("fresh start: %v", err)
|
||||
}
|
||||
first.cleanup()
|
||||
seedLegacyConversation(t, dbPath)
|
||||
if _, err := os.Stat(conversationDBPath(dbPath)); err != nil {
|
||||
t.Fatalf("legacy file not written: %v", err)
|
||||
}
|
||||
second := newBootstrap()
|
||||
second.cfg = first.cfg
|
||||
if err := second.openStateStorePool(t.Context()); err != nil {
|
||||
t.Fatalf("restart with a stray legacy file: %v", err)
|
||||
}
|
||||
second.cleanup()
|
||||
}
|
||||
|
||||
// TestGatewayRefusesASecondOwner pins D4.1: one Gateway serves a database, a
|
||||
// second refuses while the first holds its claim, and one starts again once
|
||||
// the first has shut down.
|
||||
func TestGatewayRefusesASecondOwner(t *testing.T) {
|
||||
cfg := config.Config{DatabaseURL: pgtest.URL(t), DBPath: filepath.Join(t.TempDir(), "archie.db")}
|
||||
start := func() (*boot, error) {
|
||||
b := newBootstrap()
|
||||
b.cfg = cfg
|
||||
if err := b.openChatSessions(t.Context()); err != nil {
|
||||
b.cleanup()
|
||||
return nil, err
|
||||
}
|
||||
if err := b.claimGatewayOwnership(t.Context()); err != nil {
|
||||
b.cleanup()
|
||||
return nil, err
|
||||
}
|
||||
return b, nil
|
||||
}
|
||||
first, err := start()
|
||||
if err != nil {
|
||||
t.Fatalf("first gateway: %v", err)
|
||||
}
|
||||
if _, err := start(); !errors.Is(err, postgres.ErrOwned) {
|
||||
first.cleanup()
|
||||
t.Fatalf("second gateway = %v, want ErrOwned", err)
|
||||
}
|
||||
first.cleanup()
|
||||
third, err := start()
|
||||
if err != nil {
|
||||
t.Fatalf("gateway after the owner shut down: %v", err)
|
||||
}
|
||||
third.cleanup()
|
||||
}
|
||||
|
||||
// TestConversationStoreFailsClosedWithoutURL: the conversation store is
|
||||
// Postgres-only, so a missing database_url stops the process.
|
||||
func TestConversationStoreFailsClosedWithoutURL(t *testing.T) {
|
||||
b := newBootstrap()
|
||||
defer b.cleanup()
|
||||
err := b.openChatSessions(t.Context())
|
||||
if err == nil || !strings.Contains(err.Error(), "database_url is required") {
|
||||
t.Fatalf("openChatSessions = %v, want it to name the missing database_url", err)
|
||||
}
|
||||
}
|
||||
@@ -50,10 +50,9 @@ func gatewayListenAndToken(b *boot, options GatewayOptions) (listen, token strin
|
||||
|
||||
// RunGateway owns conversation persistence, model runtime and tool-provider
|
||||
// lifecycles. Task-store adapters access the State Store contract (remote
|
||||
// *staterpc.Client via [services.state].target), not archie.db directly: the
|
||||
// single SQLite file is owned by archie-state-store, and the Gateway keeps its
|
||||
// own already-separate session SQLite (docs/prds/state-store-contract.md §12
|
||||
// step 8), which is out of state-store scope.
|
||||
// *staterpc.Client via [services.state].target). The Gateway serves the
|
||||
// conversation store from database_url and holds the Gateway serve claim for
|
||||
// its whole life.
|
||||
func RunGateway(ctx context.Context, options GatewayOptions) error {
|
||||
b := newBootstrap()
|
||||
b.processName = applystatus.Gateway
|
||||
@@ -68,7 +67,6 @@ func RunGateway(ctx context.Context, options GatewayOptions) error {
|
||||
// The Gateway also no longer opens archie.db directly: it consumes the
|
||||
// same remote State Store contract the daemon does via
|
||||
// [services.state].target (docs/prds/state-store-contract.md §12 step 7).
|
||||
// Its own session SQLite is untouched and stays Gateway-owned.
|
||||
if err := b.openGatewayState(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -127,6 +125,9 @@ func RunGateway(ctx context.Context, options GatewayOptions) error {
|
||||
}
|
||||
|
||||
func (b *boot) openGatewayState(ctx context.Context) error {
|
||||
if err := b.claimGatewayOwnership(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := b.openStateStoreAdapter(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// state_store.go composes the standalone archie-state-store process. It mirrors
|
||||
// gateway.go / cmd/archie-gateway: the binary is a thin main that passes
|
||||
// process inputs into RunStateStore, which owns the single archie.db SQLite
|
||||
// file, registers every StateStore gRPC handler (the same service .4.2 serves
|
||||
// process inputs into RunStateStore, which serves the task and event-capture
|
||||
// stores from Postgres, registers every StateStore gRPC handler (the same service .4.2 serves
|
||||
// in-process on the daemon), and shuts down cleanly on ctx cancellation.
|
||||
//
|
||||
// See docs/prds/state-store-contract.md (rev. 2c) -- the single authoritative
|
||||
@@ -66,11 +66,10 @@ type StateStoreOptions struct {
|
||||
ReadyAddr string
|
||||
}
|
||||
|
||||
// RunStateStore owns the single archie.db SQLite file, registers every
|
||||
// StateStore gRPC handler, and serves until ctx is cancelled. It opens only
|
||||
// the task store -- the gateway's session SQLite is owned by the separate
|
||||
// archie-gateway process and is deliberately untouched (state-store-contract
|
||||
// rev. 2c §12 step 8). The store service owns its own DB lifecycle, so
|
||||
// RunStateStore serves the task and event-capture stores from Postgres,
|
||||
// registers every StateStore gRPC handler, and serves until ctx is cancelled.
|
||||
// The conversation store belongs to the separate archie-gateway process. The
|
||||
// store service owns its own DB lifecycle, so
|
||||
// b.cleanup() is the sole owner closing b.st here (in-process owner).
|
||||
func RunStateStore(ctx context.Context, options StateStoreOptions) error {
|
||||
b := newBootstrap()
|
||||
@@ -186,7 +185,8 @@ func openStateStoreControlPlane(resources controlplane.ResourceStore) (*controlp
|
||||
|
||||
// openStateStore composes the State Store process's persistence: it resolves
|
||||
// secrets (for the binding cipher), opens and migrates the process-scoped
|
||||
// PostgreSQL pool (fail closed), and opens the task and event-capture stores.
|
||||
// PostgreSQL pool (fail closed), and serves the task and event-capture stores
|
||||
// from it.
|
||||
// It does NOT open gateway chat sessions -- those live in the separate
|
||||
// archie-gateway process on their own store and are out of state-store scope.
|
||||
func (b *boot) openStateStore(ctx context.Context) error {
|
||||
@@ -207,12 +207,8 @@ func (b *boot) openStateStore(ctx context.Context) error {
|
||||
if err := b.openStateStorePool(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := b.openTaskStore(ctx, taskDBPath(cfg.DBPath)); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := b.openEDAStore(cfg, bindingCipher); err != nil {
|
||||
return err
|
||||
}
|
||||
b.openTaskStore()
|
||||
b.openEDAStore(bindingCipher)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -249,8 +245,8 @@ func (b *boot) stateStoreDeps(grants *staterpc.TaskGrants) staterpc.Deps {
|
||||
if b.taskLogs != nil {
|
||||
deps.TaskLogs = b.taskLogs
|
||||
}
|
||||
// The event-capture contracts are served by the PocketBase store, not the
|
||||
// task store: those tables moved. BindingTaskCreator stays below on the
|
||||
// The event-capture contracts are served by the event-capture store, not
|
||||
// the task store. BindingTaskCreator stays below on the
|
||||
// task store, because creating a task is the one thing it still does.
|
||||
if b.eda != nil {
|
||||
deps.Captures = b.eda
|
||||
|
||||
@@ -1,33 +1,24 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/edastore"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres"
|
||||
)
|
||||
|
||||
// openEDAStore opens the event-capture store (PocketBase today, Postgres when
|
||||
// L2 ports it) beside the task database. It is a separate composition file
|
||||
// from openTaskStore so L2 can replace edastore.Open here without colliding
|
||||
// with L1's replacement of openProductionTaskStore -- the two lanes write
|
||||
// different files.
|
||||
func (b *boot) openEDAStore(cfg config.Config, cipher edastore.BindingCipher) error {
|
||||
path := taskDBPath(cfg.DBPath)
|
||||
eda, err := edastore.Open(edastore.Config{
|
||||
DBPath: edaDBPath(cfg.DBPath),
|
||||
DataDir: filepath.Join(filepath.Dir(path), "eda"),
|
||||
Cipher: cipher,
|
||||
})
|
||||
if err != nil {
|
||||
b.log.Error("open event-capture store", "err", err)
|
||||
return err
|
||||
}
|
||||
b.eda = eda
|
||||
b.addCleanup(func() {
|
||||
if err := eda.Close(); err != nil {
|
||||
b.log.Error("close event-capture store", "err", err)
|
||||
}
|
||||
})
|
||||
return nil
|
||||
// eventCaptureStore is every surface the State Store serves from the
|
||||
// event-capture tables, plus the tool_call projection it writes through.
|
||||
type eventCaptureStore interface {
|
||||
storecontract.CaptureStore
|
||||
storecontract.MappingStore
|
||||
storecontract.BindingStore
|
||||
storecontract.BindingDispatcher
|
||||
storecontract.PlaybookDispatcher
|
||||
toolCallWriter
|
||||
}
|
||||
|
||||
// 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) {
|
||||
b.eda = postgres.NewEDA(b.pg, cipher)
|
||||
}
|
||||
@@ -2,40 +2,30 @@ package archied
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/legacyimport"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres"
|
||||
)
|
||||
|
||||
// openStateStorePool opens the State Store process's one process-scoped
|
||||
// PostgreSQL pool and applies the schema. It is the fail-closed seam for the
|
||||
// Postgres-only epic: a missing or invalid database_url stops the State Store
|
||||
// from starting rather than falling back to SQLite, and a migration failure is
|
||||
// a startup failure, not a warning.
|
||||
//
|
||||
// It then claims serve ownership of the database for the process's life, so a
|
||||
// second State Store against the same database refuses to start.
|
||||
// PostgreSQL pool, applies the schema and claims serve ownership of the
|
||||
// database for the process's life, so a second State Store against the same
|
||||
// database refuses to start. A missing or invalid database_url, a migration
|
||||
// failure or unimported legacy data is a startup failure.
|
||||
//
|
||||
// The pool is stored on boot.pg and closed at shutdown; nothing opens a second
|
||||
// pool per subsystem.
|
||||
func (b *boot) openStateStorePool(ctx context.Context) error {
|
||||
url := b.cfg.DatabaseURL
|
||||
if url == "" {
|
||||
err := errors.New("database_url is required: the State Store is Postgres-only and refuses to fall back to SQLite")
|
||||
b.log.Error("open state store postgres pool", "err", err)
|
||||
return err
|
||||
}
|
||||
pool, err := postgres.Open(ctx, url)
|
||||
pool, err := openServicePool(ctx, b.cfg.DatabaseURL, b.cfg.DBPath, "the State Store")
|
||||
if err != nil {
|
||||
b.log.Error("open state store postgres pool", "err", err)
|
||||
return err
|
||||
}
|
||||
if err := postgres.Migrate(ctx, pool, postgres.Migrations()); err != nil {
|
||||
pool.Close()
|
||||
b.log.Error("migrate state store postgres schema", "err", err)
|
||||
return err
|
||||
}
|
||||
ownership, err := postgres.AcquireOwnership(ctx, pool, "state-store")
|
||||
ownership, err := postgres.AcquireOwnership(ctx, pool, postgres.OwnerStateStore)
|
||||
if err != nil {
|
||||
pool.Close()
|
||||
b.log.Error("claim state store ownership", "err", err)
|
||||
@@ -49,3 +39,48 @@ func (b *boot) openStateStorePool(ctx context.Context) error {
|
||||
b.addCleanup(func() { _ = ownership.Release(releaseCtx) })
|
||||
return nil
|
||||
}
|
||||
|
||||
// openServicePool opens and migrates a serving process's pool and refuses to
|
||||
// serve over legacy data the one-time import has not moved. service names the
|
||||
// process in the error an operator reads.
|
||||
func openServicePool(ctx context.Context, url, dbPath, service string) (*pgxpool.Pool, error) {
|
||||
if url == "" {
|
||||
return nil, fmt.Errorf("database_url is required: %s is Postgres-only and refuses to fall back to SQLite", service)
|
||||
}
|
||||
pool, err := postgres.Open(ctx, url)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := postgres.Migrate(ctx, pool, postgres.Migrations()); err != nil {
|
||||
pool.Close()
|
||||
return nil, err
|
||||
}
|
||||
if err := refuseUnimportedLegacy(ctx, pool, dbPath); err != nil {
|
||||
pool.Close()
|
||||
return nil, err
|
||||
}
|
||||
return pool, nil
|
||||
}
|
||||
|
||||
// refuseUnimportedLegacy is the cutover gate. A database with a completion
|
||||
// record serves. Otherwise non-empty legacy SQLite files mean an upgrade whose
|
||||
// import has not run, and serving would hide that data behind empty tables,
|
||||
// so it refuses. With no legacy data it is a fresh install: the completion
|
||||
// record is written so a legacy file that appears later cannot block it.
|
||||
func refuseUnimportedLegacy(ctx context.Context, pool *pgxpool.Pool, dbPath string) error {
|
||||
done, err := postgres.ImportComplete(ctx, pool)
|
||||
if err != nil || done {
|
||||
return err
|
||||
}
|
||||
sources := legacySources(dbPath)
|
||||
has, err := legacyimport.HasLegacyData(ctx, sources)
|
||||
if err != nil {
|
||||
return fmt.Errorf("check for legacy SQLite data: %w", err)
|
||||
}
|
||||
if has {
|
||||
return fmt.Errorf("legacy SQLite data found (%s) but this Postgres database has no completed import: "+
|
||||
"stop every archie process, run `archie-state-store import`, then start archie again",
|
||||
strings.Join([]string{sources.StateStore, sources.EDA, sources.Gateway}, ", "))
|
||||
}
|
||||
return postgres.RecordFreshInstall(ctx, pool)
|
||||
}
|
||||
@@ -1,39 +1,13 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres"
|
||||
)
|
||||
|
||||
// openTaskStore claims ownership of the task database and opens the production
|
||||
// task store. The ownership claim is what makes "the State Store is stopped" a
|
||||
// fact an offline recovery command can check, and a second State Store on the
|
||||
// same database fails here. It is a separate composition file from openEDAStore
|
||||
// so L1 can replace openProductionTaskStore (and the ownership claim, per the
|
||||
// serve-ownership decision) here without colliding with L2's edastore port.
|
||||
func (b *boot) openTaskStore(ctx context.Context, path string) error {
|
||||
ownership, err := store.AcquireOwnership(path)
|
||||
if err != nil {
|
||||
b.log.Error("claim state store ownership", "err", err)
|
||||
return err
|
||||
}
|
||||
b.addCleanup(func() {
|
||||
if err := ownership.Release(); err != nil {
|
||||
b.log.Error("release state store ownership", "err", err)
|
||||
}
|
||||
})
|
||||
|
||||
st, err := openProductionTaskStore(ctx, path)
|
||||
if err != nil {
|
||||
b.log.Error("open state store", "err", err)
|
||||
return err
|
||||
}
|
||||
b.st = st
|
||||
b.addCleanup(func() {
|
||||
if err := st.Close(); err != nil {
|
||||
b.log.Error("close state store", "err", err)
|
||||
}
|
||||
})
|
||||
return nil
|
||||
// openTaskStore serves the task store from the State Store's Postgres pool.
|
||||
// Serve ownership is the pool's claim (openStateStorePool), so a second State
|
||||
// Store on the same database already failed before this runs, and the pool's
|
||||
// cleanup closes what this store reads through.
|
||||
func (b *boot) openTaskStore() {
|
||||
b.st = postgres.New(b.pg)
|
||||
}
|
||||
@@ -213,7 +213,7 @@ func TestStateStoreDataSurvivesRestart(t *testing.T) {
|
||||
// this would mean archie.db is opened by two processes at once.
|
||||
func TestOpenStoresNeverOwnsTaskDB(t *testing.T) {
|
||||
b := newBootstrap()
|
||||
b.cfg = config.Config{DBPath: filepath.Join(t.TempDir(), "archie")}
|
||||
b.cfg = config.Config{DBPath: filepath.Join(t.TempDir(), "archie"), DatabaseURL: pgtest.URL(t)}
|
||||
if err := b.openStores(t.Context()); err != nil {
|
||||
t.Fatalf("openStores: %v", err)
|
||||
}
|
||||
|
||||
@@ -1,41 +0,0 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
)
|
||||
|
||||
func TestTelegramConversationStoreUsesFreshSQLiteWithoutReadingTaskLog(t *testing.T) {
|
||||
taskLogPath := filepath.Join(t.TempDir(), "tasks.db")
|
||||
taskLog := []byte("not a SQLite database")
|
||||
if err := os.WriteFile(taskLogPath, taskLog, 0o600); err != nil {
|
||||
t.Fatalf("write task log fixture: %v", err)
|
||||
}
|
||||
|
||||
sessions, err := makeTelegramSessionStore(config.Config{
|
||||
DBPath: taskLogPath,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("makeTelegramSessionStore: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = sessions.Close() })
|
||||
|
||||
if got, want := fmt.Sprintf("%T", sessions), "*gateway.sqliteSessionStore"; got != want {
|
||||
t.Fatalf("conversation store type = %q, want %q", got, want)
|
||||
}
|
||||
if _, err := os.Stat(conversationDBPath(taskLogPath)); err != nil {
|
||||
t.Fatalf("stat conversation database: %v", err)
|
||||
}
|
||||
gotTaskLog, err := os.ReadFile(taskLogPath)
|
||||
if err != nil {
|
||||
t.Fatalf("read task log fixture: %v", err)
|
||||
}
|
||||
if !bytes.Equal(gotTaskLog, taskLog) {
|
||||
t.Fatalf("task log changed during conversation-store cutover: got %q, want %q", gotTaskLog, taskLog)
|
||||
}
|
||||
}
|
||||
@@ -27,3 +27,13 @@ func ImportComplete(ctx context.Context, pool *pgxpool.Pool) (bool, error) {
|
||||
}
|
||||
return done, nil
|
||||
}
|
||||
|
||||
// RecordFreshInstall writes the completion record for a database that starts
|
||||
// with no legacy data to import, so a legacy file that appears later cannot
|
||||
// block it from serving. It leaves an existing record untouched.
|
||||
func RecordFreshInstall(ctx context.Context, pool *pgxpool.Pool) error {
|
||||
if err := postgresdb.New(pool).InsertFreshInstallCompletion(ctx); err != nil {
|
||||
return fmt.Errorf("postgres: fresh install completion: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -20,6 +20,16 @@ func (q *Queries) ImportCompleted(ctx context.Context) (bool, error) {
|
||||
return exists, err
|
||||
}
|
||||
|
||||
const insertFreshInstallCompletion = `-- name: InsertFreshInstallCompletion :exec
|
||||
INSERT INTO import_completion (id, sources, report) VALUES (1, '', 'fresh install: no legacy data')
|
||||
ON CONFLICT (id) DO NOTHING
|
||||
`
|
||||
|
||||
func (q *Queries) InsertFreshInstallCompletion(ctx context.Context) error {
|
||||
_, err := q.db.Exec(ctx, insertFreshInstallCompletion)
|
||||
return err
|
||||
}
|
||||
|
||||
const insertImportCompletion = `-- name: InsertImportCompletion :exec
|
||||
|
||||
INSERT INTO import_completion (id, sources, report) VALUES (1, $1, $2)
|
||||
|
||||
@@ -5,3 +5,7 @@ INSERT INTO import_completion (id, sources, report) VALUES (1, $1, $2);
|
||||
|
||||
-- name: ImportCompleted :one
|
||||
SELECT EXISTS (SELECT 1 FROM import_completion);
|
||||
|
||||
-- name: InsertFreshInstallCompletion :exec
|
||||
INSERT INTO import_completion (id, sources, report) VALUES (1, '', 'fresh install: no legacy data')
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
Reference in new issue
Block a user