diff --git a/cmd/archie-state-store/main_test.go b/cmd/archie-state-store/main_test.go index 6546c38c0..a11b0c99d 100644 --- a/cmd/archie-state-store/main_test.go +++ b/cmd/archie-state-store/main_test.go @@ -372,8 +372,8 @@ func TestStateStoreRealProcessSmoke(t *testing.T) { }); err != nil { t.Fatalf("InsertEvent config_captured: %v", err) } - if capID, err := cl.InsertCapture(ctx, capture("sentry", `{"id":1}`), 0, 0); err != nil || capID == 0 { - t.Fatalf("InsertCapture = (%d, %v)", capID, err) + if capID, err := cl.InsertCapture(ctx, capture("sentry", `{"id":1}`), 0, 0); err != nil || capID == "" { + t.Fatalf("InsertCapture = (%q, %v)", capID, err) } got, err := cl.TaskByID(ctx, task.ID) @@ -583,8 +583,8 @@ func TestStateStoreRealProcessRemoteSurfaces(t *testing.T) { ctx := t.Context() mappingID, err := cl.InsertMapping(ctx, mapping.Mapping{Name: "m1", Fields: []mapping.Field{{Name: "a", Path: "a", Type: mapping.TypeString}}}) - if err != nil || mappingID == 0 { - t.Fatalf("InsertMapping = (%d, %v)", mappingID, err) + if err != nil || mappingID == "" { + t.Fatalf("InsertMapping = (%q, %v)", mappingID, err) } if got, err := cl.GetMapping(ctx, mappingID); err != nil || got == nil || got.Name != "m1" { t.Fatalf("GetMapping = %+v, %v", got, err) @@ -593,8 +593,8 @@ func TestStateStoreRealProcessRemoteSurfaces(t *testing.T) { Name: "b1", Matcher: binding.Matcher{Source: "sentry"}, MappingID: mappingID, Workflow: "implement", Secret: "0123456789abcdef0123456789abcdef", }) - if err != nil || bindingID == 0 { - t.Fatalf("InsertBinding = (%d, %v)", bindingID, err) + if err != nil || bindingID == "" { + t.Fatalf("InsertBinding = (%q, %v)", bindingID, err) } // A binding starts as draft and must be edited (draft -> pending_approval) // then approved (pending_approval -> armed) before it is armed for a @@ -613,7 +613,7 @@ func TestStateStoreRealProcessRemoteSurfaces(t *testing.T) { t.Fatalf("ArmedBindingsForSource = %+v, %v", armed, err) } // Remote surfaces share error-sentinel fidelity on the wire too. - missing := mapping.Mapping{ID: mappingID + 999999, Name: "x", Fields: []mapping.Field{{Name: "a", Path: "a", Type: mapping.TypeString}}} + missing := mapping.Mapping{ID: "rabsent00000000", Name: "x", Fields: []mapping.Field{{Name: "a", Path: "a", Type: mapping.TypeString}}} if err := cl.UpdateMapping(ctx, missing); !errors.Is(err, store.ErrMappingNotFound) { t.Fatalf("UpdateMapping missing = %v, want ErrMappingNotFound", err) } diff --git a/cmd/archie-ui/main_test.go b/cmd/archie-ui/main_test.go index fc8fc2cee..60a902064 100644 --- a/cmd/archie-ui/main_test.go +++ b/cmd/archie-ui/main_test.go @@ -37,6 +37,7 @@ import ( "github.com/samcharles93/archie-core/internal/domain/health" "github.com/samcharles93/archie-core/internal/domain/messaging" "github.com/samcharles93/archie-core/internal/domain/taskactions" + "github.com/samcharles93/archie-core/internal/infrastructure/edastore" "github.com/samcharles93/archie-core/internal/infrastructure/gatewayrpc" "github.com/samcharles93/archie-core/internal/infrastructure/staterpc" "github.com/samcharles93/archie-core/internal/store" @@ -601,8 +602,9 @@ func TestUIProcessLinksMultiIdentityTaskRowsToTheirOwningForge(t *testing.T) { } stateTarget, stopState := serveGRPC(t, func(r grpc.ServiceRegistrar) { + eda := edastore.OpenTest(t) staterpc.RegisterServer(r, staterpc.Deps{ - Tasks: st, Captures: st, BindingDispatcher: st, ConfigSnapshots: st, + Tasks: st, Captures: eda, BindingDispatcher: eda, ConfigSnapshots: st, Log: slog.New(slog.DiscardHandler), }) }) @@ -657,8 +659,9 @@ func TestUIProcessServesTheDashboardAgainstLiveDependencies(t *testing.T) { gateway := &fakeGateway{} stateTarget, stopState := serveGRPC(t, func(r grpc.ServiceRegistrar) { + eda := edastore.OpenTest(t) staterpc.RegisterServer(r, staterpc.Deps{ - Tasks: st, Captures: st, BindingDispatcher: st, ConfigSnapshots: st, + Tasks: st, Captures: eda, BindingDispatcher: eda, ConfigSnapshots: st, Log: slog.New(slog.DiscardHandler), }) }) diff --git a/internal/app/agentworker/task_execution_test.go b/internal/app/agentworker/task_execution_test.go index a4933d388..208e6e043 100644 --- a/internal/app/agentworker/task_execution_test.go +++ b/internal/app/agentworker/task_execution_test.go @@ -30,6 +30,7 @@ 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/staterpc" "github.com/samcharles93/archie-core/internal/infrastructure/workflowsteps" "github.com/samcharles93/archie-core/internal/installtype" @@ -376,9 +377,10 @@ func startStateStoreGRPC(t *testing.T, local *store.Store) string { t.Fatal(err) } server := grpc.NewServer() + eda := edastore.OpenTest(t) staterpc.RegisterServer(server, staterpc.Deps{ - Tasks: local, Captures: local, Mappings: local, Bindings: local, - BindingDispatcher: local, BindingTaskCreator: local, + Tasks: local, Captures: eda, Mappings: eda, Bindings: eda, + BindingDispatcher: eda, BindingTaskCreator: local, }) go func() { _ = server.Serve(listener) }() t.Cleanup(func() { server.Stop(); _ = listener.Close() }) diff --git a/internal/app/archied/binding_cipher.go b/internal/app/archied/binding_cipher.go index b5fc1f465..bbec81d1a 100644 --- a/internal/app/archied/binding_cipher.go +++ b/internal/app/archied/binding_cipher.go @@ -5,15 +5,15 @@ import ( "strings" "github.com/samcharles93/archie-core/internal/config" + "github.com/samcharles93/archie-core/internal/infrastructure/edastore" "github.com/samcharles93/archie-core/internal/secret" - "github.com/samcharles93/archie-core/internal/store" ) // bindingCipherFromConfig resolves the binding at-rest encryption key from -// config through the secret registry and returns a store cipher. An unset +// 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) (store.BindingCipher, error) { +func bindingCipherFromConfig(cfg config.Config, secrets *secret.Registry) (edastore.BindingCipher, error) { if cfg.Bindings.EncryptionKey == (secret.SecretRef{}) { return nil, nil } @@ -36,5 +36,5 @@ func bindingCipherFromConfig(cfg config.Config, secrets *secret.Registry) (store previous = append(previous, v) } } - return store.NewBindingCipher(active, previous) + return edastore.NewBindingCipher(active, previous) } diff --git a/internal/app/archied/bootstrap.go b/internal/app/archied/bootstrap.go index 72e526297..9480f9269 100644 --- a/internal/app/archied/bootstrap.go +++ b/internal/app/archied/bootstrap.go @@ -46,6 +46,7 @@ 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" @@ -105,7 +106,8 @@ type boot struct { playbooks *playbook.Store - st storecontract.TaskStore + st storecontract.TaskStore + eda *edastore.Store // stateStore is the State Store contract adapter every daemon and gateway // store consumer depends on. It is ALWAYS the remote *staterpc.Client // dialed to the standalone archie-state-store gRPC service at diff --git a/internal/app/archied/state_store.go b/internal/app/archied/state_store.go index 7b6ca1498..1756b2506 100644 --- a/internal/app/archied/state_store.go +++ b/internal/app/archied/state_store.go @@ -25,6 +25,7 @@ import ( "github.com/samcharles93/archie-core/internal/domain/health" "github.com/samcharles93/archie-core/internal/domain/identity" "github.com/samcharles93/archie-core/internal/domain/storecontract" + "github.com/samcharles93/archie-core/internal/infrastructure/edastore" "github.com/samcharles93/archie-core/internal/infrastructure/readiness" "github.com/samcharles93/archie-core/internal/infrastructure/stateadmin" "github.com/samcharles93/archie-core/internal/infrastructure/staterpc" @@ -46,6 +47,11 @@ func configuredIdentityNames(cfg config.Config) []string { return names } +// edaDBPath derives the event-capture database from the configured db_path, +// beside the task database rather than inside it: the two stores have separate +// lifecycles and only meet at binding_dispatches.task_id. +func edaDBPath(configuredPath string) string { return configuredPath + "-eda.sqlite" } + // StateStoreOptions contains process inputs for the standalone State Store. type StateStoreOptions struct { Config string @@ -221,7 +227,23 @@ func (b *boot) openStateStore(ctx context.Context) error { log.Error("release state store ownership", "err", err) } }) - st, err := openProductionTaskStore(ctx, path, store.WithBindingCipher(bindingCipher)) + eda, err := edastore.Open(edastore.Config{ + DBPath: edaDBPath(cfg.DBPath), + DataDir: filepath.Join(filepath.Dir(path), "eda"), + Cipher: bindingCipher, + }) + if err != nil { + log.Error("open event-capture store", "err", err) + return err + } + b.eda = eda + b.addCleanup(func() { + if err := eda.Close(); err != nil { + log.Error("close event-capture store", "err", err) + } + }) + + st, err := openProductionTaskStore(ctx, path) if err != nil { log.Error("open state store", "err", err) return err @@ -268,20 +290,15 @@ func (b *boot) stateStoreDeps(grants *staterpc.TaskGrants) staterpc.Deps { if b.taskLogs != nil { deps.TaskLogs = b.taskLogs } - if cs, ok := b.st.(storecontract.CaptureStore); ok { - deps.Captures = cs - } - if ms, ok := b.st.(storecontract.MappingStore); ok { - deps.Mappings = ms - } - if bs, ok := b.st.(storecontract.BindingStore); ok { - deps.Bindings = bs - } - if bd, ok := b.st.(storecontract.BindingDispatcher); ok { - deps.BindingDispatcher = bd - } - if pd, ok := b.st.(storecontract.PlaybookDispatcher); ok { - deps.PlaybookDispatcher = pd + // The event-capture contracts are served by the PocketBase store, not the + // task store: those tables moved. 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 + deps.Mappings = b.eda + deps.Bindings = b.eda + deps.BindingDispatcher = b.eda + deps.PlaybookDispatcher = b.eda } if btc, ok := b.st.(storecontract.BindingTaskCreator); ok { deps.BindingTaskCreator = btc diff --git a/internal/app/archied/state_store_consumers_test.go b/internal/app/archied/state_store_consumers_test.go index bc2e8f408..a0cbb6c3e 100644 --- a/internal/app/archied/state_store_consumers_test.go +++ b/internal/app/archied/state_store_consumers_test.go @@ -6,6 +6,7 @@ import ( "testing" "github.com/samcharles93/archie-core/internal/config" + "github.com/samcharles93/archie-core/internal/infrastructure/edastore" taskactionstore "github.com/samcharles93/archie-core/internal/infrastructure/taskactions" "github.com/samcharles93/archie-core/internal/store" ) @@ -15,14 +16,33 @@ import ( // 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. -func openSecondStore(t *testing.T) *store.Store { +// 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 +// 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 +} + +// 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) } t.Cleanup(func() { _ = st.Close() }) - return st + return &stateStoreAdapter{Store: st, edaSide: edastore.OpenTest(t)} } // TestBuildDaemonRoutesTaskStoreThroughStateStore proves the daemon's task diff --git a/internal/app/archied/state_store_test.go b/internal/app/archied/state_store_test.go index d9007b16c..363a2b9f4 100644 --- a/internal/app/archied/state_store_test.go +++ b/internal/app/archied/state_store_test.go @@ -12,6 +12,7 @@ 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/staterpc" "github.com/samcharles93/archie-core/internal/logging" "github.com/samcharles93/archie-core/internal/store" @@ -145,12 +146,16 @@ func TestStateStoreDepsServePlaybookDispatcher(t *testing.T) { 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) + 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(st) { - t.Fatalf("PlaybookDispatcher = %T, want the opened *store.Store", deps.PlaybookDispatcher) + if deps.PlaybookDispatcher != storecontract.PlaybookDispatcher(eda) { + t.Fatalf("PlaybookDispatcher = %T, want the opened *edastore.Store", 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. diff --git a/internal/app/archieui/degraded_routes_test.go b/internal/app/archieui/degraded_routes_test.go index 91301a15d..ac245e04a 100644 --- a/internal/app/archieui/degraded_routes_test.go +++ b/internal/app/archieui/degraded_routes_test.go @@ -13,6 +13,7 @@ import ( "google.golang.org/grpc" + "github.com/samcharles93/archie-core/internal/infrastructure/edastore" "github.com/samcharles93/archie-core/internal/infrastructure/staterpc" "github.com/samcharles93/archie-core/internal/logging" "github.com/samcharles93/archie-core/internal/store" @@ -165,8 +166,9 @@ 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) staterpc.RegisterServer(r, staterpc.Deps{ - Tasks: st, Captures: st, BindingDispatcher: st, ConfigSnapshots: st, + Tasks: st, Captures: eda, BindingDispatcher: eda, ConfigSnapshots: st, TaskLogs: logs, Log: slog.New(slog.DiscardHandler), }) }) diff --git a/internal/app/archieui/run_test.go b/internal/app/archieui/run_test.go index 811b05cc7..47529eecb 100644 --- a/internal/app/archieui/run_test.go +++ b/internal/app/archieui/run_test.go @@ -21,6 +21,7 @@ import ( "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/staterpc" "github.com/samcharles93/archie-core/internal/store" @@ -151,7 +152,8 @@ func TestUIServesDashboardAgainstRemoteContracts(t *testing.T) { } stateTarget, stopState := serveGRPC(t, func(r grpc.ServiceRegistrar) { - staterpc.RegisterServer(r, staterpc.Deps{Tasks: st, Captures: st, BindingDispatcher: st, ConfigSnapshots: st, Log: slog.New(slog.DiscardHandler)}) + eda := edastore.OpenTest(t) + staterpc.RegisterServer(r, staterpc.Deps{Tasks: st, Captures: eda, BindingDispatcher: eda, ConfigSnapshots: st, Log: slog.New(slog.DiscardHandler)}) }) defer stopState() chat := &fakeChat{sessions: []gateway.SessionContext{ diff --git a/internal/app/archieui/task_logs_test.go b/internal/app/archieui/task_logs_test.go index 0dc85afb6..dffa54f2e 100644 --- a/internal/app/archieui/task_logs_test.go +++ b/internal/app/archieui/task_logs_test.go @@ -13,6 +13,7 @@ import ( "google.golang.org/grpc" + "github.com/samcharles93/archie-core/internal/infrastructure/edastore" "github.com/samcharles93/archie-core/internal/infrastructure/staterpc" "github.com/samcharles93/archie-core/internal/logging" "github.com/samcharles93/archie-core/internal/store" @@ -178,8 +179,9 @@ func composeUIProcessWithLog(t *testing.T) (*webui.Server, int64, int) { } target, stop := serveGRPC(t, func(r grpc.ServiceRegistrar) { + eda := edastore.OpenTest(t) staterpc.RegisterServer(r, staterpc.Deps{ - Tasks: st, Captures: st, BindingDispatcher: st, ConfigSnapshots: st, + Tasks: st, Captures: eda, BindingDispatcher: eda, ConfigSnapshots: st, TaskLogs: logs, Log: slog.New(slog.DiscardHandler), }) }) diff --git a/internal/contracts/state/v1/state.pb.go b/internal/contracts/state/v1/state.pb.go index f8231fd85..d96463dec 100644 --- a/internal/contracts/state/v1/state.pb.go +++ b/internal/contracts/state/v1/state.pb.go @@ -1288,7 +1288,7 @@ type Task struct { WatchCommentId int64 `protobuf:"varint,20,opt,name=watch_comment_id,json=watchCommentId,proto3" json:"watch_comment_id,omitempty"` Source string `protobuf:"bytes,21,opt,name=source,proto3" json:"source,omitempty"` Identity string `protobuf:"bytes,22,opt,name=identity,proto3" json:"identity,omitempty"` - BindingId int64 `protobuf:"varint,23,opt,name=binding_id,json=bindingId,proto3" json:"binding_id,omitempty"` + BindingId string `protobuf:"bytes,23,opt,name=binding_id,json=bindingId,proto3" json:"binding_id,omitempty"` BindingVersion int64 `protobuf:"varint,24,opt,name=binding_version,json=bindingVersion,proto3" json:"binding_version,omitempty"` CreatedAt *timestamppb.Timestamp `protobuf:"bytes,25,opt,name=created_at,json=createdAt,proto3" json:"created_at,omitempty"` UpdatedAt *timestamppb.Timestamp `protobuf:"bytes,26,opt,name=updated_at,json=updatedAt,proto3" json:"updated_at,omitempty"` @@ -1490,11 +1490,11 @@ func (x *Task) GetIdentity() string { return "" } -func (x *Task) GetBindingId() int64 { +func (x *Task) GetBindingId() string { if x != nil { return x.BindingId } - return 0 + return "" } func (x *Task) GetBindingVersion() int64 { @@ -1711,7 +1711,7 @@ func (x *Event) GetPrincipalId() string { // CapturedEvent mirrors internal/store.CapturedEvent. type CapturedEvent struct { state protoimpl.MessageState `protogen:"open.v1"` - Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` + Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` ReceivedAt *timestamppb.Timestamp `protobuf:"bytes,2,opt,name=received_at,json=receivedAt,proto3" json:"received_at,omitempty"` Source string `protobuf:"bytes,3,opt,name=source,proto3" json:"source,omitempty"` RemoteAddr string `protobuf:"bytes,4,opt,name=remote_addr,json=remoteAddr,proto3" json:"remote_addr,omitempty"` @@ -1753,11 +1753,11 @@ func (*CapturedEvent) Descriptor() ([]byte, []int) { return file_state_v1_state_proto_rawDescGZIP(), []int{26} } -func (x *CapturedEvent) GetId() int64 { +func (x *CapturedEvent) GetId() string { if x != nil { return x.Id } - return 0 + return "" } func (x *CapturedEvent) GetReceivedAt() *timestamppb.Timestamp { @@ -1881,7 +1881,7 @@ func (x *MappingField) GetRequired() bool { // Mapping mirrors internal/domain/mapping.Mapping. type Mapping struct { state protoimpl.MessageState `protogen:"open.v1"` - Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` + Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"` SourceHint string `protobuf:"bytes,3,opt,name=source_hint,json=sourceHint,proto3" json:"source_hint,omitempty"` Fields []*MappingField `protobuf:"bytes,4,rep,name=fields,proto3" json:"fields,omitempty"` @@ -1921,11 +1921,11 @@ func (*Mapping) Descriptor() ([]byte, []int) { return file_state_v1_state_proto_rawDescGZIP(), []int{28} } -func (x *Mapping) GetId() int64 { +func (x *Mapping) GetId() string { if x != nil { return x.Id } - return 0 + return "" } func (x *Mapping) GetName() string { @@ -2011,10 +2011,10 @@ func (x *BindingMatcher) GetSource() string { // Binding mirrors internal/domain/binding.Binding. type Binding struct { state protoimpl.MessageState `protogen:"open.v1"` - Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` + Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"` Matcher *BindingMatcher `protobuf:"bytes,3,opt,name=matcher,proto3" json:"matcher,omitempty"` - MappingId int64 `protobuf:"varint,4,opt,name=mapping_id,json=mappingId,proto3" json:"mapping_id,omitempty"` + MappingId string `protobuf:"bytes,4,opt,name=mapping_id,json=mappingId,proto3" json:"mapping_id,omitempty"` Workflow string `protobuf:"bytes,5,opt,name=workflow,proto3" json:"workflow,omitempty"` Owner string `protobuf:"bytes,6,opt,name=owner,proto3" json:"owner,omitempty"` Repo string `protobuf:"bytes,7,opt,name=repo,proto3" json:"repo,omitempty"` @@ -2057,11 +2057,11 @@ func (*Binding) Descriptor() ([]byte, []int) { return file_state_v1_state_proto_rawDescGZIP(), []int{30} } -func (x *Binding) GetId() int64 { +func (x *Binding) GetId() string { if x != nil { return x.Id } - return 0 + return "" } func (x *Binding) GetName() string { @@ -2078,11 +2078,11 @@ func (x *Binding) GetMatcher() *BindingMatcher { return nil } -func (x *Binding) GetMappingId() int64 { +func (x *Binding) GetMappingId() string { if x != nil { return x.MappingId } - return 0 + return "" } func (x *Binding) GetWorkflow() string { @@ -5763,7 +5763,7 @@ func (x *InsertCaptureRequest) GetMaxEvents() int64 { type InsertCaptureResponse struct { state protoimpl.MessageState `protogen:"open.v1"` - Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` + Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } @@ -5798,11 +5798,11 @@ func (*InsertCaptureResponse) Descriptor() ([]byte, []int) { return file_state_v1_state_proto_rawDescGZIP(), []int{101} } -func (x *InsertCaptureResponse) GetId() int64 { +func (x *InsertCaptureResponse) GetId() string { if x != nil { return x.Id } - return 0 + return "" } type ListCapturesRequest struct { @@ -6028,7 +6028,7 @@ func (x *InsertMappingRequest) GetMapping() *Mapping { type InsertMappingResponse struct { state protoimpl.MessageState `protogen:"open.v1"` - Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` + Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } @@ -6063,16 +6063,16 @@ func (*InsertMappingResponse) Descriptor() ([]byte, []int) { return file_state_v1_state_proto_rawDescGZIP(), []int{107} } -func (x *InsertMappingResponse) GetId() int64 { +func (x *InsertMappingResponse) GetId() string { if x != nil { return x.Id } - return 0 + return "" } type GetMappingRequest struct { state protoimpl.MessageState `protogen:"open.v1"` - Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` + Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } @@ -6107,11 +6107,11 @@ func (*GetMappingRequest) Descriptor() ([]byte, []int) { return file_state_v1_state_proto_rawDescGZIP(), []int{108} } -func (x *GetMappingRequest) GetId() int64 { +func (x *GetMappingRequest) GetId() string { if x != nil { return x.Id } - return 0 + return "" } type GetMappingResponse struct { @@ -6328,7 +6328,7 @@ func (*UpdateMappingResponse) Descriptor() ([]byte, []int) { type DeleteMappingRequest struct { state protoimpl.MessageState `protogen:"open.v1"` - Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` + Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } @@ -6363,11 +6363,11 @@ func (*DeleteMappingRequest) Descriptor() ([]byte, []int) { return file_state_v1_state_proto_rawDescGZIP(), []int{114} } -func (x *DeleteMappingRequest) GetId() int64 { +func (x *DeleteMappingRequest) GetId() string { if x != nil { return x.Id } - return 0 + return "" } type DeleteMappingResponse struct { @@ -6452,7 +6452,7 @@ func (x *InsertBindingRequest) GetBinding() *Binding { type InsertBindingResponse struct { state protoimpl.MessageState `protogen:"open.v1"` - Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` + Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } @@ -6487,16 +6487,16 @@ func (*InsertBindingResponse) Descriptor() ([]byte, []int) { return file_state_v1_state_proto_rawDescGZIP(), []int{117} } -func (x *InsertBindingResponse) GetId() int64 { +func (x *InsertBindingResponse) GetId() string { if x != nil { return x.Id } - return 0 + return "" } type GetBindingRequest struct { state protoimpl.MessageState `protogen:"open.v1"` - Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` + Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } @@ -6531,11 +6531,11 @@ func (*GetBindingRequest) Descriptor() ([]byte, []int) { return file_state_v1_state_proto_rawDescGZIP(), []int{118} } -func (x *GetBindingRequest) GetId() int64 { +func (x *GetBindingRequest) GetId() string { if x != nil { return x.Id } - return 0 + return "" } type GetBindingResponse struct { @@ -6752,7 +6752,7 @@ func (*UpdateBindingResponse) Descriptor() ([]byte, []int) { type DeleteBindingRequest struct { state protoimpl.MessageState `protogen:"open.v1"` - Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` + Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } @@ -6787,11 +6787,11 @@ func (*DeleteBindingRequest) Descriptor() ([]byte, []int) { return file_state_v1_state_proto_rawDescGZIP(), []int{124} } -func (x *DeleteBindingRequest) GetId() int64 { +func (x *DeleteBindingRequest) GetId() string { if x != nil { return x.Id } - return 0 + return "" } type DeleteBindingResponse struct { @@ -6832,7 +6832,7 @@ func (*DeleteBindingResponse) Descriptor() ([]byte, []int) { type ApproveBindingRequest struct { state protoimpl.MessageState `protogen:"open.v1"` - Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` + Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } @@ -6867,11 +6867,11 @@ func (*ApproveBindingRequest) Descriptor() ([]byte, []int) { return file_state_v1_state_proto_rawDescGZIP(), []int{126} } -func (x *ApproveBindingRequest) GetId() int64 { +func (x *ApproveBindingRequest) GetId() string { if x != nil { return x.Id } - return 0 + return "" } type ApproveBindingResponse struct { @@ -7000,12 +7000,13 @@ func (x *ArmedBindingsForSourceResponse) GetBindings() []*Binding { type RecordDispatchRequest struct { state protoimpl.MessageState `protogen:"open.v1"` - BindingId int64 `protobuf:"varint,1,opt,name=binding_id,json=bindingId,proto3" json:"binding_id,omitempty"` + BindingId string `protobuf:"bytes,1,opt,name=binding_id,json=bindingId,proto3" json:"binding_id,omitempty"` BindingVersion int64 `protobuf:"varint,2,opt,name=binding_version,json=bindingVersion,proto3" json:"binding_version,omitempty"` - CaptureId int64 `protobuf:"varint,3,opt,name=capture_id,json=captureId,proto3" json:"capture_id,omitempty"` - TaskId int64 `protobuf:"varint,4,opt,name=task_id,json=taskId,proto3" json:"task_id,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + CaptureId string `protobuf:"bytes,3,opt,name=capture_id,json=captureId,proto3" json:"capture_id,omitempty"` + // task_id addresses the SQLite-owned task tables, which are not migrating. + TaskId int64 `protobuf:"varint,4,opt,name=task_id,json=taskId,proto3" json:"task_id,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *RecordDispatchRequest) Reset() { @@ -7038,11 +7039,11 @@ func (*RecordDispatchRequest) Descriptor() ([]byte, []int) { return file_state_v1_state_proto_rawDescGZIP(), []int{130} } -func (x *RecordDispatchRequest) GetBindingId() int64 { +func (x *RecordDispatchRequest) GetBindingId() string { if x != nil { return x.BindingId } - return 0 + return "" } func (x *RecordDispatchRequest) GetBindingVersion() int64 { @@ -7052,11 +7053,11 @@ func (x *RecordDispatchRequest) GetBindingVersion() int64 { return 0 } -func (x *RecordDispatchRequest) GetCaptureId() int64 { +func (x *RecordDispatchRequest) GetCaptureId() string { if x != nil { return x.CaptureId } - return 0 + return "" } func (x *RecordDispatchRequest) GetTaskId() int64 { @@ -7487,7 +7488,7 @@ type EnqueueBindingTaskRequest struct { Body string `protobuf:"bytes,4,opt,name=body,proto3" json:"body,omitempty"` Workflow string `protobuf:"bytes,5,opt,name=workflow,proto3" json:"workflow,omitempty"` Identity string `protobuf:"bytes,6,opt,name=identity,proto3" json:"identity,omitempty"` - BindingId int64 `protobuf:"varint,7,opt,name=binding_id,json=bindingId,proto3" json:"binding_id,omitempty"` + BindingId string `protobuf:"bytes,7,opt,name=binding_id,json=bindingId,proto3" json:"binding_id,omitempty"` BindingVersion int64 `protobuf:"varint,8,opt,name=binding_version,json=bindingVersion,proto3" json:"binding_version,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache @@ -7565,11 +7566,11 @@ func (x *EnqueueBindingTaskRequest) GetIdentity() string { return "" } -func (x *EnqueueBindingTaskRequest) GetBindingId() int64 { +func (x *EnqueueBindingTaskRequest) GetBindingId() string { if x != nil { return x.BindingId } - return 0 + return "" } func (x *EnqueueBindingTaskRequest) GetBindingVersion() int64 { @@ -7734,7 +7735,7 @@ const file_state_v1_state_proto_rawDesc = "" + "\x06source\x18\x15 \x01(\tR\x06source\x12\x1a\n" + "\bidentity\x18\x16 \x01(\tR\bidentity\x12\x1d\n" + "\n" + - "binding_id\x18\x17 \x01(\x03R\tbindingId\x12'\n" + + "binding_id\x18\x17 \x01(\tR\tbindingId\x12'\n" + "\x0fbinding_version\x18\x18 \x01(\x03R\x0ebindingVersion\x129\n" + "\n" + "created_at\x18\x19 \x01(\v2\x1a.google.protobuf.TimestampR\tcreatedAt\x129\n" + @@ -7762,7 +7763,7 @@ const file_state_v1_state_proto_rawDesc = "" + "actor_kind\x18\r \x01(\tR\tactorKind\x12!\n" + "\fprincipal_id\x18\x0e \x01(\tR\vprincipalId\"\x8c\x02\n" + "\rCapturedEvent\x12\x0e\n" + - "\x02id\x18\x01 \x01(\x03R\x02id\x12;\n" + + "\x02id\x18\x01 \x01(\tR\x02id\x12;\n" + "\vreceived_at\x18\x02 \x01(\v2\x1a.google.protobuf.TimestampR\n" + "receivedAt\x12\x16\n" + "\x06source\x18\x03 \x01(\tR\x06source\x12\x1f\n" + @@ -7778,7 +7779,7 @@ const file_state_v1_state_proto_rawDesc = "" + "\x04type\x18\x03 \x01(\tR\x04type\x12\x1a\n" + "\brequired\x18\x04 \x01(\bR\brequired\"\xf4\x01\n" + "\aMapping\x12\x0e\n" + - "\x02id\x18\x01 \x01(\x03R\x02id\x12\x12\n" + + "\x02id\x18\x01 \x01(\tR\x02id\x12\x12\n" + "\x04name\x18\x02 \x01(\tR\x04name\x12\x1f\n" + "\vsource_hint\x18\x03 \x01(\tR\n" + "sourceHint\x12.\n" + @@ -7790,11 +7791,11 @@ const file_state_v1_state_proto_rawDesc = "" + "\x0eBindingMatcher\x12\x16\n" + "\x06source\x18\x01 \x01(\tR\x06source\"\x86\x03\n" + "\aBinding\x12\x0e\n" + - "\x02id\x18\x01 \x01(\x03R\x02id\x12\x12\n" + + "\x02id\x18\x01 \x01(\tR\x02id\x12\x12\n" + "\x04name\x18\x02 \x01(\tR\x04name\x122\n" + "\amatcher\x18\x03 \x01(\v2\x18.state.v1.BindingMatcherR\amatcher\x12\x1d\n" + "\n" + - "mapping_id\x18\x04 \x01(\x03R\tmappingId\x12\x1a\n" + + "mapping_id\x18\x04 \x01(\tR\tmappingId\x12\x1a\n" + "\bworkflow\x18\x05 \x01(\tR\bworkflow\x12\x14\n" + "\x05owner\x18\x06 \x01(\tR\x05owner\x12\x12\n" + "\x04repo\x18\a \x01(\tR\x04repo\x12\x18\n" + @@ -8024,7 +8025,7 @@ const file_state_v1_state_proto_rawDesc = "" + "\n" + "max_events\x18\x03 \x01(\x03R\tmaxEvents\"'\n" + "\x15InsertCaptureResponse\x12\x0e\n" + - "\x02id\x18\x01 \x01(\x03R\x02id\"+\n" + + "\x02id\x18\x01 \x01(\tR\x02id\"+\n" + "\x13ListCapturesRequest\x12\x14\n" + "\x05limit\x18\x01 \x01(\x03R\x05limit\"K\n" + "\x14ListCapturesResponse\x123\n" + @@ -8036,9 +8037,9 @@ const file_state_v1_state_proto_rawDesc = "" + "\x14InsertMappingRequest\x12+\n" + "\amapping\x18\x01 \x01(\v2\x11.state.v1.MappingR\amapping\"'\n" + "\x15InsertMappingResponse\x12\x0e\n" + - "\x02id\x18\x01 \x01(\x03R\x02id\"#\n" + + "\x02id\x18\x01 \x01(\tR\x02id\"#\n" + "\x11GetMappingRequest\x12\x0e\n" + - "\x02id\x18\x01 \x01(\x03R\x02id\"W\n" + + "\x02id\x18\x01 \x01(\tR\x02id\"W\n" + "\x12GetMappingResponse\x12+\n" + "\amapping\x18\x01 \x01(\v2\x11.state.v1.MappingR\amapping\x12\x14\n" + "\x05found\x18\x02 \x01(\bR\x05found\"\x15\n" + @@ -8049,14 +8050,14 @@ const file_state_v1_state_proto_rawDesc = "" + "\amapping\x18\x01 \x01(\v2\x11.state.v1.MappingR\amapping\"\x17\n" + "\x15UpdateMappingResponse\"&\n" + "\x14DeleteMappingRequest\x12\x0e\n" + - "\x02id\x18\x01 \x01(\x03R\x02id\"\x17\n" + + "\x02id\x18\x01 \x01(\tR\x02id\"\x17\n" + "\x15DeleteMappingResponse\"C\n" + "\x14InsertBindingRequest\x12+\n" + "\abinding\x18\x01 \x01(\v2\x11.state.v1.BindingR\abinding\"'\n" + "\x15InsertBindingResponse\x12\x0e\n" + - "\x02id\x18\x01 \x01(\x03R\x02id\"#\n" + + "\x02id\x18\x01 \x01(\tR\x02id\"#\n" + "\x11GetBindingRequest\x12\x0e\n" + - "\x02id\x18\x01 \x01(\x03R\x02id\"W\n" + + "\x02id\x18\x01 \x01(\tR\x02id\"W\n" + "\x12GetBindingResponse\x12+\n" + "\abinding\x18\x01 \x01(\v2\x11.state.v1.BindingR\abinding\x12\x14\n" + "\x05found\x18\x02 \x01(\bR\x05found\"\x15\n" + @@ -8067,10 +8068,10 @@ const file_state_v1_state_proto_rawDesc = "" + "\abinding\x18\x01 \x01(\v2\x11.state.v1.BindingR\abinding\"\x17\n" + "\x15UpdateBindingResponse\"&\n" + "\x14DeleteBindingRequest\x12\x0e\n" + - "\x02id\x18\x01 \x01(\x03R\x02id\"\x17\n" + + "\x02id\x18\x01 \x01(\tR\x02id\"\x17\n" + "\x15DeleteBindingResponse\"'\n" + "\x15ApproveBindingRequest\x12\x0e\n" + - "\x02id\x18\x01 \x01(\x03R\x02id\"\x18\n" + + "\x02id\x18\x01 \x01(\tR\x02id\"\x18\n" + "\x16ApproveBindingResponse\"7\n" + "\x1dArmedBindingsForSourceRequest\x12\x16\n" + "\x06source\x18\x01 \x01(\tR\x06source\"O\n" + @@ -8078,10 +8079,10 @@ const file_state_v1_state_proto_rawDesc = "" + "\bbindings\x18\x01 \x03(\v2\x11.state.v1.BindingR\bbindings\"\x97\x01\n" + "\x15RecordDispatchRequest\x12\x1d\n" + "\n" + - "binding_id\x18\x01 \x01(\x03R\tbindingId\x12'\n" + + "binding_id\x18\x01 \x01(\tR\tbindingId\x12'\n" + "\x0fbinding_version\x18\x02 \x01(\x03R\x0ebindingVersion\x12\x1d\n" + "\n" + - "capture_id\x18\x03 \x01(\x03R\tcaptureId\x12\x17\n" + + "capture_id\x18\x03 \x01(\tR\tcaptureId\x12\x17\n" + "\atask_id\x18\x04 \x01(\x03R\x06taskId\"\x18\n" + "\x16RecordDispatchResponse\"\xa3\x01\n" + "\x1dRecordPlaybookDispatchRequest\x12\x1f\n" + @@ -8113,7 +8114,7 @@ const file_state_v1_state_proto_rawDesc = "" + "\bworkflow\x18\x05 \x01(\tR\bworkflow\x12\x1a\n" + "\bidentity\x18\x06 \x01(\tR\bidentity\x12\x1d\n" + "\n" + - "binding_id\x18\a \x01(\x03R\tbindingId\x12'\n" + + "binding_id\x18\a \x01(\tR\tbindingId\x12'\n" + "\x0fbinding_version\x18\b \x01(\x03R\x0ebindingVersion\"@\n" + "\x1aEnqueueBindingTaskResponse\x12\"\n" + "\x04task\x18\x01 \x01(\v2\x0e.state.v1.TaskR\x04task2\xe1)\n" + diff --git a/internal/daemon/daemon.go b/internal/daemon/daemon.go index d78bd8a85..7add5e30e 100644 --- a/internal/daemon/daemon.go +++ b/internal/daemon/daemon.go @@ -678,7 +678,7 @@ func (d *Daemon) dispatchOneBinding(ctx context.Context, b binding.Binding, c st if hasBlockingFailure(m.Fields, failures) { _, _ = d.Store.InsertEvent(ctx, events.Event{ Kind: "binding_dispatch_failure", - Detail: fmt.Sprintf("binding %d (capture %d): required field failed", b.ID, c.ID), + Detail: fmt.Sprintf("binding %q (capture %q): required field failed", b.ID, c.ID), Data: map[string]any{ "binding_id": b.ID, "binding_version": b.Version, @@ -746,7 +746,7 @@ func hasBlockingFailure(fields []mapping.Field, failures []mapping.Failure) bool // provenance to hand back to the operator. func renderBindingBody(values map[string]any, c storecontract.CapturedEvent) string { if len(values) == 0 { - return fmt.Sprintf("(no fields resolved from capture %d)", c.ID) + return fmt.Sprintf("(no fields resolved from capture %q)", c.ID) } parts := make([]string, 0, len(values)) for k, v := range values { diff --git a/internal/daemon/dispatch_bindings_test.go b/internal/daemon/dispatch_bindings_test.go index e55951eaa..63e16501b 100644 --- a/internal/daemon/dispatch_bindings_test.go +++ b/internal/daemon/dispatch_bindings_test.go @@ -11,6 +11,7 @@ import ( "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" ) @@ -35,7 +36,7 @@ func TestDispatchBindingsCreatesTaskFromArmedCapture(t *testing.T) { } got := tasks[0] if got.BindingID != bindingID { - t.Errorf("task.BindingID = %d, want %d", got.BindingID, bindingID) + t.Errorf("task.BindingID = %q, want %q", got.BindingID, bindingID) } if got.BindingVersion != bindingVersion { t.Errorf("task.BindingVersion = %d, want %d", got.BindingVersion, bindingVersion) @@ -230,9 +231,9 @@ func TestDispatchBindingsNilDispatcherIsNoOp(t *testing.T) { d := &Daemon{ Cfg: config.NewHolder(config.Config{Repos: []config.Repo{{Owner: "acme", Name: "widget"}}}), - Store: s, - Mappings: s, - Bindings: s, + Store: s.Store, + Mappings: s.EdaStore, + Bindings: s.EdaStore, // BindingDispatcher and BindingTaskCreator intentionally nil. Log: slog.New(slog.NewTextHandler(os.Stderr, nil)), } @@ -248,22 +249,31 @@ 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. -func openDispatchTestStore(t *testing.T) *store.Store { +// 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. +type dispatchStores struct { + *store.Store + EdaStore *edastore.Store +} + +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) } t.Cleanup(func() { _ = s.Close() }) - return s + return &dispatchStores{Store: s, EdaStore: edastore.OpenTest(t)} } // seedMapping inserts a mapping with the given fields and returns its id. // The Name field is "sentry-mapping" by default; callers pass fields // inline. -func seedMapping(t *testing.T, s *store.Store, sourceHint string, fields ...mapping.Field) int64 { +func seedMapping(t *testing.T, s *dispatchStores, sourceHint string, fields ...mapping.Field) string { t.Helper() - id, err := s.InsertMapping(t.Context(), mapping.Mapping{ + id, err := s.EdaStore.InsertMapping(t.Context(), mapping.Mapping{ Name: sourceHint + "-mapping", SourceHint: sourceHint, Fields: fields, @@ -281,7 +291,7 @@ func seedMapping(t *testing.T, s *store.Store, sourceHint string, fields ...mapp // advances through pending_approval via the store's test-only DB // accessor -- production callers must use the structured methods // (bindings.go) rather than touching the SQL directly. -func seedArmedBinding(t *testing.T, s *store.Store, source string, mappingID int64) (int64, int) { +func seedArmedBinding(t *testing.T, s *dispatchStores, source, mappingID string) (string, int) { t.Helper() return seedArmedBindingWithRepo(t, s, source, mappingID, "", "") } @@ -289,9 +299,9 @@ func seedArmedBinding(t *testing.T, s *store.Store, source string, mappingID int // seedArmedBindingWithRepo is seedArmedBinding with an explicit // owner/repo pin (pass "", "" for the unpinned case seedArmedBinding // covers). -func seedArmedBindingWithRepo(t *testing.T, s *store.Store, source string, mappingID int64, owner, repo string) (int64, int) { +func seedArmedBindingWithRepo(t *testing.T, s *dispatchStores, source, mappingID, owner, repo string) (string, int) { t.Helper() - id, err := s.InsertBinding(t.Context(), binding.Binding{ + id, err := s.EdaStore.InsertBinding(t.Context(), binding.Binding{ Name: "test " + source, Matcher: binding.Matcher{Source: source}, MappingID: mappingID, @@ -303,13 +313,25 @@ func seedArmedBindingWithRepo(t *testing.T, s *store.Store, source string, mappi if err != nil { t.Fatalf("InsertBinding: %v", err) } - if _, err := s.DB().ExecContext(t.Context(), `UPDATE bindings SET status='pending_approval' WHERE id=?`, id); err != nil { - t.Fatalf("force pending_approval: %v", err) + // Edit moves a draft to pending_approval through the real lifecycle, + // which is what makes it approvable. The old raw-SQL shortcut reached + // into a table the task store no longer owns. + if err := s.EdaStore.UpdateBinding(t.Context(), binding.Binding{ + ID: id, + Name: "test " + source, + Matcher: binding.Matcher{Source: source}, + MappingID: mappingID, + Workflow: "implement", + Owner: owner, + Repo: repo, + Secret: "0123456789abcdef0123456789abcdef", + }); err != nil { + t.Fatalf("UpdateBinding to pending_approval: %v", err) } - if err := s.ApproveBinding(t.Context(), id); err != nil { + if err := s.EdaStore.ApproveBinding(t.Context(), id); err != nil { t.Fatalf("ApproveBinding: %v", err) } - got, err := s.GetBinding(t.Context(), id) + got, err := s.EdaStore.GetBinding(t.Context(), id) if err != nil || got == nil { t.Fatalf("GetBinding after approve: %+v, %v", got, err) } @@ -321,9 +343,9 @@ func seedArmedBindingWithRepo(t *testing.T, s *store.Store, source string, mappi // the per-insert pruning the production path uses, so a test that // only needs a single row in the table is not at the mercy of // maxEvents=0's "no cap" reading. -func seedCapture(t *testing.T, s *store.Store, source string, authenticated bool, body string) { +func seedCapture(t *testing.T, s *dispatchStores, source string, authenticated bool, body string) { t.Helper() - _, err := s.InsertCapture(t.Context(), store.CapturedEvent{ + _, err := s.EdaStore.InsertCapture(t.Context(), store.CapturedEvent{ Source: source, Body: body, Authenticated: authenticated, @@ -341,7 +363,7 @@ func seedCapture(t *testing.T, s *store.Store, source string, authenticated bool // single-repo fallback accepts the dispatch; with zero or many // configured repos the loop would log and skip, masking the test's // positive assertions. -func newDispatchDaemon(t *testing.T, s *store.Store) *Daemon { +func newDispatchDaemon(t *testing.T, s *dispatchStores) *Daemon { t.Helper() return newDispatchDaemonWithRepos(t, s, []config.Repo{{Owner: "acme", Name: "widget"}}) } @@ -349,36 +371,37 @@ func newDispatchDaemon(t *testing.T, s *store.Store) *Daemon { // newDispatchDaemonWithRepos is newDispatchDaemon with an explicit repo // list, for tests exercising resolveBindingRepo's owner/repo-pin path // against zero, one, or several configured repos. -func newDispatchDaemonWithRepos(t *testing.T, s *store.Store, repos []config.Repo) *Daemon { +func newDispatchDaemonWithRepos(t *testing.T, s *dispatchStores, repos []config.Repo) *Daemon { t.Helper() cfg := config.Config{Repos: repos} return &Daemon{ Cfg: config.NewHolder(cfg), - Store: s, - Mappings: s, - Bindings: s, - BindingDispatcher: s, - BindingTaskCreator: s, + Store: s.Store, + Mappings: s.EdaStore, + Bindings: s.EdaStore, + BindingDispatcher: s.EdaStore, + BindingTaskCreator: s.Store, Log: slog.New(slog.NewTextHandler(os.Stderr, nil)), } } // assertDispatchRecorded reads the dedup ledger directly: the -// (binding_id, capture_id) primary key is what guarantees no double +// (binding, capture) unique index is what guarantees no double // dispatch. Going through the SQL table rather than the public // BindingStore surface keeps the assertion focused on the contract // Phase E actually writes to, not on a ListDispatches helper that // may not exist. -func assertDispatchRecorded(t *testing.T, s *store.Store, bindingID, taskID int64) { +func assertDispatchRecorded(t *testing.T, s *dispatchStores, bindingID string, taskID int64) { t.Helper() - var gotBindingID, gotTaskID int64 - if err := s.DB().QueryRowContext( - t.Context(), - `SELECT binding_id, task_id FROM binding_dispatches WHERE binding_id=?`, bindingID, - ).Scan(&gotBindingID, &gotTaskID); err != nil { + 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 { t.Fatalf("binding_dispatches row missing: %v", err) } if gotBindingID != bindingID || gotTaskID != taskID { - t.Fatalf("binding_dispatches row = (%d, %d), want (%d, %d)", gotBindingID, gotTaskID, bindingID, taskID) + t.Fatalf("binding_dispatches row = (%q, %d), want (%q, %d)", gotBindingID, gotTaskID, bindingID, taskID) } } diff --git a/internal/domain/binding/binding.go b/internal/domain/binding/binding.go index 92fa0a728..dc8f14112 100644 --- a/internal/domain/binding/binding.go +++ b/internal/domain/binding/binding.go @@ -43,10 +43,10 @@ type Matcher struct { // for an event to be marked authenticated; it is never returned by // GET handlers. type Binding struct { - ID int64 `json:"id"` + ID string `json:"id"` Name string `json:"name"` Matcher Matcher `json:"matcher"` - MappingID int64 `json:"mapping_id"` + MappingID string `json:"mapping_id"` Workflow string `json:"workflow"` // Owner and Repo pin a binding to a specific configured repo, so a // multi-repo deployment can dispatch correctly. Both empty means "no @@ -110,8 +110,8 @@ func (b Binding) validateCommon() error { if strings.TrimSpace(b.Matcher.Source) == "" { return fmt.Errorf("binding: matcher.source is required") } - if b.MappingID <= 0 { - return fmt.Errorf("binding: mapping_id must be positive") + if strings.TrimSpace(b.MappingID) == "" { + return fmt.Errorf("binding: mapping_id is required") } if strings.TrimSpace(b.Workflow) == "" { return fmt.Errorf("binding: workflow is required") diff --git a/internal/domain/binding/binding_test.go b/internal/domain/binding/binding_test.go index 7ca909086..793390ab9 100644 --- a/internal/domain/binding/binding_test.go +++ b/internal/domain/binding/binding_test.go @@ -6,7 +6,7 @@ func validBinding() Binding { return Binding{ Name: "sentry alerts", Matcher: Matcher{Source: "sentry"}, - MappingID: 1, + MappingID: "m1", Workflow: "implement", Secret: "0123456789abcdef0123456789abcdef", } diff --git a/internal/domain/mapping/mapping.go b/internal/domain/mapping/mapping.go index 3337fe6c9..c225210b0 100644 --- a/internal/domain/mapping/mapping.go +++ b/internal/domain/mapping/mapping.go @@ -50,7 +50,7 @@ type Field struct { // through one example captured event but not pinned to that event or its // source -- t2db.4's matcher decides which events a binding applies to. type Mapping struct { - ID int64 `json:"id"` + ID string `json:"id"` Name string `json:"name"` SourceHint string `json:"source_hint"` Fields []Field `json:"fields"` diff --git a/internal/domain/storecontract/storecontract.go b/internal/domain/storecontract/storecontract.go index 1956cee8a..2729d9638 100644 --- a/internal/domain/storecontract/storecontract.go +++ b/internal/domain/storecontract/storecontract.go @@ -94,7 +94,7 @@ type TaskEvents interface { // should not acquire the full task-lifecycle surface, mirroring why // TaskArchiver is split out above. See docs/prds/event-capture-storage.md. type CaptureStore interface { - InsertCapture(ctx context.Context, c CapturedEvent, retention time.Duration, maxEvents int) (int64, error) + InsertCapture(ctx context.Context, c CapturedEvent, retention time.Duration, maxEvents int) (string, error) ListCaptures(ctx context.Context, limit int) ([]CapturedEvent, error) } @@ -142,11 +142,11 @@ type ApplyStatusStore interface { // surface, not the full task or capture APIs. See // docs/prds/payload-field-mapping.md. type MappingStore interface { - InsertMapping(ctx context.Context, m mapping.Mapping) (int64, error) - GetMapping(ctx context.Context, id int64) (*mapping.Mapping, error) + InsertMapping(ctx context.Context, m mapping.Mapping) (string, error) + GetMapping(ctx context.Context, id string) (*mapping.Mapping, error) ListMappings(ctx context.Context) ([]mapping.Mapping, error) UpdateMapping(ctx context.Context, m mapping.Mapping) error - DeleteMapping(ctx context.Context, id int64) error + DeleteMapping(ctx context.Context, id string) error } // BindingStore persists playbook bindings (t2db.4 Phase B): CRUD and the @@ -156,12 +156,12 @@ type MappingStore interface { // BindingDispatcher; the daemon depends on both. See // docs/prds/playbook-binding.md. type BindingStore interface { - InsertBinding(ctx context.Context, b binding.Binding) (int64, error) - GetBinding(ctx context.Context, id int64) (*binding.Binding, error) + InsertBinding(ctx context.Context, b binding.Binding) (string, error) + GetBinding(ctx context.Context, id string) (*binding.Binding, error) ListBindings(ctx context.Context) ([]binding.Binding, error) UpdateBinding(ctx context.Context, b binding.Binding) error - DeleteBinding(ctx context.Context, id int64) error - ApproveBinding(ctx context.Context, id int64) error + DeleteBinding(ctx context.Context, id string) error + ApproveBinding(ctx context.Context, id string) error } // BindingDispatcher is the dispatch-loop surface over the bindings store: @@ -174,9 +174,11 @@ type BindingDispatcher interface { ArmedBindingsForSource(ctx context.Context, source string) ([]binding.Binding, error) RecordDispatch( ctx context.Context, - bindingID int64, + bindingID string, bindingVersion int64, - captureID int64, + captureID string, + // taskID addresses the SQLite-owned task tables, which are not + // migrating: it stays an integer on purpose. taskID int64, ) error ListUndispatchedCaptures(ctx context.Context, sources []string, limit int) ([]CapturedEvent, error) @@ -187,7 +189,7 @@ type BindingDispatcher interface { // keeps the lifecycle surface narrow (8 methods, the interfacebloat limit) // and keeps the binding-specific shape on the binding interfaces. type BindingTaskCreator interface { - EnqueueBindingTask(ctx context.Context, owner, repo, title, body, wf, identity string, bindingID int64, bindingVersion int) (*task.Task, error) + EnqueueBindingTask(ctx context.Context, owner, repo, title, body, wf, identity, bindingID string, bindingVersion int) (*task.Task, error) } // PlaybookDispatcher is the idempotency-ledger surface for side-effecting @@ -231,7 +233,7 @@ type TaskLogStore interface { // no forge/task association -- just what arrived, from where, and when. // See docs/prds/event-capture-storage.md. type CapturedEvent struct { - ID int64 `json:"id"` + ID string `json:"id"` ReceivedAt time.Time `json:"received_at"` Source string `json:"source"` RemoteAddr string `json:"remote_addr"` diff --git a/internal/domain/workflow/task/task.go b/internal/domain/workflow/task/task.go index 63e2e70a7..fe30ca1d8 100644 --- a/internal/domain/workflow/task/task.go +++ b/internal/domain/workflow/task/task.go @@ -82,8 +82,8 @@ type Task struct { // from a playbook binding dispatch (t2db.4 Phase B). They record // provenance: which binding fired this task and at what version, so // later edits to the binding cannot silently rewrite history. - BindingID int64 `json:"binding_id"` - BindingVersion int `json:"binding_version"` + BindingID string `json:"binding_id"` + BindingVersion int `json:"binding_version"` // ReviewPayload is the JSON-encoded review unit (the forge review's // actionable comments) the remediate workflow's current run must // address. The daemon's reaction consumer injects it before queuing a diff --git a/internal/infrastructure/captureintake/receiver_test.go b/internal/infrastructure/captureintake/receiver_test.go index 22c07def3..7889ff515 100644 --- a/internal/infrastructure/captureintake/receiver_test.go +++ b/internal/infrastructure/captureintake/receiver_test.go @@ -9,13 +9,13 @@ import ( "log/slog" "net/http" "net/http/httptest" - "path/filepath" "strings" "testing" "time" "github.com/samcharles93/archie-core/internal/domain/binding" "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/webhookguard" ) @@ -37,7 +37,9 @@ func (r *recordingPublisher) Publish(_ context.Context, e events.Event) { // wrote. type testReceiver struct { *Receiver - store *store.Store + // 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 } // Handler serves the receiver's route the way its host process mounts it, @@ -58,11 +60,7 @@ func captureTestServerWithoutStore(t *testing.T) testReceiver { func captureTestServer(t *testing.T) testReceiver { t.Helper() - s, err := store.Open(t.Context(), filepath.Join(t.TempDir(), "test.db")) - if err != nil { - t.Fatal(err) - } - t.Cleanup(func() { _ = s.Close() }) + s := edastore.OpenTest(t) return testReceiver{ Receiver: &Receiver{ Log: slog.New(slog.DiscardHandler), @@ -125,9 +123,9 @@ func (s *stubBindingStore) ApproveBinding(_ context.Context, _ int64) error { func (s *stubBindingStore) RecordDispatch( _ context.Context, + _ string, _ int64, - _ int64, - _ int64, + _ string, _ int64, ) error { return nil @@ -148,10 +146,10 @@ func captureBindingServer(t *testing.T, secret, source string) testReceiver { srv.Bindings = &stubBindingStore{ armedBySource: map[string][]binding.Binding{ source: {{ - ID: 1, + ID: "rbind0000000001", Name: "test", Matcher: binding.Matcher{Source: source}, - MappingID: 1, + MappingID: "rmap00000000001", Workflow: "implement", Version: 1, Status: binding.StatusArmed, @@ -425,8 +423,8 @@ type captureInsertErrorStore struct { store.CaptureStore } -func (captureInsertErrorStore) InsertCapture(context.Context, store.CapturedEvent, time.Duration, int) (int64, error) { - return 0, errors.New("boom") +func (captureInsertErrorStore) InsertCapture(context.Context, store.CapturedEvent, time.Duration, int) (string, error) { + return "", errors.New("boom") } func TestHandleCaptureStorageFailureIs500(t *testing.T) { @@ -543,8 +541,8 @@ func TestHandleCaptureWithMultipleArmedBindingsReturns409(t *testing.T) { srv.Bindings = &stubBindingStore{ armedBySource: map[string][]binding.Binding{ "github": { - {ID: 1, Matcher: binding.Matcher{Source: "github"}, Status: binding.StatusArmed, Secret: "abcdefghijklmnop"}, - {ID: 2, Matcher: binding.Matcher{Source: "github"}, Status: binding.StatusArmed, Secret: "qrstuvwxyz123456"}, + {ID: "rbind0000000001", Matcher: binding.Matcher{Source: "github"}, Status: binding.StatusArmed, Secret: "abcdefghijklmnop"}, + {ID: "rbind0000000002", Matcher: binding.Matcher{Source: "github"}, Status: binding.StatusArmed, Secret: "qrstuvwxyz123456"}, }, }, } diff --git a/internal/store/binding_cipher.go b/internal/infrastructure/edastore/cipher.go similarity index 99% rename from internal/store/binding_cipher.go rename to internal/infrastructure/edastore/cipher.go index ccbb27ec2..6c398adaf 100644 --- a/internal/store/binding_cipher.go +++ b/internal/infrastructure/edastore/cipher.go @@ -1,4 +1,4 @@ -package store +package edastore import ( "crypto/aes" diff --git a/internal/store/binding_cipher_test.go b/internal/infrastructure/edastore/cipher_test.go similarity index 58% rename from internal/store/binding_cipher_test.go rename to internal/infrastructure/edastore/cipher_test.go index 9ba199d2c..42ae13d26 100644 --- a/internal/store/binding_cipher_test.go +++ b/internal/infrastructure/edastore/cipher_test.go @@ -1,4 +1,4 @@ -package store +package edastore import ( "encoding/base64" @@ -121,122 +121,112 @@ func TestBindingCipherDerivesDistinctKeys(t *testing.T) { } } -func TestStoreBindingSecretEncryptedAtRest(t *testing.T) { - s := openTestWithBindingCipher(t) - b := testBinding("sentry") - id, err := s.InsertBinding(t.Context(), b) - if err != nil { - t.Fatalf("InsertBinding: %v", err) - } - - // The raw column must not be the plaintext secret. - var stored string - if err := s.db.QueryRowContext(t.Context(), `SELECT secret FROM bindings WHERE id=?`, id).Scan(&stored); err != nil { - t.Fatalf("read raw secret: %v", err) - } - if stored == b.Secret { - t.Fatal("bindings.secret stored as plaintext") - } - if !strings.HasPrefix(stored, "arcie-binding:v1:") { - t.Fatalf("stored secret = %q, want arcie-binding:v1: envelope", stored) - } - - // GetBinding returns the plaintext secret. - got, err := s.GetBinding(t.Context(), id) - if err != nil || got == nil { - t.Fatalf("GetBinding: %+v, %v", got, err) - } - if got.Secret != b.Secret { - t.Fatalf("GetBinding.Secret = %q, want %q", got.Secret, b.Secret) - } -} - -func TestStoreListBindingsDecryptsSecrets(t *testing.T) { - s := openTestWithBindingCipher(t) - if _, err := s.InsertBinding(t.Context(), testBinding("sentry")); err != nil { - t.Fatalf("InsertBinding: %v", err) - } - got, err := s.ListBindings(t.Context()) - if err != nil { - t.Fatalf("ListBindings: %v", err) - } - if len(got) != 1 { - t.Fatalf("ListBindings = %d rows, want 1", len(got)) - } - if got[0].Secret != testBinding("sentry").Secret { - t.Fatalf("ListBindings.Secret not decrypted") - } -} - -func TestStoreBindingCipherNoKeyIsPlaintext(t *testing.T) { - s := openTest(t) // no cipher -> legacy plaintext - b := testBinding("sentry") - id, err := s.InsertBinding(t.Context(), b) - if err != nil { - t.Fatalf("InsertBinding: %v", err) - } - got, err := s.GetBinding(t.Context(), id) - if err != nil || got == nil { - t.Fatalf("GetBinding: %+v, %v", got, err) - } - if got.Secret != b.Secret { - t.Fatalf("plaintext store round-trip = %q, want %q", got.Secret, b.Secret) - } -} - -// TestStoreEncryptedReadLeavesLegacyPlaintextAlone pins that enabling a -// cipher does not break rows written before it was configured: a non-envelope -// secret must remain readable as plaintext (encryption is not retroactive). -func TestStoreEncryptedReadLeavesLegacyPlaintextAlone(t *testing.T) { - path := filepath.Join(t.TempDir(), "legacy.db") - plain, err := Open(t.Context(), path) - if err != nil { - t.Fatalf("Open (plaintext): %v", err) - } - b := testBinding("sentry") - id, err := plain.InsertBinding(t.Context(), b) - if err != nil { - t.Fatalf("InsertBinding (plaintext): %v", err) - } - if err := plain.Close(); err != nil { - t.Fatalf("Close: %v", err) - } - - c, _ := NewBindingCipher(testBindingKey, nil) - encrypted, err := Open(t.Context(), path, WithBindingCipher(c)) - if err != nil { - t.Fatalf("Open (cipher): %v", err) - } - t.Cleanup(func() { _ = encrypted.Close() }) - got, err := encrypted.GetBinding(t.Context(), id) - if err != nil { - t.Fatalf("GetBinding under cipher: %v", err) - } - if got == nil { - t.Fatal("GetBinding returned nil") - } - if got.Secret != b.Secret { - t.Fatalf("legacy plaintext secret = %q, want %q (must stay readable)", got.Secret, b.Secret) - } -} - -func openTestWithBindingCipher(t *testing.T) *Store { +// openWithCipher builds a store whose binding secrets are encrypted at rest. +func openWithCipher(t *testing.T, cipher BindingCipher) *Store { t.Helper() - c, err := NewBindingCipher(testBindingKey, nil) + 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("NewBindingCipher: %v", err) - } - s, err := Open(t.Context(), filepath.Join(t.TempDir(), "test.db"), WithBindingCipher(c)) - if err != nil { - t.Fatalf("Open: %v", err) + t.Fatalf("Open() error = %v", err) } t.Cleanup(func() { _ = s.Close() }) return s } -// tamperEnvelope decodes the payload, flips one byte inside the sealed -// ciphertext (after the 12-byte nonce), and re-encodes it, so the auth tag -// must fail. It returns the envelope with a corrupt ciphertext. +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 { t.Helper() parts := strings.SplitN(envelope, ":", 4) diff --git a/internal/infrastructure/edastore/contracts.go b/internal/infrastructure/edastore/contracts.go new file mode 100644 index 000000000..ee1b1d9a9 --- /dev/null +++ b/internal/infrastructure/edastore/contracts.go @@ -0,0 +1,190 @@ +package edastore + +import ( + "context" + "database/sql" + "errors" + "fmt" + "strings" + "time" + + "github.com/pocketbase/dbx" + "github.com/pocketbase/pocketbase/core" + + "github.com/samcharles93/archie-core/internal/domain/storecontract" +) + +// capturedAtLayout is fixed-width UTC with nanosecond precision, so string +// comparison is time comparison. time.RFC3339Nano trims trailing zeros, which +// would break that. +const capturedAtLayout = "2006-01-02T15:04:05.000000000Z" + +// This store is the implementation of every event-capture contract. The task +// lifecycle contracts stay on the SQLite store; the two meet only at +// binding_dispatches.task_id. +var ( + _ storecontract.CaptureStore = (*Store)(nil) + _ storecontract.MappingStore = (*Store)(nil) + _ storecontract.BindingStore = (*Store)(nil) + _ storecontract.BindingDispatcher = (*Store)(nil) + _ storecontract.PlaybookDispatcher = (*Store)(nil) +) + +func (s *Store) record(collection, id string) (*core.Record, error) { + r, err := s.app.FindRecordById(collection, id) + if errors.Is(err, sql.ErrNoRows) { + return nil, nil + } + return r, err +} + +// InsertCapture stores one inbound event verbatim. Redaction happens upstream +// in webhookguard; this persists exactly what it is given, because field +// mapping is designed against the payload as received. +// +// retention and maxEvents are accepted for contract compatibility and applied +// as a prune after the insert. +func (s *Store) InsertCapture(ctx context.Context, c storecontract.CapturedEvent, retention time.Duration, maxEvents int) (string, error) { + collection, err := s.app.FindCollectionByNameOrId(CollCaptures) + if err != nil { + return "", err + } + r := core.NewRecord(collection) + r.Set("source", c.Source) + r.Set("remote_addr", c.RemoteAddr) + r.Set("content_type", c.ContentType) + r.Set("headers", c.Headers) + r.Set("body", c.Body) + r.Set("authenticated", c.Authenticated) + received := c.ReceivedAt + if received.IsZero() { + received = time.Now() + } + r.Set("received_at", received.UTC().Format(capturedAtLayout)) + if err := s.app.Save(r); err != nil { + return "", fmt.Errorf("edastore: insert capture: %w", err) + } + if err := s.pruneCaptures(ctx, retention, maxEvents); err != nil { + return "", err + } + return r.Id, nil +} + +// pruneCaptures enforces the retention window and count cap. A capture exists +// to be mapped against while it is recent; keeping every event forever would +// make an unauthenticated intake surface a disk-growth vector. +func (s *Store) pruneCaptures(_ context.Context, retention time.Duration, maxEvents int) error { + if retention > 0 { + cutoff := time.Now().Add(-retention).UTC().Format(time.RFC3339) + if _, err := s.app.DB().NewQuery( + "DELETE FROM " + CollCaptures + " WHERE received_at < {:cutoff}"). + Bind(map[string]any{"cutoff": cutoff}).Execute(); err != nil { + return fmt.Errorf("edastore: prune captures by age: %w", err) + } + } + if maxEvents > 0 { + if _, err := s.app.DB().NewQuery( + "DELETE FROM " + CollCaptures + " WHERE id NOT IN (SELECT id FROM " + CollCaptures + + " ORDER BY received_at DESC LIMIT {:keep})"). + Bind(map[string]any{"keep": maxEvents}).Execute(); err != nil { + return fmt.Errorf("edastore: prune captures by count: %w", err) + } + } + return nil +} + +// parseCapturedAt reads the stored timestamp, tolerating the RFC3339 form a +// caller-supplied value may carry. +func parseCapturedAt(raw string) time.Time { + for _, layout := range []string{capturedAtLayout, time.RFC3339Nano, time.RFC3339} { + if t, err := time.Parse(layout, raw); err == nil { + return t + } + } + return time.Time{} +} + +func captureValue(r *core.Record) storecontract.CapturedEvent { + return storecontract.CapturedEvent{ + ID: r.Id, + ReceivedAt: parseCapturedAt(r.GetString("received_at")), + Source: r.GetString("source"), + RemoteAddr: r.GetString("remote_addr"), + ContentType: r.GetString("content_type"), + Headers: r.GetString("headers"), + Body: r.GetString("body"), + Authenticated: r.GetBool("authenticated"), + } +} + +// ListCaptures returns the newest captures first. +func (s *Store) ListCaptures(_ context.Context, limit int) ([]storecontract.CapturedEvent, error) { + records, err := s.app.FindRecordsByFilter(CollCaptures, "", "-received_at", limit, 0) + if err != nil { + return nil, fmt.Errorf("edastore: list captures: %w", err) + } + out := make([]storecontract.CapturedEvent, 0, len(records)) + for _, r := range records { + out = append(out, captureValue(r)) + } + return out, nil +} + +// ListUndispatchedCaptures returns recent captures for the given sources that +// no binding has dispatched yet. +// +// This is raw SQL rather than a record filter: the anti-join against the +// dispatch ledger is a subquery, and PocketBase's filter DSL is not SQL (it +// has no IN (SELECT ...) form). A read fires no hooks either way, so nothing +// is lost by dropping to the query builder here. +func (s *Store) ListUndispatchedCaptures(_ context.Context, sources []string, limit int) ([]storecontract.CapturedEvent, error) { + if len(sources) == 0 || limit <= 0 { + return nil, nil + } + placeholders := make([]string, 0, len(sources)) + params := dbx.Params{"limit": limit} + for i, src := range sources { + key := fmt.Sprintf("s%d", i) + placeholders = append(placeholders, "{:"+key+"}") + params[key] = src + } + query := "SELECT id, received_at, source, remote_addr, content_type, headers, body, authenticated FROM " + + CollCaptures + " WHERE source IN (" + strings.Join(placeholders, ",") + + ") AND id NOT IN (SELECT capture FROM " + CollBindingDispatches + ") ORDER BY received_at DESC LIMIT {:limit}" + + var rows []captureRow + if err := s.app.DB().NewQuery(query).Bind(params).All(&rows); err != nil { + return nil, fmt.Errorf("edastore: list undispatched captures: %w", err) + } + out := make([]storecontract.CapturedEvent, 0, len(rows)) + for _, r := range rows { + out = append(out, r.value()) + } + return out, nil +} + +// captureRow is the raw-SQL shape of a capture, used only where a record +// filter cannot express the query. +type captureRow struct { + ID string `db:"id"` + ReceivedAt string `db:"received_at"` + Source string `db:"source"` + RemoteAddr string `db:"remote_addr"` + ContentType string `db:"content_type"` + Headers string `db:"headers"` + Body string `db:"body"` + Authenticated bool `db:"authenticated"` +} + +func (r captureRow) value() storecontract.CapturedEvent { + return storecontract.CapturedEvent{ + ID: r.ID, + ReceivedAt: parseCapturedAt(r.ReceivedAt), + Source: r.Source, + RemoteAddr: r.RemoteAddr, + ContentType: r.ContentType, + Headers: r.Headers, + Body: r.Body, + Authenticated: r.Authenticated, + } +} diff --git a/internal/infrastructure/edastore/contracts_binding.go b/internal/infrastructure/edastore/contracts_binding.go new file mode 100644 index 000000000..cc61cb4ad --- /dev/null +++ b/internal/infrastructure/edastore/contracts_binding.go @@ -0,0 +1,370 @@ +package edastore + +import ( + "context" + "encoding/json" + "fmt" + "strings" + + "github.com/pocketbase/pocketbase/core" + + "github.com/samcharles93/archie-core/internal/domain/binding" + "github.com/samcharles93/archie-core/internal/domain/mapping" +) + +// --- mappings --- + +func mappingValue(r *core.Record) (mapping.Mapping, error) { + var fields []mapping.Field + if raw := r.GetString("fields"); raw != "" { + if err := json.Unmarshal([]byte(raw), &fields); err != nil { + return mapping.Mapping{}, fmt.Errorf("edastore: decode mapping fields: %w", err) + } + } + return mapping.Mapping{ + ID: r.Id, + Name: r.GetString("name"), + SourceHint: r.GetString("source_hint"), + Fields: fields, + CreatedAt: r.GetDateTime("created_at").Time(), + UpdatedAt: r.GetDateTime("updated_at").Time(), + }, nil +} + +func (s *Store) applyMapping(r *core.Record, m mapping.Mapping) error { + encoded, err := json.Marshal(m.Fields) + if err != nil { + return fmt.Errorf("edastore: encode mapping fields: %w", err) + } + r.Set("name", m.Name) + r.Set("source_hint", m.SourceHint) + r.Set("fields", string(encoded)) + return nil +} + +func (s *Store) InsertMapping(_ context.Context, m mapping.Mapping) (string, error) { + collection, err := s.app.FindCollectionByNameOrId(CollMappings) + if err != nil { + return "", err + } + r := core.NewRecord(collection) + if err := s.applyMapping(r, m); err != nil { + return "", err + } + if err := s.app.Save(r); err != nil { + return "", fmt.Errorf("edastore: insert mapping: %w", err) + } + return r.Id, nil +} + +func (s *Store) GetMapping(_ context.Context, id string) (*mapping.Mapping, error) { + r, err := s.record(CollMappings, id) + if err != nil || r == nil { + return nil, err + } + m, err := mappingValue(r) + if err != nil { + return nil, err + } + return &m, nil +} + +func (s *Store) ListMappings(_ context.Context) ([]mapping.Mapping, error) { + records, err := s.app.FindRecordsByFilter(CollMappings, "", "-created_at", 0, 0) + if err != nil { + return nil, fmt.Errorf("edastore: list mappings: %w", err) + } + out := make([]mapping.Mapping, 0, len(records)) + for _, r := range records { + m, err := mappingValue(r) + if err != nil { + return nil, err + } + out = append(out, m) + } + return out, nil +} + +func (s *Store) UpdateMapping(_ context.Context, m mapping.Mapping) error { + r, err := s.record(CollMappings, m.ID) + if err != nil { + return err + } + if r == nil { + return ErrMappingNotFound + } + if err := s.applyMapping(r, m); err != nil { + return err + } + return s.app.Save(r) +} + +func (s *Store) DeleteMapping(_ context.Context, id string) error { + r, err := s.record(CollMappings, id) + if err != nil { + return err + } + if r == nil { + return ErrMappingNotFound + } + return s.app.Delete(r) +} + +// --- bindings --- + +func (s *Store) bindingValue(r *core.Record) (binding.Binding, error) { + b := binding.Binding{ + ID: r.Id, + Name: r.GetString("name"), + Matcher: binding.Matcher{Source: r.GetString("source")}, + MappingID: r.GetString("mapping"), + Workflow: r.GetString("workflow"), + Owner: r.GetString("owner"), + Repo: r.GetString("repo"), + Version: r.GetInt("version"), + Status: binding.Status(r.GetString("status")), + Secret: r.GetString("secret"), + CreatedAt: r.GetDateTime("created_at").Time(), + UpdatedAt: r.GetDateTime("updated_at").Time(), + } + if s.cipher != nil && b.Secret != "" { + plain, err := s.cipher.Decrypt(b.Secret) + if err != nil { + return binding.Binding{}, fmt.Errorf("edastore: decrypt binding secret: %w", err) + } + b.Secret = plain + } + return b, nil +} + +func (s *Store) applyBinding(r *core.Record, b binding.Binding) error { + r.Set("name", b.Name) + r.Set("source", b.Matcher.Source) + r.Set("mapping", b.MappingID) + r.Set("workflow", b.Workflow) + r.Set("owner", b.Owner) + r.Set("repo", b.Repo) + // An empty secret means "keep the stored one". An edit form that does not + // echo the secret back must not silently disarm the binding by erasing it. + if b.Secret == "" { + return nil + } + secret := b.Secret + if s.cipher != nil { + encrypted, err := s.cipher.Encrypt(secret) + if err != nil { + return fmt.Errorf("edastore: encrypt binding secret: %w", err) + } + secret = encrypted + } + r.Set("secret", secret) + return nil +} + +// InsertBinding stores a new binding as a draft. The caller's status is +// ignored on purpose: a binding cannot go live without explicit approval, so +// ApproveBinding is the only path to armed. +// +// A source may carry at most one binding, so an insert against a source that +// already has one is refused rather than creating an ambiguous second matcher. +func (s *Store) InsertBinding(ctx context.Context, b binding.Binding) (string, error) { + existing, err := s.bindingsByFilter("source = {:source}", map[string]any{"source": b.Matcher.Source}) + if err != nil { + return "", err + } + if len(existing) > 0 { + return "", ErrBindingOverlap + } + collection, err := s.app.FindCollectionByNameOrId(CollBindings) + if err != nil { + return "", err + } + r := core.NewRecord(collection) + if err := s.applyBinding(r, b); err != nil { + return "", err + } + r.Set("version", 1) + r.Set("status", string(binding.StatusDraft)) + if err := s.app.Save(r); err != nil { + return "", fmt.Errorf("edastore: insert binding: %w", err) + } + _ = ctx + return r.Id, nil +} + +func (s *Store) GetBinding(_ context.Context, id string) (*binding.Binding, error) { + r, err := s.record(CollBindings, id) + if err != nil || r == nil { + return nil, err + } + b, err := s.bindingValue(r) + if err != nil { + return nil, err + } + return &b, nil +} + +func (s *Store) ListBindings(_ context.Context) ([]binding.Binding, error) { + return s.bindingsByFilter("", nil) +} + +// ArmedBindingsForSource returns the armed bindings a source can dispatch. A +// draft or pending_approval binding is never returned: that is the gate. +func (s *Store) ArmedBindingsForSource(_ context.Context, source string) ([]binding.Binding, error) { + return s.bindingsByFilter("source = {:source} && status = {:status}", + map[string]any{"source": source, "status": string(binding.StatusArmed)}) +} + +func (s *Store) bindingsByFilter(filter string, params map[string]any) ([]binding.Binding, error) { + var records []*core.Record + var err error + if params == nil { + records, err = s.app.FindRecordsByFilter(CollBindings, filter, "-created_at", 0, 0) + } else { + records, err = s.app.FindRecordsByFilter(CollBindings, filter, "-created_at", 0, 0, params) + } + if err != nil { + return nil, fmt.Errorf("edastore: list bindings: %w", err) + } + out := make([]binding.Binding, 0, len(records)) + for _, r := range records { + b, err := s.bindingValue(r) + if err != nil { + return nil, err + } + out = append(out, b) + } + return out, nil +} + +// UpdateBinding rewrites a binding's editable fields, bumps its version, and +// sends it back to pending_approval. An edit always requires re-approval: an +// armed binding whose matcher or workflow changed is a different binding, and +// re-arming it silently would defeat the gate. +func (s *Store) UpdateBinding(_ context.Context, b binding.Binding) error { + r, err := s.record(CollBindings, b.ID) + if err != nil { + return err + } + if r == nil { + return ErrBindingNotFound + } + others, err := s.bindingsByFilter("source = {:source} && id != {:id}", + map[string]any{"source": b.Matcher.Source, "id": b.ID}) + if err != nil { + return err + } + if len(others) > 0 { + return ErrBindingOverlap + } + if err := s.applyBinding(r, b); err != nil { + return err + } + r.Set("status", string(binding.StatusPendingApproval)) + r.Set("version", r.GetInt("version")+1) + return s.app.Save(r) +} + +func (s *Store) DeleteBinding(_ context.Context, id string) error { + r, err := s.record(CollBindings, id) + if err != nil { + return err + } + if r == nil { + return ErrBindingNotFound + } + return s.app.Delete(r) +} + +// ApproveBinding is the only transition that arms a binding. It moves +// pending_approval to armed; any other current state is refused, so a draft +// cannot skip review and an armed binding cannot be re-approved. +// +// A source may have only one armed binding, so approval is refused when +// another binding on the same source is already armed. Without that guard, +// one capture could match two armed matchers and dispatch twice. +func (s *Store) ApproveBinding(_ context.Context, id string) error { + r, err := s.record(CollBindings, id) + if err != nil { + return err + } + if r == nil { + return ErrBindingNotFound + } + armed, err := s.bindingsByFilter("source = {:source} && status = {:status} && id != {:id}", + map[string]any{"source": r.GetString("source"), "status": string(binding.StatusArmed), "id": id}) + if err != nil { + return err + } + if len(armed) > 0 { + return ErrBindingOverlap + } + if r.GetString("status") != string(binding.StatusPendingApproval) { + return ErrBindingTransition + } + r.Set("status", string(binding.StatusArmed)) + return s.app.Save(r) +} + +// --- dispatch ledgers --- + +// RecordDispatch writes one at-most-once binding dispatch. Uniqueness is the +// collection's index, so a replay is refused by the schema; the caller sees +// ErrAlreadyDispatched rather than a silent second run. +func (s *Store) RecordDispatch(_ context.Context, bindingID string, bindingVersion int64, captureID string, taskID int64) error { + collection, err := s.app.FindCollectionByNameOrId(CollBindingDispatches) + if err != nil { + return err + } + r := core.NewRecord(collection) + r.Set("binding", bindingID) + r.Set("binding_version", bindingVersion) + r.Set("capture", captureID) + r.Set("task_id", taskID) + return ledgerWrite(s.app.Save(r), "edastore: record dispatch") +} + +func (s *Store) RecordPlaybookDispatch(_ context.Context, playbookID, playbookVersion, eventID, actionID string) error { + collection, err := s.app.FindCollectionByNameOrId(CollPlaybookDispatches) + if err != nil { + return err + } + r := core.NewRecord(collection) + r.Set("playbook_id", playbookID) + r.Set("playbook_version", playbookVersion) + r.Set("event_id", eventID) + r.Set("action_id", actionID) + return ledgerWrite(s.app.Save(r), "edastore: record playbook dispatch") +} + +func (s *Store) DeletePlaybookDispatches(_ context.Context, playbookID string) error { + _, err := s.app.DB().NewQuery( + "DELETE FROM " + CollPlaybookDispatches + " WHERE playbook_id = {:id}"). + Bind(map[string]any{"id": playbookID}).Execute() + if err != nil { + return fmt.Errorf("edastore: delete playbook dispatches: %w", err) + } + return nil +} + +// ledgerWrite turns the unique-index refusal into ErrAlreadyDispatched and +// leaves every other failure alone. Treating all errors as "already recorded" +// would turn an at-most-once ledger into a silent at-least-once dispatcher. +func ledgerWrite(err error, what string) error { + switch { + case err == nil: + return nil + case isUniqueViolation(err): + return ErrAlreadyDispatched + default: + return fmt.Errorf("%s: %w", what, err) + } +} + +// isUniqueViolation reports whether err is the unique-index refusal. +// PocketBase surfaces it as a validation failure rather than a typed error, +// so the message is what there is to match on. +func isUniqueViolation(err error) bool { + text := strings.ToLower(err.Error()) + return strings.Contains(text, "unique") || strings.Contains(text, "already exists") +} diff --git a/internal/infrastructure/edastore/edastore.go b/internal/infrastructure/edastore/edastore.go index 2adca1db6..15d2922ff 100644 --- a/internal/infrastructure/edastore/edastore.go +++ b/internal/infrastructure/edastore/edastore.go @@ -27,6 +27,8 @@ import ( "github.com/pocketbase/pocketbase" "github.com/pocketbase/pocketbase/core" _ "modernc.org/sqlite" + + "github.com/samcharles93/archie-core/internal/domain/storecontract" ) // Collection names. They are unprefixed because this store owns its database; @@ -40,19 +42,21 @@ const ( CollToolCalls = "tool_calls" ) -// Binding lifecycle. A binding is only live once a human approves it, which is -// an acceptance criterion of the epic rather than a convention. -const ( - StatusDraft = "draft" - StatusApproved = "approved" +// Sentinels are re-exported from the contract rather than redefined. Their +// exact message strings are the wire contract: staterpc matches on (code, +// canonical message) to rehydrate them on the client, so a second definition +// with different text would break errors.Is across the gRPC boundary without +// changing anything visible. +var ( + ErrBindingNotFound = storecontract.ErrBindingNotFound + ErrBindingOverlap = storecontract.ErrBindingOverlap + ErrBindingTransition = storecontract.ErrBindingTransition + ErrAlreadyDispatched = storecontract.ErrAlreadyDispatched + ErrMappingNotFound = storecontract.ErrMappingNotFound ) -var ( - // ErrBindingNotFound reports an operation naming a binding that is absent. - ErrBindingNotFound = errors.New("edastore: binding not found") - // ErrCaptureNotFound reports a capture that is absent or aged out. - ErrCaptureNotFound = errors.New("edastore: capture not found") -) +// ErrCaptureNotFound reports a capture that is absent or aged out. +var ErrCaptureNotFound = errors.New("edastore: capture not found") // Collections returns every collection this store owns. func Collections() []string { @@ -64,6 +68,9 @@ func Collections() []string { // Config describes one store. type Config struct { + // Cipher encrypts binding secrets at rest. Nil keeps them plaintext, + // which is the behaviour that predates the option. + Cipher BindingCipher // DBPath is the SQLite file PocketBase owns for these collections. DBPath string // DataDir holds PocketBase's auxiliary database and settings. @@ -71,7 +78,10 @@ type Config struct { } // Store is the PocketBase-backed EDA persistence. -type Store struct{ app *pocketbase.PocketBase } +type Store struct { + app *pocketbase.PocketBase + cipher BindingCipher +} // Open bootstraps the store and ensures its collections exist. func Open(cfg Config) (*Store, error) { @@ -100,7 +110,7 @@ func Open(cfg Config) (*Store, error) { if err := ensureCollections(app); err != nil { return nil, err } - return &Store{app: app}, nil + return &Store{app: app, cipher: cfg.Cipher}, nil } // App exposes the PocketBase application so one process can serve this store diff --git a/internal/infrastructure/edastore/opentest.go b/internal/infrastructure/edastore/opentest.go new file mode 100644 index 000000000..2168e553e --- /dev/null +++ b/internal/infrastructure/edastore/opentest.go @@ -0,0 +1,23 @@ +package edastore + +import ( + "path/filepath" + "testing" +) + +// OpenTest builds a throwaway store for tests, closed when the test ends. +// It mirrors store.OpenTest so a test that needs both stores wires them the +// same way. +func OpenTest(t *testing.T) *Store { + t.Helper() + dir := t.TempDir() + s, err := Open(Config{ + DBPath: filepath.Join(dir, "eda.sqlite"), + DataDir: filepath.Join(dir, "pb_data"), + }) + if err != nil { + t.Fatalf("edastore.OpenTest: %v", err) + } + t.Cleanup(func() { _ = s.Close() }) + return s +} diff --git a/internal/infrastructure/edastore/records.go b/internal/infrastructure/edastore/records.go deleted file mode 100644 index f079c7830..000000000 --- a/internal/infrastructure/edastore/records.go +++ /dev/null @@ -1,211 +0,0 @@ -package edastore - -import ( - "context" - "database/sql" - "errors" - "fmt" - "strings" - - "github.com/pocketbase/pocketbase/core" -) - -// Capture is one inbound event, stored whether or not anything understands it. -type Capture struct { - ID string - Source string - RemoteAddr string - ContentType string - Headers string - Body string - Authenticated bool -} - -// Binding ties a matcher and mapping to a workflow. -type Binding struct { - ID string - Name string - Source string - MappingID string - Workflow string - Owner string - Repo string - Version int64 - Status string - Secret string -} - -// Dispatch is one at-most-once binding dispatch ledger entry. -type Dispatch struct { - BindingID string - BindingVersion int64 - CaptureID string - // TaskID addresses the SQLite-owned task tables, which are not migrating. - TaskID int64 -} - -// PlaybookDispatch is one at-most-once playbook action ledger entry. -type PlaybookDispatch struct { - PlaybookID string - PlaybookVersion string - EventID string - ActionID string -} - -// InsertCapture stores one inbound event and returns its id. -func (s *Store) InsertCapture(_ context.Context, c Capture) (string, error) { - collection, err := s.app.FindCollectionByNameOrId(CollCaptures) - if err != nil { - return "", err - } - r := core.NewRecord(collection) - r.Set("source", c.Source) - r.Set("remote_addr", c.RemoteAddr) - r.Set("content_type", c.ContentType) - r.Set("headers", c.Headers) - r.Set("body", c.Body) - r.Set("authenticated", c.Authenticated) - if err := s.app.Save(r); err != nil { - return "", fmt.Errorf("edastore: insert capture: %w", err) - } - return r.Id, nil -} - -// Capture returns one stored event verbatim. -func (s *Store) Capture(_ context.Context, id string) (Capture, error) { - r, err := s.app.FindRecordById(CollCaptures, id) - if err != nil { - if errors.Is(err, sql.ErrNoRows) { - return Capture{}, ErrCaptureNotFound - } - return Capture{}, err - } - return Capture{ - ID: r.Id, - Source: r.GetString("source"), - RemoteAddr: r.GetString("remote_addr"), - ContentType: r.GetString("content_type"), - Headers: r.GetString("headers"), - Body: r.GetString("body"), - Authenticated: r.GetBool("authenticated"), - }, nil -} - -// InsertBinding stores a new binding. It is always created as a draft: the -// epic requires explicit human approval before a binding can run anything. -func (s *Store) InsertBinding(_ context.Context, b Binding) (string, error) { - collection, err := s.app.FindCollectionByNameOrId(CollBindings) - if err != nil { - return "", err - } - r := core.NewRecord(collection) - r.Set("name", b.Name) - r.Set("source", b.Source) - r.Set("mapping", b.MappingID) - r.Set("workflow", b.Workflow) - r.Set("owner", b.Owner) - r.Set("repo", b.Repo) - r.Set("version", 1) - r.Set("status", StatusDraft) - r.Set("secret", b.Secret) - if err := s.app.Save(r); err != nil { - return "", fmt.Errorf("edastore: insert binding: %w", err) - } - return r.Id, nil -} - -// GetBinding returns one binding. -func (s *Store) GetBinding(_ context.Context, id string) (Binding, error) { - r, err := s.app.FindRecordById(CollBindings, id) - if err != nil { - if errors.Is(err, sql.ErrNoRows) { - return Binding{}, ErrBindingNotFound - } - return Binding{}, err - } - return Binding{ - ID: r.Id, - Name: r.GetString("name"), - Source: r.GetString("source"), - MappingID: r.GetString("mapping"), - Workflow: r.GetString("workflow"), - Owner: r.GetString("owner"), - Repo: r.GetString("repo"), - Version: int64(r.GetInt("version")), - Status: r.GetString("status"), - Secret: r.GetString("secret"), - }, nil -} - -// ApproveBinding moves a draft binding to approved. It is the only way a -// binding becomes live. -func (s *Store) ApproveBinding(_ context.Context, id string) error { - r, err := s.app.FindRecordById(CollBindings, id) - if err != nil { - if errors.Is(err, sql.ErrNoRows) { - return ErrBindingNotFound - } - return err - } - r.Set("status", StatusApproved) - r.Set("version", r.GetInt("version")+1) - if err := s.app.Save(r); err != nil { - return fmt.Errorf("edastore: approve binding: %w", err) - } - return nil -} - -// RecordDispatch writes one binding dispatch, reporting whether it was new. -// The (binding, capture) uniqueness is enforced by the collection's index, so -// a duplicate is refused by the schema rather than by the caller. -func (s *Store) RecordDispatch(_ context.Context, d Dispatch) (bool, error) { - collection, err := s.app.FindCollectionByNameOrId(CollBindingDispatches) - if err != nil { - return false, err - } - r := core.NewRecord(collection) - r.Set("binding", d.BindingID) - r.Set("binding_version", d.BindingVersion) - r.Set("capture", d.CaptureID) - r.Set("task_id", d.TaskID) - return savedOrDuplicate(s.app, r, "edastore: record dispatch") -} - -// RecordPlaybookDispatch writes one playbook action dispatch, reporting -// whether it was new. -func (s *Store) RecordPlaybookDispatch(_ context.Context, d PlaybookDispatch) (bool, error) { - collection, err := s.app.FindCollectionByNameOrId(CollPlaybookDispatches) - if err != nil { - return false, err - } - r := core.NewRecord(collection) - r.Set("playbook_id", d.PlaybookID) - r.Set("playbook_version", d.PlaybookVersion) - r.Set("event_id", d.EventID) - r.Set("action_id", d.ActionID) - return savedOrDuplicate(s.app, r, "edastore: record playbook dispatch") -} - -// savedOrDuplicate saves a ledger record, translating the unique-index -// violation into "already recorded" rather than an error. Anything else is a -// real failure and is returned: silently swallowing every save error here -// would turn a broken ledger into a silent at-least-once dispatcher. -func savedOrDuplicate(app core.App, r *core.Record, what string) (bool, error) { - err := app.Save(r) - switch { - case err == nil: - return true, nil - case isUniqueViolation(err): - return false, nil - default: - return false, fmt.Errorf("%s: %w", what, err) - } -} - -// isUniqueViolation reports whether err is the unique-index refusal. PocketBase -// surfaces it as a validation failure rather than a typed error, so the text is -// what there is to match on. -func isUniqueViolation(err error) bool { - text := strings.ToLower(err.Error()) - return strings.Contains(text, "unique") || strings.Contains(text, "already exists") -} diff --git a/internal/infrastructure/edastore/schema.go b/internal/infrastructure/edastore/schema.go index f7c83f0ad..9d125b24c 100644 --- a/internal/infrastructure/edastore/schema.go +++ b/internal/infrastructure/edastore/schema.go @@ -7,6 +7,8 @@ import ( "path/filepath" "github.com/pocketbase/pocketbase/core" + + "github.com/samcharles93/archie-core/internal/domain/binding" ) // isDataDB reports whether PocketBase is asking for its main database, as @@ -73,7 +75,13 @@ func ensureCaptures(app core.App) error { &core.JSONField{Name: "headers", MaxSize: 1 << 20}, &core.TextField{Name: "body", Max: 1 << 20}, &core.BoolField{Name: "authenticated"}, - &core.AutodateField{Name: "received_at", OnCreate: true}, + // received_at is written by the store, not an autodate field, because + // it is also the sort key. PocketBase autodates are millisecond + // precision and record ids are random, so two captures arriving in + // the same millisecond would order arbitrarily -- the old store got + // insertion order free from an autoincrement id. capturedAtLayout is + // fixed-width so lexicographic order is chronological order. + &core.TextField{Name: "received_at"}, ) c.AddIndex("idx_captures_source", false, "source, received_at", "") return save(app, c) @@ -111,9 +119,14 @@ func ensureBindings(app core.App) error { &core.TextField{Name: "owner"}, &core.TextField{Name: "repo"}, &core.NumberField{Name: "version"}, - // status carries the approval gate. It is deliberately not defaulted - // to anything live: a binding reaches "approved" only by ApproveBinding. - &core.SelectField{Name: "status", Values: []string{StatusDraft, StatusApproved}, MaxSelect: 1}, + // status is the domain's three-state lifecycle, not a local + // vocabulary: draft -> pending_approval -> armed. Only + // ApproveBinding reaches armed, which is the epic's approval gate. + &core.SelectField{Name: "status", MaxSelect: 1, Values: []string{ + string(binding.StatusDraft), + string(binding.StatusPendingApproval), + string(binding.StatusArmed), + }}, &core.TextField{Name: "secret"}, &core.AutodateField{Name: "created_at", OnCreate: true}, &core.AutodateField{Name: "updated_at", OnCreate: true, OnUpdate: true}, diff --git a/internal/infrastructure/edastore/schema_test.go b/internal/infrastructure/edastore/schema_test.go index 242d64534..798d2c4e0 100644 --- a/internal/infrastructure/edastore/schema_test.go +++ b/internal/infrastructure/edastore/schema_test.go @@ -7,6 +7,8 @@ import ( "github.com/pocketbase/pocketbase/core" + "github.com/samcharles93/archie-core/internal/domain/binding" + "github.com/samcharles93/archie-core/internal/domain/storecontract" "github.com/samcharles93/archie-core/internal/infrastructure/edastore" ) @@ -46,23 +48,13 @@ func TestCollectionsAreCreated(t *testing.T) { // refused by the schema rather than by the caller remembering to ignore it. func TestBindingDispatchIsIdempotent(t *testing.T) { st := newStore(t) - first, err := st.RecordDispatch(t.Context(), edastore.Dispatch{ - BindingID: "b1", BindingVersion: 1, CaptureID: "c1", TaskID: 42, - }) - if err != nil { + if err := st.RecordDispatch(t.Context(), "b1", 1, "c1", 42); err != nil { t.Fatalf("first RecordDispatch() error = %v", err) } - if !first { - t.Fatal("first RecordDispatch() = false, want true: a fresh dispatch must be recorded") - } - second, err := st.RecordDispatch(t.Context(), edastore.Dispatch{ - BindingID: "b1", BindingVersion: 1, CaptureID: "c1", TaskID: 99, - }) - if err != nil { - t.Fatalf("second RecordDispatch() error = %v", err) - } - if second { - t.Error("second RecordDispatch() = true, want false: (binding, capture) is an at-most-once ledger") + // A replay of the same (binding, capture) must be refused, not run again. + err := st.RecordDispatch(t.Context(), "b1", 1, "c1", 99) + if !errors.Is(err, storecontract.ErrAlreadyDispatched) { + t.Errorf("second RecordDispatch() error = %v, want ErrAlreadyDispatched: (binding, capture) is an at-most-once ledger", err) } } @@ -70,12 +62,12 @@ func TestBindingDispatchIsIdempotent(t *testing.T) { // four-part playbook key (playbook, version, event, action). func TestPlaybookDispatchIsIdempotent(t *testing.T) { st := newStore(t) - key := edastore.PlaybookDispatch{PlaybookID: "p1", PlaybookVersion: "v1", EventID: "e1", ActionID: "a1"} - if ok, err := st.RecordPlaybookDispatch(t.Context(), key); err != nil || !ok { - t.Fatalf("first RecordPlaybookDispatch() = %v, %v; want true, nil", ok, err) + if err := st.RecordPlaybookDispatch(t.Context(), "p1", "v1", "e1", "a1"); err != nil { + t.Fatalf("first RecordPlaybookDispatch() error = %v", err) } - if ok, err := st.RecordPlaybookDispatch(t.Context(), key); err != nil || ok { - t.Fatalf("second RecordPlaybookDispatch() = %v, %v; want false, nil", ok, err) + err := st.RecordPlaybookDispatch(t.Context(), "p1", "v1", "e1", "a1") + if !errors.Is(err, storecontract.ErrAlreadyDispatched) { + t.Errorf("second RecordPlaybookDispatch() error = %v, want ErrAlreadyDispatched", err) } } @@ -84,7 +76,9 @@ func TestPlaybookDispatchIsIdempotent(t *testing.T) { // binding created without a status must not default to anything live. func TestBindingStartsAsDraft(t *testing.T) { st := newStore(t) - id, err := st.InsertBinding(t.Context(), edastore.Binding{Name: "n", Source: "sentry", Workflow: "implement"}) + id, err := st.InsertBinding(t.Context(), binding.Binding{ + Name: "n", Matcher: binding.Matcher{Source: "sentry"}, Workflow: "implement", + }) if err != nil { t.Fatalf("InsertBinding() error = %v", err) } @@ -92,15 +86,15 @@ func TestBindingStartsAsDraft(t *testing.T) { if err != nil { t.Fatalf("GetBinding() error = %v", err) } - if b.Status != edastore.StatusDraft { - t.Errorf("new binding status = %q, want %q: a binding must not be live before approval", b.Status, edastore.StatusDraft) + if b.Status != binding.StatusDraft { + t.Errorf("new binding status = %q, want %q: a binding must not be live before approval", b.Status, binding.StatusDraft) } } // TestApproveRejectsUnknownBinding pins the sentinel the gRPC layer maps. func TestApproveRejectsUnknownBinding(t *testing.T) { st := newStore(t) - if err := st.ApproveBinding(t.Context(), "nosuchbinding"); !errors.Is(err, edastore.ErrBindingNotFound) { + if err := st.ApproveBinding(t.Context(), "nosuchbinding"); !errors.Is(err, storecontract.ErrBindingNotFound) { t.Errorf("ApproveBinding(unknown) error = %v, want ErrBindingNotFound", err) } } @@ -111,19 +105,90 @@ func TestApproveRejectsUnknownBinding(t *testing.T) { func TestCaptureRoundTripsPayload(t *testing.T) { st := newStore(t) body := `{"action":"created","issue":{"number":7,"title":"it broke"}}` - id, err := st.InsertCapture(t.Context(), edastore.Capture{ + if _, err := st.InsertCapture(t.Context(), storecontract.CapturedEvent{ Source: "sentry", Body: body, Headers: `{"X-Hook":"1"}`, ContentType: "application/json", - }) - if err != nil { + }, 0, 0); err != nil { t.Fatalf("InsertCapture() error = %v", err) } - got, err := st.Capture(t.Context(), id) + list, err := st.ListCaptures(t.Context(), 10) if err != nil { - t.Fatalf("Capture() error = %v", err) + t.Fatalf("ListCaptures() error = %v", err) } + if len(list) != 1 { + t.Fatalf("ListCaptures() returned %d captures, want 1", len(list)) + } + got := list[0] if got.Body != body { t.Errorf("Body round-trip = %q, want %q: the raw payload is what field mapping is designed against", got.Body, body) } } var _ = core.Collection{} + +// TestBindingLifecycleIsThreeStates pins draft -> pending_approval -> armed. +// The states are the domain's, not this package's: collapsing them (as an +// earlier version of this store did) removes the review step while still +// looking like an approval gate, which is the worst of both. +func TestBindingLifecycleIsThreeStates(t *testing.T) { + st := newStore(t) + id, err := st.InsertBinding(t.Context(), binding.Binding{ + Name: "n", Matcher: binding.Matcher{Source: "sentry"}, Workflow: "implement", + }) + if err != nil { + t.Fatalf("InsertBinding() error = %v", err) + } + + // A draft cannot skip review. + if err := st.ApproveBinding(t.Context(), id); !errors.Is(err, storecontract.ErrBindingTransition) { + t.Fatalf("ApproveBinding(draft) error = %v, want ErrBindingTransition: draft must not skip review", err) + } + + // Editing sends it to pending_approval. + if err := st.UpdateBinding(t.Context(), binding.Binding{ + ID: id, Name: "n2", Matcher: binding.Matcher{Source: "sentry"}, Workflow: "implement", + }); err != nil { + t.Fatalf("UpdateBinding() error = %v", err) + } + b, err := st.GetBinding(t.Context(), id) + if err != nil { + t.Fatalf("GetBinding() error = %v", err) + } + if b.Status != binding.StatusPendingApproval { + t.Fatalf("status after edit = %q, want %q", b.Status, binding.StatusPendingApproval) + } + + // Approval arms it, and only from pending_approval. + if err := st.ApproveBinding(t.Context(), id); err != nil { + t.Fatalf("ApproveBinding(pending_approval) error = %v", err) + } + if b, err = st.GetBinding(t.Context(), id); err != nil || b.Status != binding.StatusArmed { + t.Fatalf("status after approve = %q (err %v), want %q", b.Status, err, binding.StatusArmed) + } + if err := st.ApproveBinding(t.Context(), id); !errors.Is(err, storecontract.ErrBindingTransition) { + t.Errorf("re-approving an armed binding = %v, want ErrBindingTransition", err) + } + + // Only armed bindings dispatch. + armed, err := st.ArmedBindingsForSource(t.Context(), "sentry") + if err != nil || len(armed) != 1 { + t.Fatalf("ArmedBindingsForSource() = %d bindings (err %v), want 1", len(armed), err) + } +} + +// TestOneBindingPerSource pins the overlap guard: a second binding on a +// source that already has one is refused, so a capture can never match two. +func TestOneBindingPerSource(t *testing.T) { + st := newStore(t) + mk := func() error { + _, err := st.InsertBinding(t.Context(), binding.Binding{ + Name: "n", Matcher: binding.Matcher{Source: "sentry"}, Workflow: "implement", + }) + return err + } + if err := mk(); err != nil { + t.Fatalf("first InsertBinding() error = %v", err) + } + if err := mk(); !errors.Is(err, storecontract.ErrBindingOverlap) { + t.Errorf("second InsertBinding() error = %v, want ErrBindingOverlap", err) + } +} diff --git a/internal/infrastructure/edastore/testsupport_test.go b/internal/infrastructure/edastore/testsupport_test.go new file mode 100644 index 000000000..3a817a523 --- /dev/null +++ b/internal/infrastructure/edastore/testsupport_test.go @@ -0,0 +1,30 @@ +package edastore + +import ( + "testing" + + "github.com/samcharles93/archie-core/internal/domain/binding" +) + +// bindingInput is the small shape the cipher tests need, kept separate from +// binding.Binding so a domain field addition does not churn every test. +type bindingInput struct { + Name string + Source string + Workflow string + Secret string +} + +func insertBinding(t *testing.T, s *Store, in bindingInput) string { + t.Helper() + id, err := s.InsertBinding(t.Context(), binding.Binding{ + Name: in.Name, + Matcher: binding.Matcher{Source: in.Source}, + Workflow: in.Workflow, + Secret: in.Secret, + }) + if err != nil { + t.Fatalf("InsertBinding() error = %v", err) + } + return id +} diff --git a/internal/infrastructure/stateadmin/stateadmin.go b/internal/infrastructure/stateadmin/stateadmin.go index 4c8dd6fec..62c31e221 100644 --- a/internal/infrastructure/stateadmin/stateadmin.go +++ b/internal/infrastructure/stateadmin/stateadmin.go @@ -50,6 +50,11 @@ var refusedPrefixes = []string{"/api/backups", "/api/sql"} // collection name is prefixed so it cannot collide with a PocketBase system // collection, and every query must select an "id": PocketBase keys view // records on it, and resources is keyed by kind rather than a row id. +// +// Only the task-lifecycle tables appear here. The event-capture tables moved +// to internal/infrastructure/edastore, which owns them as real, editable +// collections; mirroring them as read-only views would be a second, weaker +// surface over data that already has a better one. var views = []struct { name string query string @@ -57,7 +62,6 @@ var views = []struct { {"archie_tasks", `SELECT id, owner, repo, issue_number, title, status, workflow, stage, branch, pr_number, tokens_used, iterations, attempt, park_reason, identity, created_at, updated_at FROM tasks`}, {"archie_transitions", `SELECT id, task_id, at, from_status, to_status, detail FROM transitions`}, {"archie_events", `SELECT id, at, kind, task_id, repo, issue, workflow, stage, attempt FROM events`}, - {"archie_bindings", `SELECT id, name, source, mapping_id, workflow, owner, repo, version, status FROM bindings`}, {"archie_identities", `SELECT id, kind, display_name, lifecycle, version, created_at, updated_at FROM identities`}, {"archie_resources", `SELECT kind AS id, kind, version, updated_at FROM resources`}, } diff --git a/internal/infrastructure/staterpc/attribution_test.go b/internal/infrastructure/staterpc/attribution_test.go index 68a5ba91b..8535e00b4 100644 --- a/internal/infrastructure/staterpc/attribution_test.go +++ b/internal/infrastructure/staterpc/attribution_test.go @@ -31,7 +31,7 @@ func TestEventAttributionSurvivesTheStateStoreBoundary(t *testing.T) { local := store.OpenTest(t) var c contract = local if mode == "grpc" { - c = remoteTaskStore(t, local, nil) + c = remoteTaskStore(t, local, nil, nil) } task, err := c.EnqueueChatTask(ctx, "acme", "widget", "title", "body", "implement", "") diff --git a/internal/infrastructure/staterpc/capture_stream_test.go b/internal/infrastructure/staterpc/capture_stream_test.go index f2db99e48..2bc059e87 100644 --- a/internal/infrastructure/staterpc/capture_stream_test.go +++ b/internal/infrastructure/staterpc/capture_stream_test.go @@ -5,37 +5,49 @@ import ( "testing" "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" ) func TestCaptureListsExceedUnaryMessageLimit(t *testing.T) { local := store.OpenTest(t) + eda := edastore.OpenTest(t) body := strings.Repeat("x", 256<<10) for range 20 { - if _, err := local.InsertCapture(t.Context(), store.CapturedEvent{Source: "large", Body: body, Authenticated: true}, 0, 0); err != nil { + if _, err := eda.InsertCapture(t.Context(), store.CapturedEvent{Source: "large", Body: body, Authenticated: true}, 0, 0); err != nil { t.Fatal(err) } } + // A binding's mapping is a real relation now, so it must point at a + // mapping that exists; the store refuses a dangling id. + mappingID, mapErr := eda.InsertMapping(t.Context(), mapping.Mapping{ + Name: "m", + Fields: []mapping.Field{{Name: "title", Path: "title", Type: mapping.TypeString}}, + }) + if mapErr != nil { + t.Fatal(mapErr) + } // ListUndispatchedCaptures only returns sources with an armed binding - // (internal/store/bindings.go), so "large" needs one taken through the + // (edastore.ArmedBindingsForSource), so "large" needs one taken through the // public draft -> pending_approval -> armed lifecycle. - id, err := local.InsertBinding(t.Context(), binding.Binding{ + id, err := eda.InsertBinding(t.Context(), binding.Binding{ Name: "large binding", Matcher: binding.Matcher{Source: "large"}, - MappingID: 1, Workflow: "implement", Secret: "0123456789abcdef0123456789abcdef", + MappingID: mappingID, Workflow: "implement", Secret: "0123456789abcdef0123456789abcdef", }) if err != nil { t.Fatal(err) } - if err := local.UpdateBinding(t.Context(), binding.Binding{ + if err := eda.UpdateBinding(t.Context(), binding.Binding{ ID: id, Name: "large binding", Matcher: binding.Matcher{Source: "large"}, - MappingID: 1, Workflow: "implement", Secret: "0123456789abcdef0123456789abcdef", + MappingID: mappingID, Workflow: "implement", Secret: "0123456789abcdef0123456789abcdef", }); err != nil { t.Fatal(err) } - if err := local.ApproveBinding(t.Context(), id); err != nil { + if err := eda.ApproveBinding(t.Context(), id); err != nil { t.Fatal(err) } - remote := remoteContract(t, local) + remote := remoteEDA(t, local, eda) for _, undispatched := range []bool{false, true} { var captures []store.CapturedEvent var err error diff --git a/internal/infrastructure/staterpc/client.go b/internal/infrastructure/staterpc/client.go index 57a23cb0c..3037918e8 100644 --- a/internal/infrastructure/staterpc/client.go +++ b/internal/infrastructure/staterpc/client.go @@ -257,10 +257,10 @@ func (c *Client) TokensByDay(ctx context.Context, days int) ([]storecontract.Day // Capture -func (c *Client) InsertCapture(ctx context.Context, ce storecontract.CapturedEvent, retention time.Duration, maxEvents int) (int64, error) { +func (c *Client) InsertCapture(ctx context.Context, ce storecontract.CapturedEvent, retention time.Duration, maxEvents int) (string, error) { r, err := c.client.InsertCapture(ctx, &pb.InsertCaptureRequest{Capture: capturedEventProto(ce), RetentionSeconds: int64(retention.Seconds()), MaxEvents: int64(maxEvents)}) if err != nil { - return 0, unmapError(err) + return "", unmapError(err) } return r.Id, nil } @@ -357,15 +357,15 @@ func (c *Client) ListCaptures(ctx context.Context, limit int) ([]storecontract.C // Mapping -func (c *Client) InsertMapping(ctx context.Context, m mapping.Mapping) (int64, error) { +func (c *Client) InsertMapping(ctx context.Context, m mapping.Mapping) (string, error) { r, err := c.client.InsertMapping(ctx, &pb.InsertMappingRequest{Mapping: mappingProto(m)}) if err != nil { - return 0, unmapError(err) + return "", unmapError(err) } return r.Id, nil } -func (c *Client) GetMapping(ctx context.Context, id int64) (*mapping.Mapping, error) { +func (c *Client) GetMapping(ctx context.Context, id string) (*mapping.Mapping, error) { r, err := c.client.GetMapping(ctx, &pb.GetMappingRequest{Id: id}) if err != nil { return nil, unmapError(err) @@ -390,22 +390,22 @@ func (c *Client) UpdateMapping(ctx context.Context, m mapping.Mapping) error { return unmapError(err) } -func (c *Client) DeleteMapping(ctx context.Context, id int64) error { +func (c *Client) DeleteMapping(ctx context.Context, id string) error { _, err := c.client.DeleteMapping(ctx, &pb.DeleteMappingRequest{Id: id}) return unmapError(err) } // Binding -func (c *Client) InsertBinding(ctx context.Context, b binding.Binding) (int64, error) { +func (c *Client) InsertBinding(ctx context.Context, b binding.Binding) (string, error) { r, err := c.client.InsertBinding(ctx, &pb.InsertBindingRequest{Binding: bindingProto(b)}) if err != nil { - return 0, unmapError(err) + return "", unmapError(err) } return r.Id, nil } -func (c *Client) GetBinding(ctx context.Context, id int64) (*binding.Binding, error) { +func (c *Client) GetBinding(ctx context.Context, id string) (*binding.Binding, error) { r, err := c.client.GetBinding(ctx, &pb.GetBindingRequest{Id: id}) if err != nil { return nil, unmapError(err) @@ -430,12 +430,12 @@ func (c *Client) UpdateBinding(ctx context.Context, b binding.Binding) error { return unmapError(err) } -func (c *Client) DeleteBinding(ctx context.Context, id int64) error { +func (c *Client) DeleteBinding(ctx context.Context, id string) error { _, err := c.client.DeleteBinding(ctx, &pb.DeleteBindingRequest{Id: id}) return unmapError(err) } -func (c *Client) ApproveBinding(ctx context.Context, id int64) error { +func (c *Client) ApproveBinding(ctx context.Context, id string) error { _, err := c.client.ApproveBinding(ctx, &pb.ApproveBindingRequest{Id: id}) return unmapError(err) } @@ -450,7 +450,7 @@ func (c *Client) ArmedBindingsForSource(ctx context.Context, source string) ([]b return mapValues(r.Bindings, bindingValue), nil } -func (c *Client) RecordDispatch(ctx context.Context, bindingID, bindingVersion, captureID, taskID int64) error { +func (c *Client) RecordDispatch(ctx context.Context, bindingID string, bindingVersion int64, captureID string, taskID int64) error { _, err := c.client.RecordDispatch(ctx, &pb.RecordDispatchRequest{BindingId: bindingID, BindingVersion: bindingVersion, CaptureId: captureID, TaskId: taskID}) return unmapError(err) } @@ -489,7 +489,7 @@ func (c *Client) ListUndispatchedCaptures(ctx context.Context, sources []string, // BindingTaskCreator -func (c *Client) EnqueueBindingTask(ctx context.Context, owner, repo, title, body, wf, identity string, bindingID int64, bindingVersion int) (*task.Task, error) { +func (c *Client) EnqueueBindingTask(ctx context.Context, owner, repo, title, body, wf, identity, bindingID string, bindingVersion int) (*task.Task, error) { r, err := c.client.EnqueueBindingTask(ctx, &pb.EnqueueBindingTaskRequest{Owner: owner, Repo: repo, Title: title, Body: body, Workflow: wf, Identity: identity, BindingId: bindingID, BindingVersion: int64(bindingVersion)}) if err != nil { return nil, unmapError(err) diff --git a/internal/infrastructure/staterpc/conformance_test.go b/internal/infrastructure/staterpc/conformance_test.go index 78b9ae8a5..b2a322248 100644 --- a/internal/infrastructure/staterpc/conformance_test.go +++ b/internal/infrastructure/staterpc/conformance_test.go @@ -14,6 +14,7 @@ import ( "github.com/samcharles93/archie-core/internal/domain/binding" "github.com/samcharles93/archie-core/internal/domain/mapping" "github.com/samcharles93/archie-core/internal/events" + "github.com/samcharles93/archie-core/internal/infrastructure/edastore" "github.com/samcharles93/archie-core/internal/store" ) @@ -24,13 +25,19 @@ import ( // docs/prds/state-store-contract.md §11's conformance requirement. type contract interface { store.TaskStore + store.BindingTaskCreator + store.ConfigSnapshotStore + store.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 - store.BindingTaskCreator - store.ConfigSnapshotStore - store.ApplyStatusStore } // playbookContract is the playbook-dispatch idempotency-ledger surface, split @@ -48,24 +55,43 @@ type taskLogContract interface { store.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 { + t.Helper() + return remoteTaskStore(t, local, nil, eda) +} + func remoteContract(t *testing.T, local *store.Store) contract { t.Helper() - return remoteTaskStore(t, local, nil) + return remoteTaskStore(t, local, nil, nil) } // remoteTaskStore serves local behind a bufconn listener with a task-log // reader attached, and returns a client for it. The reader is a parameter // because the log files are internal/logging's, not the store's: this contract // fronts a reader rather than a table. -func remoteTaskStore(t *testing.T, local *store.Store, logs store.TaskLogStore) *Client { +// remoteTaskStore fronts the same two stores the real composition wires: the +// 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 { t.Helper() listener := bufconn.Listen(1 << 20) server := grpc.NewServer() - RegisterServer(server, Deps{ - Tasks: local, Captures: local, Mappings: local, Bindings: local, - BindingDispatcher: local, BindingTaskCreator: local, PlaybookDispatcher: local, ConfigSnapshots: local, ApplyStatus: local, + deps := Deps{ + Tasks: local, BindingTaskCreator: local, + ConfigSnapshots: local, ApplyStatus: local, TaskLogs: logs, - }) + } + if eda != nil { + deps.Captures = eda + deps.Mappings = eda + deps.Bindings = eda + deps.BindingDispatcher = eda + deps.PlaybookDispatcher = eda + } + RegisterServer(server, deps) go func() { _ = server.Serve(listener) }() t.Cleanup(func() { server.Stop(); _ = listener.Close() }) conn, err := grpc.NewClient("passthrough:///state", @@ -87,11 +113,14 @@ func TestStateStoreConformance(t *testing.T) { t.Run(mode, func(t *testing.T) { ctx := t.Context() local := store.OpenTest(t) + eda := edastore.OpenTest(t) var c contract = local - var pc playbookContract = local + var ec edaContract = eda + var pc playbookContract = eda if mode == "grpc" { - remote := remoteTaskStore(t, local, nil) + remote := remoteTaskStore(t, local, nil, eda) c = remote + ec = remote pc = remote } @@ -253,30 +282,30 @@ func TestStateStoreConformance(t *testing.T) { } // Mapping: found=false, ErrMappingNotFound. - mappingID, err := c.InsertMapping(ctx, mapping.Mapping{Name: "m1", Fields: []mapping.Field{{Name: "a", Path: "a", Type: mapping.TypeString}}}) - if err != nil || mappingID == 0 { + mappingID, err := ec.InsertMapping(ctx, mapping.Mapping{Name: "m1", Fields: []mapping.Field{{Name: "a", Path: "a", Type: mapping.TypeString}}}) + if err != nil || mappingID == "" { t.Fatalf("InsertMapping: %v %v", mappingID, err) } - missingMapping, err := c.GetMapping(ctx, mappingID+999999) + missingMapping, err := ec.GetMapping(ctx, "rabsent00000000") if err != nil || missingMapping != nil { t.Fatalf("GetMapping missing: %+v %v", missingMapping, err) } - gotMapping, err := c.GetMapping(ctx, mappingID) + gotMapping, err := ec.GetMapping(ctx, mappingID) if err != nil || gotMapping == nil || gotMapping.Name != "m1" { t.Fatalf("GetMapping: %+v %v", gotMapping, err) } - if _, err := c.ListMappings(ctx); err != nil { + if _, err := ec.ListMappings(ctx); err != nil { t.Fatalf("ListMappings: %v", err) } gotMapping.Name = "m1-renamed" - if err := c.UpdateMapping(ctx, *gotMapping); err != nil { + if err := ec.UpdateMapping(ctx, *gotMapping); err != nil { t.Fatalf("UpdateMapping: %v", err) } - err = c.UpdateMapping(ctx, mapping.Mapping{ID: mappingID + 999999, Name: "x", Fields: gotMapping.Fields}) + err = ec.UpdateMapping(ctx, mapping.Mapping{ID: "rabsent00000000", Name: "x", Fields: gotMapping.Fields}) if !errors.Is(err, store.ErrMappingNotFound) { t.Fatalf("UpdateMapping missing = %v, want ErrMappingNotFound", err) } - err = c.DeleteMapping(ctx, mappingID+999999) + err = ec.DeleteMapping(ctx, "rabsent00000000") if !errors.Is(err, store.ErrMappingNotFound) { t.Fatalf("DeleteMapping missing = %v, want ErrMappingNotFound", err) } @@ -284,63 +313,63 @@ func TestStateStoreConformance(t *testing.T) { // Binding: found=false, ErrBindingNotFound, ErrBindingOverlap, // ErrBindingTransition, and the dispatch surface incl. // ErrAlreadyDispatched. - bindingID, err := c.InsertBinding(ctx, binding.Binding{ + bindingID, err := ec.InsertBinding(ctx, binding.Binding{ Name: "b1", Matcher: binding.Matcher{Source: "sentry"}, MappingID: mappingID, Workflow: "implement", Secret: "0123456789abcdef0123456789abcdef", }) - if err != nil || bindingID == 0 { + if err != nil || bindingID == "" { t.Fatalf("InsertBinding: %v %v", bindingID, err) } - _, err = c.InsertBinding(ctx, binding.Binding{ + _, err = ec.InsertBinding(ctx, binding.Binding{ Name: "b2", Matcher: binding.Matcher{Source: "sentry"}, MappingID: mappingID, Workflow: "implement", Secret: "0123456789abcdef0123456789abcdef", }) if !errors.Is(err, store.ErrBindingOverlap) { t.Fatalf("InsertBinding overlap = %v, want ErrBindingOverlap", err) } - missingBinding, err := c.GetBinding(ctx, bindingID+999999) + missingBinding, err := ec.GetBinding(ctx, "rabsent00000000") if err != nil || missingBinding != nil { t.Fatalf("GetBinding missing: %+v %v", missingBinding, err) } - gotBinding, err := c.GetBinding(ctx, bindingID) + gotBinding, err := ec.GetBinding(ctx, bindingID) if err != nil || gotBinding == nil || gotBinding.Name != "b1" { t.Fatalf("GetBinding: %+v %v", gotBinding, err) } - if _, err := c.ListBindings(ctx); err != nil { + if _, err := ec.ListBindings(ctx); err != nil { t.Fatalf("ListBindings: %v", err) } - err = c.ApproveBinding(ctx, bindingID) + err = ec.ApproveBinding(ctx, bindingID) if !errors.Is(err, store.ErrBindingTransition) { t.Fatalf("ApproveBinding from draft = %v, want ErrBindingTransition", err) } - err = c.DeleteBinding(ctx, bindingID+999999) + err = ec.DeleteBinding(ctx, "rabsent00000000") if !errors.Is(err, store.ErrBindingNotFound) { t.Fatalf("DeleteBinding missing = %v, want ErrBindingNotFound", err) } // Capture + dispatch. - captureID, err := c.InsertCapture(ctx, store.CapturedEvent{Source: "sentry", Body: `{"id":1}`, Authenticated: true}, 0, 0) - if err != nil || captureID == 0 { + captureID, err := ec.InsertCapture(ctx, store.CapturedEvent{Source: "sentry", Body: `{"id":1}`, Authenticated: true}, 0, 0) + if err != nil || captureID == "" { t.Fatalf("InsertCapture: %v %v", captureID, err) } - if _, err := c.ListCaptures(ctx, 10); err != nil { + if _, err := ec.ListCaptures(ctx, 10); err != nil { t.Fatalf("ListCaptures: %v", err) } - if _, err := c.ArmedBindingsForSource(ctx, "sentry"); err != nil { + if _, err := ec.ArmedBindingsForSource(ctx, "sentry"); err != nil { t.Fatalf("ArmedBindingsForSource: %v", err) } bindingTask, err := c.EnqueueBindingTask(ctx, "acme", "widget", "t", "b", "implement", "", bindingID, 1) if err != nil || bindingTask == nil { t.Fatalf("EnqueueBindingTask: %+v %v", bindingTask, err) } - if err := c.RecordDispatch(ctx, bindingID, 1, captureID, bindingTask.ID); err != nil { + if err := ec.RecordDispatch(ctx, bindingID, 1, captureID, bindingTask.ID); err != nil { t.Fatalf("RecordDispatch: %v", err) } - err = c.RecordDispatch(ctx, bindingID, 1, captureID, bindingTask.ID) + err = ec.RecordDispatch(ctx, bindingID, 1, captureID, bindingTask.ID) if !errors.Is(err, store.ErrAlreadyDispatched) { t.Fatalf("RecordDispatch dup = %v, want ErrAlreadyDispatched", err) } - if _, err := c.ListUndispatchedCaptures(ctx, []string{"sentry"}, 10); err != nil { + if _, err := ec.ListUndispatchedCaptures(ctx, []string{"sentry"}, 10); err != nil { t.Fatalf("ListUndispatchedCaptures: %v", err) } diff --git a/internal/infrastructure/staterpc/task_grants_test.go b/internal/infrastructure/staterpc/task_grants_test.go index fac2710aa..46bbf252e 100644 --- a/internal/infrastructure/staterpc/task_grants_test.go +++ b/internal/infrastructure/staterpc/task_grants_test.go @@ -13,8 +13,10 @@ import ( "google.golang.org/grpc/test/bufconn" "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/events" + "github.com/samcharles93/archie-core/internal/infrastructure/edastore" "github.com/samcharles93/archie-core/internal/store" ) @@ -31,7 +33,15 @@ func grantsServer(t *testing.T, adminToken string) (grants *TaskGrants, dial fun grpc.ChainUnaryInterceptor(grants.UnaryInterceptor(adminToken)), grpc.ChainStreamInterceptor(grants.StreamInterceptor(adminToken)), ) - RegisterServer(server, Deps{Tasks: local, Captures: local, Bindings: local, BindingDispatcher: local, PlaybookDispatcher: local, Grants: grants, ConfigSnapshots: local, ApplyStatus: local}) + // One event-capture store serves every EDA surface, as the real + // composition does: separate instances would not share a database. + eda := edastore.OpenTest(t) + RegisterServer(server, Deps{ + Tasks: local, ConfigSnapshots: local, ApplyStatus: local, + Captures: eda, Mappings: eda, Bindings: eda, + BindingDispatcher: eda, PlaybookDispatcher: eda, + Grants: grants, + }) go func() { _ = server.Serve(listener) }() t.Cleanup(func() { server.Stop(); _ = listener.Close() }) @@ -74,18 +84,27 @@ func TestCaptureStreamsCarryTheAdminToken(t *testing.T) { } } // ListUndispatchedCaptures only returns sources with an armed binding - // (internal/store/bindings.go), so "large" needs one taken through the + // A binding's mapping is a real relation now, so it must point at a + // mapping that exists; the store refuses a dangling id. + mappingID, mapErr := admin.InsertMapping(t.Context(), mapping.Mapping{ + Name: "m", + Fields: []mapping.Field{{Name: "title", Path: "title", Type: mapping.TypeString}}, + }) + if mapErr != nil { + t.Fatal(mapErr) + } + // (edastore.ArmedBindingsForSource), so "large" needs one taken through the // public draft -> pending_approval -> armed lifecycle. id, err := admin.InsertBinding(ctx, binding.Binding{ Name: "large binding", Matcher: binding.Matcher{Source: "large"}, - MappingID: 1, Workflow: "implement", Secret: "0123456789abcdef0123456789abcdef", + MappingID: mappingID, Workflow: "implement", Secret: "0123456789abcdef0123456789abcdef", }) if err != nil { t.Fatal(err) } if err := admin.UpdateBinding(ctx, binding.Binding{ ID: id, Name: "large binding", Matcher: binding.Matcher{Source: "large"}, - MappingID: 1, Workflow: "implement", Secret: "0123456789abcdef0123456789abcdef", + MappingID: mappingID, Workflow: "implement", Secret: "0123456789abcdef0123456789abcdef", }); err != nil { t.Fatal(err) } diff --git a/internal/infrastructure/staterpc/task_log_nilslice_test.go b/internal/infrastructure/staterpc/task_log_nilslice_test.go index 8837f9a76..fcef50e59 100644 --- a/internal/infrastructure/staterpc/task_log_nilslice_test.go +++ b/internal/infrastructure/staterpc/task_log_nilslice_test.go @@ -54,7 +54,7 @@ func TestTaskLogPageCarriesNoNilCollectionFields(t *testing.T) { var c taskLogContract = reader if mode == "grpc" { - c = remoteTaskStore(t, store.OpenTest(t), reader) + c = remoteTaskStore(t, store.OpenTest(t), reader, nil) } page, err := c.TaskLog(ctx, taskID, 0, logging.Query{}) diff --git a/internal/infrastructure/staterpc/task_log_test.go b/internal/infrastructure/staterpc/task_log_test.go index f641eb1b0..c87185888 100644 --- a/internal/infrastructure/staterpc/task_log_test.go +++ b/internal/infrastructure/staterpc/task_log_test.go @@ -41,7 +41,7 @@ func TestTaskLogContract(t *testing.T) { var c taskLogContract = reader if mode == "grpc" { - c = remoteTaskStore(t, store.OpenTest(t), reader) + c = remoteTaskStore(t, store.OpenTest(t), reader, nil) } t.Run("a page carries the decoded entries and their fields", func(t *testing.T) { diff --git a/internal/store/bindings.go b/internal/store/bindings.go deleted file mode 100644 index d04c49d95..000000000 --- a/internal/store/bindings.go +++ /dev/null @@ -1,450 +0,0 @@ -package store - -import ( - "context" - "database/sql" - "errors" - "fmt" - "strings" - "time" - - "github.com/samcharles93/archie-core/internal/domain/binding" -) - -const bindingsSchema = ` -CREATE TABLE IF NOT EXISTS bindings ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - name TEXT NOT NULL DEFAULT '', - source TEXT NOT NULL DEFAULT '', - mapping_id INTEGER NOT NULL DEFAULT 0, - workflow TEXT NOT NULL DEFAULT '', - owner TEXT NOT NULL DEFAULT '', - repo TEXT NOT NULL DEFAULT '', - version INTEGER NOT NULL DEFAULT 1, - status TEXT NOT NULL DEFAULT 'draft', - secret TEXT NOT NULL DEFAULT '', - created_at TEXT NOT NULL, - updated_at TEXT NOT NULL, - CHECK (status IN ('draft','pending_approval','armed')) -); -CREATE INDEX IF NOT EXISTS idx_bindings_source_status ON bindings(source, status); -CREATE TABLE IF NOT EXISTS binding_dispatches ( - binding_id INTEGER NOT NULL, - binding_version INTEGER NOT NULL, - capture_id INTEGER NOT NULL, - task_id INTEGER NOT NULL, - dispatched_at TEXT NOT NULL, - PRIMARY KEY (binding_id, capture_id) -); -` - -// ErrBindingNotFound is returned by UpdateBinding and DeleteBinding when no -// row matches the given ID. GetBinding uses (nil, nil) instead, matching -// TaskByID's convention -- "not found" is the normal answer to "does a -// binding with this ID currently exist," not an error. - -// ErrBindingOverlap is returned by InsertBinding and UpdateBinding when a -// different binding already covers the same source. Two bindings for one -// source would race over the same inbound webhook; the store refuses rather -// than picking an arbitrary winner. - -// ErrBindingTransition is returned by ApproveBinding when the from-status -// is anything other than pending_approval. Approve is the only sanctioned -// transition into armed, and the guard is the SQL WHERE clause, not a -// separate read. - -// ErrAlreadyDispatched is returned by RecordDispatch when the (binding_id, -// capture_id) pair already exists in binding_dispatches, and by -// RecordPlaybookDispatch when the (playbook_id, playbook_version, event_id, -// action_id) tuple already exists in playbook_dispatches. Each dedup ledger -// is an at-most-once guarantee; the caller is expected to surface this to the -// dispatch loop rather than retry. - -// bindingTimeLayout follows captureTimeLayout's reasoning: fixed-width -// RFC3339 so string and chronological order agree. -const bindingTimeLayout = time.RFC3339 - -// InsertBinding persists a new binding in status=draft regardless of the -// caller's Status field, stamps CreatedAt/UpdatedAt to now, and seeds -// Version=1. A pre-insert overlap check refuses a duplicate source in the -// same transaction; ErrBindingOverlap is returned rather than a silent -// constraint violation. -func (s *Store) InsertBinding(ctx context.Context, b binding.Binding) (int64, error) { - tx, err := s.db.BeginTx(ctx, nil) - if err != nil { - return 0, err - } - defer func() { _ = tx.Rollback() }() - - var overlapID int64 - row := tx.QueryRowContext(ctx, `SELECT id FROM bindings WHERE source = ? LIMIT 1`, b.Matcher.Source) - if err := row.Scan(&overlapID); err == nil { - return 0, ErrBindingOverlap - } else if !errors.Is(err, sql.ErrNoRows) { - return 0, err - } - - now := time.Now().UTC().Format(bindingTimeLayout) - secret, err := s.encryptBindingSecret(b.Secret) - if err != nil { - return 0, err - } - res, err := tx.ExecContext(ctx, ` - INSERT INTO bindings (name, source, mapping_id, workflow, owner, repo, version, status, secret, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, 1, 'draft', ?, ?, ?)`, - b.Name, b.Matcher.Source, b.MappingID, b.Workflow, b.Owner, b.Repo, secret, now, now) - if err != nil { - return 0, err - } - id, err := res.LastInsertId() - if err != nil { - return 0, err - } - if err := tx.Commit(); err != nil { - return 0, err - } - return id, nil -} - -// GetBinding returns the binding with the given ID, or (nil, nil) if none -// exists. -func (s *Store) GetBinding(ctx context.Context, id int64) (*binding.Binding, error) { - row := s.db.QueryRowContext(ctx, ` - SELECT id, name, source, mapping_id, workflow, owner, repo, version, status, secret, created_at, updated_at - FROM bindings WHERE id=?`, id) - b, err := scanBindingRow(row) - if errors.Is(err, sql.ErrNoRows) { - return nil, nil - } - if err != nil { - return nil, err - } - if err := s.decryptBindingSecret(b); err != nil { - return nil, err - } - return b, nil -} - -// ListBindings returns every binding, newest first. -func (s *Store) ListBindings(ctx context.Context) (out []binding.Binding, retErr error) { - rows, err := s.db.QueryContext(ctx, ` - SELECT id, name, source, mapping_id, workflow, owner, repo, version, status, secret, created_at, updated_at - FROM bindings ORDER BY id DESC`) - if err != nil { - return nil, err - } - defer func() { retErr = errors.Join(retErr, rows.Close()) }() - - for rows.Next() { - b, err := scanBindingRow(rows) - if err != nil { - return nil, err - } - if err := s.decryptBindingSecret(b); err != nil { - return nil, err - } - out = append(out, *b) - } - return out, rows.Err() -} - -// UpdateBinding replaces the editable fields of an existing binding and -// bumps Version by 1. Per docs/prds/webhook-intake-security.md point 2: -// any edit always drops status to pending_approval, including edits to -// already-armed bindings -- an edit cannot silently re-arm, or the -// approval gate is decorative. Secret is preserved when the caller passes -// an empty string via COALESCE(NULLIF(?, ”), secret) so a partial update -// cannot erase the HMAC secret. Returns ErrBindingNotFound when no row -// matches, ErrBindingOverlap when the new source collides with a different -// binding. -func (s *Store) UpdateBinding(ctx context.Context, b binding.Binding) error { - tx, err := s.db.BeginTx(ctx, nil) - if err != nil { - return err - } - defer func() { _ = tx.Rollback() }() - - var overlapID int64 - row := tx.QueryRowContext(ctx, `SELECT id FROM bindings WHERE source = ? AND id != ? LIMIT 1`, - b.Matcher.Source, b.ID) - if err := row.Scan(&overlapID); err == nil { - return ErrBindingOverlap - } else if !errors.Is(err, sql.ErrNoRows) { - return err - } - - now := time.Now().UTC().Format(bindingTimeLayout) - secret, err := s.encryptBindingSecret(b.Secret) - if err != nil { - return err - } - res, err := tx.ExecContext(ctx, ` - UPDATE bindings SET name=?, source=?, mapping_id=?, workflow=?, owner=?, repo=?, secret=COALESCE(NULLIF(?, ''), secret), - status = 'pending_approval', - version = version + 1, - updated_at = ? - WHERE id=?`, - b.Name, b.Matcher.Source, b.MappingID, b.Workflow, b.Owner, b.Repo, secret, now, b.ID) - if err != nil { - return err - } - n, err := res.RowsAffected() - if err != nil { - return err - } - if n == 0 { - return ErrBindingNotFound - } - return tx.Commit() -} - -// DeleteBinding removes a binding by ID along with any rows it owns in -// binding_dispatches. The dedup rows are deleted in the same transaction -// so a recreate with the same source does not inherit old dedup state. -// Returns ErrBindingNotFound if it does not exist. -func (s *Store) DeleteBinding(ctx context.Context, id int64) error { - tx, err := s.db.BeginTx(ctx, nil) - if err != nil { - return err - } - defer func() { _ = tx.Rollback() }() - - if _, err := tx.ExecContext(ctx, `DELETE FROM binding_dispatches WHERE binding_id = ?`, id); err != nil { - return err - } - res, err := tx.ExecContext(ctx, `DELETE FROM bindings WHERE id=?`, id) - if err != nil { - return err - } - n, err := res.RowsAffected() - if err != nil { - return err - } - if n == 0 { - return ErrBindingNotFound - } - return tx.Commit() -} - -// ApproveBinding moves a binding from pending_approval to armed. The -// status guard is the SQL WHERE clause: a row whose status does not match -// pending_approval yields RowsAffected == 0 and is distinguished as a -// transition error (row exists, wrong from-status) or a not-found error -// (no row) by a follow-up SELECT inside the same transaction. Approve is -// also refused when a different binding is already armed for the same -// source: the overlap rule has to hold across status changes, so this is -// a TOCTOU guard rather than a primary check (Insert/Update own the -// initial overlap prevention). -func (s *Store) ApproveBinding(ctx context.Context, id int64) error { - tx, err := s.db.BeginTx(ctx, nil) - if err != nil { - return err - } - defer func() { _ = tx.Rollback() }() - - var source string - row := tx.QueryRowContext(ctx, `SELECT source FROM bindings WHERE id=?`, id) - if err := row.Scan(&source); err != nil { - if errors.Is(err, sql.ErrNoRows) { - return ErrBindingNotFound - } - return err - } - - var otherArmed int64 - row = tx.QueryRowContext(ctx, - `SELECT id FROM bindings WHERE source=? AND status='armed' AND id != ? LIMIT 1`, - source, id) - if err := row.Scan(&otherArmed); err == nil { - return ErrBindingOverlap - } else if !errors.Is(err, sql.ErrNoRows) { - return err - } - - now := time.Now().UTC().Format(bindingTimeLayout) - res, err := tx.ExecContext(ctx, ` - UPDATE bindings SET status='armed', updated_at=? - WHERE id=? AND status='pending_approval'`, - now, id) - if err != nil { - return err - } - n, err := res.RowsAffected() - if err != nil { - return err - } - if n == 0 { - return ErrBindingTransition - } - return tx.Commit() -} - -// ArmedBindingsForSource returns every armed binding for the given source, -// ordered by id so captureintake's receiver picks a stable winner if multiple -// rows are ever present (the overlap guard should make this impossible in -// practice, but the store returns the full set rather than collapsing). -func (s *Store) ArmedBindingsForSource(ctx context.Context, source string) ([]binding.Binding, error) { - rows, err := s.db.QueryContext(ctx, ` - SELECT id, name, source, mapping_id, workflow, owner, repo, version, status, secret, created_at, updated_at - FROM bindings WHERE source=? AND status='armed' ORDER BY id`, source) - if err != nil { - return nil, err - } - defer func() { _ = rows.Close() }() - - var out []binding.Binding - for rows.Next() { - b, err := scanBindingRow(rows) - if err != nil { - return nil, err - } - if err := s.decryptBindingSecret(b); err != nil { - return nil, err - } - out = append(out, *b) - } - return out, rows.Err() -} - -// encryptBindingSecret seals a plaintext secret for persistence. With no -// cipher configured it returns the value unchanged (legacy plaintext). -// -// An empty secret is the store's sentinel for "no secret" and is returned -// unchanged even when a cipher is installed. Sealing it would yield a -// non-empty envelope, and callers rely on emptiness surviving to the SQL -// layer: UpdateBinding preserves an existing secret through -// COALESCE(NULLIF(?, ”), secret), which cannot fire once encryption has -// turned an empty caller secret into a non-empty value. A partial edit would -// then overwrite the binding's HMAC secret with an encrypted empty string. -func (s *Store) encryptBindingSecret(plaintext string) (string, error) { - if s.bindingsCipher == nil { - return plaintext, nil - } - if plaintext == "" { - return "", nil - } - return s.bindingsCipher.Encrypt(plaintext) -} - -// decryptBindingSecret returns a binding's secret as plaintext. With no cipher -// configured the stored value is returned unchanged. A value that is not an -// encryption envelope is treated as a legacy plaintext row written before a -// cipher was configured and left readable as-is -- encryption applies to rows -// written or edited after the key is installed, not retroactively (see -// docs/prds/binding-secret-encryption.md). -func (s *Store) decryptBindingSecret(b *binding.Binding) error { - if s.bindingsCipher == nil { - return nil - } - if b.Secret == "" || !strings.HasPrefix(b.Secret, bindingEnvelopeMarker+":") { - return nil - } - decrypted, err := s.bindingsCipher.Decrypt(b.Secret) - if err != nil { - return err - } - b.Secret = decrypted - return nil -} - -// RecordDispatch writes a (binding, capture) dedup row using the store's -// own connection (best-effort, not atomic with the task row -- the -// at-most-once guarantee is the INSERT OR IGNORE dedup row itself, which -// is already transactionless in production). INSERT OR IGNORE + -// RowsAffected is the dedup test: a duplicate (binding_id, capture_id) -// is a no-op write and returns ErrAlreadyDispatched rather than a -// constraint error. -func (s *Store) RecordDispatch( - ctx context.Context, - bindingID int64, - bindingVersion int64, - captureID int64, - taskID int64, -) error { - res, err := s.db.ExecContext(ctx, ` - INSERT OR IGNORE INTO binding_dispatches (binding_id, binding_version, capture_id, task_id, dispatched_at) - VALUES (?, ?, ?, ?, ?)`, - bindingID, bindingVersion, captureID, taskID, - time.Now().UTC().Format(bindingTimeLayout)) - if err != nil { - return err - } - n, err := res.RowsAffected() - if err != nil { - return err - } - if n == 0 { - return ErrAlreadyDispatched - } - return nil -} - -// ListUndispatchedCaptures returns authenticated captures that have not -// yet been dispatched by any armed binding whose source matches. The -// nested source query means the result is naturally limited to sources -// with an armed binding; an empty sources slice is therefore a no-arms -// short-circuit and returns (nil, nil) without hitting the table. -func (s *Store) ListUndispatchedCaptures(ctx context.Context, sources []string, limit int) ([]CapturedEvent, error) { - if len(sources) == 0 { - return nil, nil - } - rows, err := s.db.QueryContext(ctx, ` - SELECT id, received_at, source, remote_addr, content_type, headers, body, authenticated - FROM captured_events - WHERE authenticated = 1 - AND id NOT IN (SELECT capture_id FROM binding_dispatches) - AND source IN ( - SELECT source FROM bindings WHERE status = 'armed' GROUP BY source - ) - ORDER BY id - LIMIT ?`, limit) - if err != nil { - return nil, err - } - defer func() { _ = rows.Close() }() - - var out []CapturedEvent - for rows.Next() { - var c CapturedEvent - var receivedAt string - var authenticated int - if err := rows.Scan(&c.ID, &receivedAt, &c.Source, &c.RemoteAddr, - &c.ContentType, &c.Headers, &c.Body, &authenticated); err != nil { - return nil, err - } - parsed, err := parseCaptureTime(receivedAt) - if err != nil { - return nil, err - } - c.ReceivedAt = parsed - c.Authenticated = authenticated != 0 - out = append(out, c) - } - return out, rows.Err() -} - -// bindingScanner is satisfied by both *sql.Row and *sql.Rows so -// scanBindingRow's column list stays in exactly one place. -type bindingScanner interface { - Scan(dest ...any) error -} - -func scanBindingRow(row bindingScanner) (*binding.Binding, error) { - var b binding.Binding - var createdAt, updatedAt string - if err := row.Scan(&b.ID, &b.Name, &b.Matcher.Source, &b.MappingID, &b.Workflow, - &b.Owner, &b.Repo, &b.Version, &b.Status, &b.Secret, &createdAt, &updatedAt); err != nil { - return nil, err - } - created, err := time.Parse(bindingTimeLayout, createdAt) - if err != nil { - return nil, fmt.Errorf("store: unrecognised binding created_at %q: %w", createdAt, err) - } - updated, err := time.Parse(bindingTimeLayout, updatedAt) - if err != nil { - return nil, fmt.Errorf("store: unrecognised binding updated_at %q: %w", updatedAt, err) - } - b.CreatedAt = created.UTC() - b.UpdatedAt = updated.UTC() - return &b, nil -} diff --git a/internal/store/bindings_test.go b/internal/store/bindings_test.go deleted file mode 100644 index c3542e961..000000000 --- a/internal/store/bindings_test.go +++ /dev/null @@ -1,544 +0,0 @@ -package store - -import ( - "database/sql" - "errors" - "path/filepath" - "strings" - "testing" - - "github.com/samcharles93/archie-core/internal/domain/binding" -) - -// testBinding returns a valid binding with a sufficiently long secret for -// Validate. Tests that need a different shape build their own. -func testBinding(source string) binding.Binding { - return binding.Binding{ - Name: "sentry binding", - Matcher: binding.Matcher{Source: source}, - MappingID: 1, - Workflow: "implement", - Status: binding.StatusDraft, - Secret: "0123456789abcdef0123456789abcdef", - } -} - -func TestInsertBindingRoundTrips(t *testing.T) { - s := openTest(t) - b := testBinding("sentry") - id, err := s.InsertBinding(t.Context(), b) - if err != nil { - t.Fatalf("InsertBinding: %v", err) - } - if id == 0 { - t.Fatalf("InsertBinding returned zero id") - } - - got, err := s.GetBinding(t.Context(), id) - if err != nil { - t.Fatalf("GetBinding: %v", err) - } - if got == nil { - t.Fatalf("GetBinding returned nil for a just-inserted row") - } - if got.ID != id { - t.Fatalf("round-tripped id = %d, want %d", got.ID, id) - } - if got.Name != b.Name || got.Workflow != b.Workflow || got.MappingID != b.MappingID { - t.Fatalf("round-tripped fields = %+v", got) - } - if got.Matcher.Source != b.Matcher.Source { - t.Fatalf("round-tripped matcher.source = %q, want %q", got.Matcher.Source, b.Matcher.Source) - } - if got.Status != binding.StatusDraft { - t.Fatalf("status = %q, want %q (insert forces draft regardless of caller)", got.Status, binding.StatusDraft) - } - if got.Version != 1 { - t.Fatalf("version = %d, want 1", got.Version) - } - if got.Secret != b.Secret { - t.Fatalf("secret round-trip mismatch") - } - if got.CreatedAt.IsZero() || got.UpdatedAt.IsZero() { - t.Fatalf("CreatedAt/UpdatedAt must be stamped, got %+v", got) - } -} - -// TestInsertBindingRoundTripsOwnerRepo covers the multi-repo fix: a -// binding pinned to a specific owner/repo persists and reads back -// unchanged, and UpdateBinding can change the pin the same way it -// changes any other editable field. -func TestInsertBindingRoundTripsOwnerRepo(t *testing.T) { - s := openTest(t) - b := testBinding("sentry") - b.Owner, b.Repo = "acme", "widget" - id, err := s.InsertBinding(t.Context(), b) - if err != nil { - t.Fatalf("InsertBinding: %v", err) - } - - got, err := s.GetBinding(t.Context(), id) - if err != nil || got == nil { - t.Fatalf("GetBinding: %+v, %v", got, err) - } - if got.Owner != "acme" || got.Repo != "widget" { - t.Fatalf("round-tripped owner/repo = %q/%q, want acme/widget", got.Owner, got.Repo) - } - - updated := *got - updated.Owner, updated.Repo = "other-org", "other-repo" - if err := s.UpdateBinding(t.Context(), updated); err != nil { - t.Fatalf("UpdateBinding: %v", err) - } - got, err = s.GetBinding(t.Context(), id) - if err != nil || got == nil { - t.Fatalf("GetBinding after update: %+v, %v", got, err) - } - if got.Owner != "other-org" || got.Repo != "other-repo" { - t.Fatalf("updated owner/repo = %q/%q, want other-org/other-repo", got.Owner, got.Repo) - } -} - -func TestOpenMigratesLegacyBindingsOwnerRepoColumns(t *testing.T) { - path := filepath.Join(t.TempDir(), "legacy.db") - raw, err := sql.Open("sqlite", path) - if err != nil { - t.Fatal(err) - } - _, err = raw.ExecContext(t.Context(), ` - CREATE TABLE bindings ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - name TEXT NOT NULL DEFAULT '', - source TEXT NOT NULL DEFAULT '', - mapping_id INTEGER NOT NULL DEFAULT 0, - workflow TEXT NOT NULL DEFAULT '', - version INTEGER NOT NULL DEFAULT 1, - status TEXT NOT NULL DEFAULT 'draft', - secret TEXT NOT NULL DEFAULT '', - created_at TEXT NOT NULL, - updated_at TEXT NOT NULL - ); - INSERT INTO bindings (name, source, workflow, secret, created_at, updated_at) - VALUES ('legacy', 'sentry', 'implement', 'legacy-secret', '2026-01-01T00:00:00Z', '2026-01-01T00:00:00Z'); - PRAGMA user_version = 2`) - if err != nil { - t.Fatal(err) - } - if err := raw.Close(); err != nil { - t.Fatal(err) - } - - s, err := Open(t.Context(), path) - if err != nil { - t.Fatal(err) - } - t.Cleanup(func() { _ = s.Close() }) - - got, err := s.ListBindings(t.Context()) - if err != nil { - t.Fatalf("ListBindings after legacy migration: %v", err) - } - if len(got) != 1 || got[0].Name != "legacy" || got[0].Owner != "" || got[0].Repo != "" { - t.Fatalf("legacy bindings = %+v, want preserved row with empty owner/repo", got) - } - - created := testBinding("github") - created.Owner, created.Repo = "acme", "widget" - id, err := s.InsertBinding(t.Context(), created) - if err != nil { - t.Fatalf("InsertBinding after legacy migration: %v", err) - } - created.ID = id - created.Secret = "" - created.Owner, created.Repo = "other", "repo" - if err := s.UpdateBinding(t.Context(), created); err != nil { - t.Fatalf("UpdateBinding after legacy migration: %v", err) - } - updated, err := s.GetBinding(t.Context(), id) - if err != nil || updated == nil { - t.Fatalf("GetBinding after legacy migration update: %+v, %v", updated, err) - } - if updated.Owner != "other" || updated.Repo != "repo" { - t.Fatalf("updated owner/repo = %q/%q, want other/repo", updated.Owner, updated.Repo) - } -} - -func TestGetBindingMissingReturnsNilNoError(t *testing.T) { - s := openTest(t) - got, err := s.GetBinding(t.Context(), 99999) - if err != nil { - t.Fatalf("GetBinding: %v", err) - } - if got != nil { - t.Fatalf("GetBinding for a missing id = %+v, want nil", got) - } -} - -func TestListBindingsOrdersNewestFirst(t *testing.T) { - s := openTest(t) - for i, src := range []string{"alpha", "beta", "gamma"} { - if _, err := s.InsertBinding(t.Context(), testBinding(src)); err != nil { - t.Fatalf("InsertBinding[%d]: %v", i, err) - } - } - got, err := s.ListBindings(t.Context()) - if err != nil { - t.Fatalf("ListBindings: %v", err) - } - if len(got) != 3 { - t.Fatalf("ListBindings = %d rows, want 3", len(got)) - } - if got[0].ID <= got[1].ID || got[1].ID <= got[2].ID { - t.Fatalf("ListBindings not newest-first: ids = %d, %d, %d", got[0].ID, got[1].ID, got[2].ID) - } -} - -func TestUpdateBindingBumpsVersion(t *testing.T) { - s := openTest(t) - id, err := s.InsertBinding(t.Context(), testBinding("sentry")) - if err != nil { - t.Fatalf("InsertBinding: %v", err) - } - updated := testBinding("sentry") - updated.ID = id - updated.Name = "renamed" - if err := s.UpdateBinding(t.Context(), updated); err != nil { - t.Fatalf("UpdateBinding: %v", err) - } - got, err := s.GetBinding(t.Context(), id) - if err != nil || got == nil { - t.Fatalf("GetBinding after update: %+v, %v", got, err) - } - if got.Version != 2 { - t.Fatalf("version = %d, want 2 after one update", got.Version) - } - if got.Name != "renamed" { - t.Fatalf("updated name = %q, want %q", got.Name, "renamed") - } -} - -func TestUpdateBindingOnArmedForcesPendingApproval(t *testing.T) { - s := openTest(t) - id, err := s.InsertBinding(t.Context(), testBinding("sentry")) - if err != nil { - t.Fatalf("InsertBinding: %v", err) - } - if _, err := s.db.ExecContext(t.Context(), `UPDATE bindings SET status='pending_approval' WHERE id=?`, id); err != nil { - t.Fatalf("force pending_approval: %v", err) - } - if err := s.ApproveBinding(t.Context(), id); err != nil { - t.Fatalf("ApproveBinding: %v", err) - } - armed, err := s.GetBinding(t.Context(), id) - if err != nil || armed == nil { - t.Fatalf("GetBinding after approve: %+v, %v", armed, err) - } - if armed.Status != binding.StatusArmed { - t.Fatalf("status after approve = %q, want armed", armed.Status) - } - - // An edit on an armed binding must drop it back to pending_approval. - updated := *armed - updated.Name = "edit while armed" - if err := s.UpdateBinding(t.Context(), updated); err != nil { - t.Fatalf("UpdateBinding on armed: %v", err) - } - got, err := s.GetBinding(t.Context(), id) - if err != nil || got == nil { - t.Fatalf("GetBinding after armed edit: %+v, %v", got, err) - } - if got.Status != binding.StatusPendingApproval { - t.Fatalf("status after armed edit = %q, want pending_approval", got.Status) - } - if got.Version <= armed.Version { - t.Fatalf("version did not advance after update: was %d, now %d", armed.Version, got.Version) - } -} - -func TestUpdateBindingPreservesSecretWhenEmpty(t *testing.T) { - s := openTest(t) - b := testBinding("sentry") - b.Secret = "0123456789abcdef0123456789abcdef" - id, err := s.InsertBinding(t.Context(), b) - if err != nil { - t.Fatalf("InsertBinding: %v", err) - } - updated := testBinding("sentry") - updated.ID = id - updated.Secret = "" // empty -> preserve - if err := s.UpdateBinding(t.Context(), updated); err != nil { - t.Fatalf("UpdateBinding: %v", err) - } - got, err := s.GetBinding(t.Context(), id) - if err != nil || got == nil { - t.Fatalf("GetBinding after update: %+v, %v", got, err) - } - if got.Secret != b.Secret { - t.Fatalf("secret = %q, want preserved %q", got.Secret, b.Secret) - } -} - -// TestUpdateBindingSecretWithCipher covers the same empty-secret-means-preserve -// contract as TestUpdateBindingPreservesSecretWhenEmpty, but with an at-rest -// cipher installed -- the configuration every deployment with -// [bindings].encryption_key actually runs. -// -// The sibling test opens the store without a cipher, where -// COALESCE(NULLIF(?, ”), secret) sees a literal empty string and holds. With a -// cipher the secret is encrypted BEFORE that guard runs, so an empty caller -// secret was sealed into a non-empty envelope, NULLIF stopped firing, and a -// name-only edit overwrote the binding's HMAC secret with an encrypted empty -// value -- after which the binding can never authenticate an inbound webhook. -// -// The second case is the other half of the contract: a genuinely supplied -// secret must still replace the stored one, so the fix cannot degrade into -// "updates never change the secret". -func TestUpdateBindingSecretWithCipher(t *testing.T) { - t.Parallel() - - const original = "0123456789abcdef0123456789abcdef" - replacement := strings.Repeat("f", len(original)) - - cases := []struct { - name string - newSecret string - want string - }{ - {"empty caller secret preserves the stored secret", "", original}, - {"a supplied secret replaces the stored secret", replacement, replacement}, - } - - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - t.Parallel() - - s := openTestWithBindingCipher(t) - b := testBinding("sentry") - b.Secret = original - id, err := s.InsertBinding(t.Context(), b) - if err != nil { - t.Fatalf("InsertBinding: %v", err) - } - - updated := testBinding("sentry") - updated.ID = id - updated.Name = "renamed binding" // an ordinary edit that does not touch the secret - updated.Secret = tc.newSecret - if err := s.UpdateBinding(t.Context(), updated); err != nil { - t.Fatalf("UpdateBinding: %v", err) - } - - got, err := s.GetBinding(t.Context(), id) - if err != nil || got == nil { - t.Fatalf("GetBinding after update: %+v, %v", got, err) - } - if got.Secret != tc.want { - t.Fatalf("secret = %q, want %q", got.Secret, tc.want) - } - }) - } -} - -func TestApproveBindingFromPendingApprovalToArmedSucceeds(t *testing.T) { - s := openTest(t) - id, err := s.InsertBinding(t.Context(), testBinding("sentry")) - if err != nil { - t.Fatalf("InsertBinding: %v", err) - } - if _, err := s.db.ExecContext(t.Context(), `UPDATE bindings SET status='pending_approval' WHERE id=?`, id); err != nil { - t.Fatalf("force pending_approval: %v", err) - } - if err := s.ApproveBinding(t.Context(), id); err != nil { - t.Fatalf("ApproveBinding: %v", err) - } - got, err := s.GetBinding(t.Context(), id) - if err != nil || got == nil { - t.Fatalf("GetBinding after approve: %+v, %v", got, err) - } - if got.Status != binding.StatusArmed { - t.Fatalf("status = %q, want armed", got.Status) - } -} - -func TestApproveBindingFromDraftFails(t *testing.T) { - s := openTest(t) - id, err := s.InsertBinding(t.Context(), testBinding("sentry")) - if err != nil { - t.Fatalf("InsertBinding: %v", err) - } - err = s.ApproveBinding(t.Context(), id) - if !errors.Is(err, ErrBindingTransition) { - t.Fatalf("ApproveBinding from draft = %v, want ErrBindingTransition", err) - } - got, err := s.GetBinding(t.Context(), id) - if err != nil || got == nil { - t.Fatalf("GetBinding after failed approve: %+v, %v", got, err) - } - if got.Status != binding.StatusDraft { - t.Fatalf("status after failed approve = %q, want unchanged draft", got.Status) - } -} - -func TestApproveBindingFromArmedFails(t *testing.T) { - s := openTest(t) - id, err := s.InsertBinding(t.Context(), testBinding("sentry")) - if err != nil { - t.Fatalf("InsertBinding: %v", err) - } - if _, err := s.db.ExecContext(t.Context(), `UPDATE bindings SET status='armed' WHERE id=?`, id); err != nil { - t.Fatalf("force armed: %v", err) - } - err = s.ApproveBinding(t.Context(), id) - if !errors.Is(err, ErrBindingTransition) { - t.Fatalf("ApproveBinding from armed = %v, want ErrBindingTransition", err) - } -} - -func TestApproveBindingMissingReturnsErrBindingNotFound(t *testing.T) { - s := openTest(t) - err := s.ApproveBinding(t.Context(), 99999) - if !errors.Is(err, ErrBindingNotFound) { - t.Fatalf("ApproveBinding on missing id = %v, want ErrBindingNotFound", err) - } -} - -func TestInsertBindingRejectsOverlap(t *testing.T) { - s := openTest(t) - if _, err := s.InsertBinding(t.Context(), testBinding("sentry")); err != nil { - t.Fatalf("first InsertBinding: %v", err) - } - _, err := s.InsertBinding(t.Context(), testBinding("sentry")) - if !errors.Is(err, ErrBindingOverlap) { - t.Fatalf("second InsertBinding (same source) = %v, want ErrBindingOverlap", err) - } -} - -func TestApproveBindingRejectsOverlapAfterSecondInserted(t *testing.T) { - s := openTest(t) - first, err := s.InsertBinding(t.Context(), testBinding("sentry")) - if err != nil { - t.Fatalf("first InsertBinding: %v", err) - } - if _, err := s.db.ExecContext(t.Context(), `UPDATE bindings SET status='pending_approval' WHERE id=?`, first); err != nil { - t.Fatalf("force pending_approval: %v", err) - } - if err := s.ApproveBinding(t.Context(), first); err != nil { - t.Fatalf("ApproveBinding first: %v", err) - } - - second, err := s.InsertBinding(t.Context(), testBinding("sentry")) - if err == nil { - // A duplicate-source insert must be rejected outright, so reaching - // here means the overlap guard failed at insert time. - t.Fatalf("second InsertBinding for armed source = id %d, want ErrBindingOverlap", second) - } - if !errors.Is(err, ErrBindingOverlap) { - t.Fatalf("second InsertBinding = %v, want ErrBindingOverlap", err) - } -} - -func TestDeleteBindingRemovesRowAndLedgerEntries(t *testing.T) { - s := openTest(t) - id, err := s.InsertBinding(t.Context(), testBinding("sentry")) - if err != nil { - t.Fatalf("InsertBinding: %v", err) - } - if err := s.RecordDispatch(t.Context(), id, 1, 42, 7); err != nil { - t.Fatalf("RecordDispatch: %v", err) - } - if err := s.DeleteBinding(t.Context(), id); err != nil { - t.Fatalf("DeleteBinding: %v", err) - } - got, err := s.GetBinding(t.Context(), id) - if err != nil { - t.Fatalf("GetBinding after delete: %v", err) - } - if got != nil { - t.Fatalf("GetBinding after delete = %+v, want nil", got) - } - var n int - if err := s.db.QueryRowContext(t.Context(), `SELECT COUNT(*) FROM binding_dispatches WHERE binding_id=?`, id).Scan(&n); err != nil { - t.Fatalf("COUNT binding_dispatches: %v", err) - } - if n != 0 { - t.Fatalf("binding_dispatches rows for binding_id=%d = %d, want 0", id, n) - } -} - -func TestRecordDispatchIsIdempotent(t *testing.T) { - s := openTest(t) - id, err := s.InsertBinding(t.Context(), testBinding("sentry")) - if err != nil { - t.Fatalf("InsertBinding: %v", err) - } - ctx := t.Context() - if err := s.RecordDispatch(ctx, id, 1, 42, 7); err != nil { - t.Fatalf("first RecordDispatch: %v", err) - } - - err = s.RecordDispatch(ctx, id, 1, 42, 99) - if !errors.Is(err, ErrAlreadyDispatched) { - t.Fatalf("second RecordDispatch (same binding/capture) = %v, want ErrAlreadyDispatched", err) - } -} - -func TestListUndispatchedCapturesExcludesDispatched(t *testing.T) { - s := openTest(t) - id, err := s.InsertBinding(t.Context(), testBinding("sentry")) - if err != nil { - t.Fatalf("InsertBinding: %v", err) - } - if _, err := s.db.ExecContext(t.Context(), `UPDATE bindings SET status='armed' WHERE id=?`, id); err != nil { - t.Fatalf("arm binding: %v", err) - } - - // Capture 1: authenticated, will be dispatched -> should NOT appear. - cap1, err := s.InsertCapture(t.Context(), CapturedEvent{ - Source: "sentry", Authenticated: true, Body: `{"id":"1"}`, - }, 0, 0) - if err != nil { - t.Fatalf("InsertCapture 1: %v", err) - } - // Capture 2: authenticated, not dispatched -> SHOULD appear. - cap2, err := s.InsertCapture(t.Context(), CapturedEvent{ - Source: "sentry", Authenticated: true, Body: `{"id":"2"}`, - }, 0, 0) - if err != nil { - t.Fatalf("InsertCapture 2: %v", err) - } - // Capture 3: unauthenticated -> should NOT appear (matches() requires auth). - cap3, err := s.InsertCapture(t.Context(), CapturedEvent{ - Source: "sentry", Authenticated: false, Body: `{"id":"3"}`, - }, 0, 0) - if err != nil { - t.Fatalf("InsertCapture 3: %v", err) - } - - ctx := t.Context() - if err := s.RecordDispatch(ctx, id, 1, cap1, 100); err != nil { - t.Fatalf("RecordDispatch: %v", err) - } - - got, err := s.ListUndispatchedCaptures(ctx, []string{"sentry"}, 10) - if err != nil { - t.Fatalf("ListUndispatchedCaptures: %v", err) - } - if len(got) != 1 { - t.Fatalf("ListUndispatchedCaptures = %d rows, want 1", len(got)) - } - if got[0].ID != cap2 { - t.Fatalf("returned capture id = %d, want %d (cap3 unauthenticated, cap1 dispatched)", got[0].ID, cap2) - } - _ = cap3 -} - -func TestListUndispatchedCapturesEmptySourcesReturnsNil(t *testing.T) { - s := openTest(t) - got, err := s.ListUndispatchedCaptures(t.Context(), nil, 10) - if err != nil { - t.Fatalf("ListUndispatchedCaptures(nil sources): %v", err) - } - if got != nil { - t.Fatalf("ListUndispatchedCaptures(nil sources) = %+v, want nil", got) - } -} diff --git a/internal/store/captures.go b/internal/store/captures.go deleted file mode 100644 index 8834d8938..000000000 --- a/internal/store/captures.go +++ /dev/null @@ -1,124 +0,0 @@ -package store - -import ( - "context" - "errors" - "fmt" - "time" -) - -const capturesSchema = ` -CREATE TABLE IF NOT EXISTS captured_events ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - received_at TEXT NOT NULL, - source TEXT NOT NULL DEFAULT '', - remote_addr TEXT NOT NULL DEFAULT '', - content_type TEXT NOT NULL DEFAULT '', - headers TEXT NOT NULL DEFAULT '{}', - body TEXT NOT NULL DEFAULT '', - authenticated INTEGER NOT NULL DEFAULT 0 -); -CREATE INDEX IF NOT EXISTS idx_captured_events_source ON captured_events(source, id); -` - -// captureTimeLayout is fixed-width (unlike time.RFC3339Nano, whose -// fractional-seconds field is trimmed of trailing zeros and omitted -// entirely when zero). A variable-width fractional part breaks lexicographic -// string comparison -- "15:04:05Z" (an exact second) sorts AFTER -// "15:04:05.1Z" (0.1s later) because 'Z' > '.', which would make the -// retention prune's `WHERE received_at < ?` unreliable. Second precision is -// enough here: row order already comes from id (autoincrement), and -// retention windows are measured in days, not sub-second intervals. -const captureTimeLayout = time.RFC3339 - -// InsertCapture persists a captured event and prunes the table in the same -// transaction: rows older than retention (when > 0) and rows beyond the -// newest maxEvents (when > 0) are deleted. Either bound of 0 or less -// disables that prune. See docs/prds/event-capture-storage.md's disk-bound -// mechanics -- this is one of three independent bounds, the other two -// (per-request size cap, per-source rate limit) are enforced by the caller -// before the body ever reaches this method. -func (s *Store) InsertCapture(ctx context.Context, c CapturedEvent, retention time.Duration, maxEvents int) (int64, error) { - tx, err := s.db.BeginTx(ctx, nil) - if err != nil { - return 0, err - } - defer func() { _ = tx.Rollback() }() - - if c.ReceivedAt.IsZero() { - c.ReceivedAt = time.Now().UTC() - } - res, err := tx.ExecContext(ctx, ` - INSERT INTO captured_events (received_at, source, remote_addr, content_type, headers, body, authenticated) - VALUES (?, ?, ?, ?, ?, ?, ?)`, - c.ReceivedAt.UTC().Format(captureTimeLayout), c.Source, c.RemoteAddr, - c.ContentType, c.Headers, c.Body, c.Authenticated) - if err != nil { - return 0, err - } - id, err := res.LastInsertId() - if err != nil { - return 0, err - } - - if retention > 0 { - cutoff := time.Now().UTC().Add(-retention).Format(captureTimeLayout) - if _, err := tx.ExecContext(ctx, `DELETE FROM captured_events WHERE received_at < ?`, cutoff); err != nil { - return 0, err - } - } - if maxEvents > 0 { - if _, err := tx.ExecContext(ctx, ` - DELETE FROM captured_events WHERE id NOT IN ( - SELECT id FROM captured_events ORDER BY id DESC LIMIT ? - )`, maxEvents); err != nil { - return 0, err - } - } - - if err := tx.Commit(); err != nil { - return 0, err - } - return id, nil -} - -// ListCaptures returns up to limit captured events, newest first. -func (s *Store) ListCaptures(ctx context.Context, limit int) (out []CapturedEvent, retErr error) { - rows, err := s.db.QueryContext(ctx, ` - SELECT id, received_at, source, remote_addr, content_type, headers, body, authenticated - FROM captured_events ORDER BY id DESC LIMIT ?`, limit) - if err != nil { - return nil, err - } - defer func() { retErr = errors.Join(retErr, rows.Close()) }() - - for rows.Next() { - var c CapturedEvent - var receivedAt string - var authenticated int - if err := rows.Scan(&c.ID, &receivedAt, &c.Source, &c.RemoteAddr, - &c.ContentType, &c.Headers, &c.Body, &authenticated); err != nil { - return nil, err - } - parsed, err := parseCaptureTime(receivedAt) - if err != nil { - return nil, err - } - c.ReceivedAt = parsed - c.Authenticated = authenticated != 0 - out = append(out, c) - } - return out, rows.Err() -} - -func parseCaptureTime(v string) (time.Time, error) { - if v == "" { - return time.Time{}, nil - } - for _, layout := range []string{time.RFC3339Nano, time.RFC3339} { - if parsed, err := time.Parse(layout, v); err == nil { - return parsed.UTC(), nil - } - } - return time.Time{}, fmt.Errorf("store: unrecognised capture timestamp %q", v) -} diff --git a/internal/store/captures_test.go b/internal/store/captures_test.go deleted file mode 100644 index 36c9eeda2..000000000 --- a/internal/store/captures_test.go +++ /dev/null @@ -1,169 +0,0 @@ -package store - -import ( - "testing" - "time" -) - -func TestInsertCaptureRoundTrips(t *testing.T) { - s := openTest(t) - id, err := s.InsertCapture(t.Context(), CapturedEvent{ - Source: "github", - RemoteAddr: "203.0.113.5", - ContentType: "application/json", - Headers: `{"x-hub-signature-256":"[redacted]"}`, - Body: `{"action":"opened"}`, - Authenticated: false, - }, 7*24*time.Hour, 0) - if err != nil { - t.Fatalf("InsertCapture: %v", err) - } - if id == 0 { - t.Fatalf("InsertCapture returned zero id") - } - - got, err := s.ListCaptures(t.Context(), 10) - if err != nil { - t.Fatalf("ListCaptures: %v", err) - } - if len(got) != 1 { - t.Fatalf("ListCaptures = %d rows, want 1", len(got)) - } - c := got[0] - if c.ID != id || c.Source != "github" || c.RemoteAddr != "203.0.113.5" || - c.ContentType != "application/json" || c.Body != `{"action":"opened"}` || - c.Authenticated { - t.Fatalf("round-tripped capture = %+v, want matching fields", c) - } - if c.ReceivedAt.IsZero() { - t.Fatalf("ReceivedAt is zero, want a timestamp stamped at insert") - } -} - -func TestListCapturesOrdersNewestFirst(t *testing.T) { - s := openTest(t) - for i := range 3 { - if _, err := s.InsertCapture(t.Context(), CapturedEvent{Source: "src", Body: "{}"}, 0, 0); err != nil { - t.Fatalf("InsertCapture[%d]: %v", i, err) - } - } - got, err := s.ListCaptures(t.Context(), 10) - if err != nil { - t.Fatalf("ListCaptures: %v", err) - } - if len(got) != 3 { - t.Fatalf("ListCaptures = %d rows, want 3", len(got)) - } - if got[0].ID <= got[1].ID || got[1].ID <= got[2].ID { - t.Fatalf("ListCaptures not newest-first: ids = %d, %d, %d", got[0].ID, got[1].ID, got[2].ID) - } -} - -func TestInsertCapturePrunesBeyondMaxEvents(t *testing.T) { - s := openTest(t) - var lastID int64 - for i := range 5 { - id, err := s.InsertCapture(t.Context(), CapturedEvent{Source: "src", Body: "{}"}, 0, 3) - if err != nil { - t.Fatalf("InsertCapture[%d]: %v", i, err) - } - lastID = id - } - got, err := s.ListCaptures(t.Context(), 100) - if err != nil { - t.Fatalf("ListCaptures: %v", err) - } - if len(got) != 3 { - t.Fatalf("row count = %d, want 3 (maxEvents cap)", len(got)) - } - if got[0].ID != lastID { - t.Fatalf("newest surviving row id = %d, want %d (the last insert)", got[0].ID, lastID) - } - // The two oldest of the five inserts must have been pruned. - for _, c := range got { - if c.ID <= lastID-3 { - t.Fatalf("found pruned row id %d still present after maxEvents=3 cap", c.ID) - } - } -} - -func TestInsertCapturePrunesOlderThanRetention(t *testing.T) { - s := openTest(t) - // Insert a row and manually age it beyond the retention window, since - // InsertCapture always stamps "now" and the test cannot wait real days. - id, err := s.InsertCapture(t.Context(), CapturedEvent{Source: "old", Body: "{}"}, 0, 0) - if err != nil { - t.Fatalf("InsertCapture: %v", err) - } - stale := time.Now().UTC().Add(-8 * 24 * time.Hour).Format(captureTimeLayout) - if _, err := s.db.ExecContext(t.Context(), - `UPDATE captured_events SET received_at = ? WHERE id = ?`, stale, id); err != nil { - t.Fatalf("backdate row: %v", err) - } - - // A fresh insert with a 7-day retention should prune the now-stale row. - if _, err := s.InsertCapture(t.Context(), CapturedEvent{Source: "new", Body: "{}"}, 7*24*time.Hour, 0); err != nil { - t.Fatalf("InsertCapture: %v", err) - } - - got, err := s.ListCaptures(t.Context(), 100) - if err != nil { - t.Fatalf("ListCaptures: %v", err) - } - for _, c := range got { - if c.ID == id { - t.Fatalf("stale row id %d survived a 7-day retention prune", id) - } - } - if len(got) != 1 { - t.Fatalf("row count = %d, want 1 (only the fresh insert)", len(got)) - } -} - -// TestCaptureTimeLayoutSortsLexicographicallyLikeChronologically pins a real -// defect that time.RFC3339Nano has: it trims trailing fractional-second -// zeros and omits the fractional part entirely when it is exactly zero, so -// "15:04:05Z" (an exact second) sorts LEXICOGRAPHICALLY AFTER "15:04:05.1Z" -// (0.1s later) because 'Z' (0x5A) > '.' (0x2E) -- backwards from -// chronological order. A retention prune using `WHERE received_at < ?` on a -// column written that way is unreliable within the same second. -// captureTimeLayout must be fixed-width so string order and time order -// always agree. -// -// This compares captureTimeLayout's string output directly rather than -// going through InsertCapture's real prune, because the defect only shows up -// when two timestamps share the same whole-second value and differ only in -// fractional presence -- a case InsertCapture's own cutoff (computed from -// the real wall clock) cannot be steered into deterministically in a test. -func TestCaptureTimeLayoutSortsLexicographicallyLikeChronologically(t *testing.T) { - exactSecond := time.Date(2026, 1, 1, 15, 4, 5, 0, time.UTC) - fractionLater := time.Date(2026, 1, 1, 15, 4, 5, 100_000_000, time.UTC) // same second, 0.1s later - - if !exactSecond.Before(fractionLater) { - t.Fatalf("test setup: %v must be before %v", exactSecond, fractionLater) - } - es, fs := exactSecond.Format(captureTimeLayout), fractionLater.Format(captureTimeLayout) - // The layout is second-precision, so two timestamps within the same - // second are allowed to format identically (that's the accepted - // precision tradeoff, not a bug) -- but a later time must never sort as - // lexicographically LESS than an earlier one. - if es > fs { - t.Fatalf("captureTimeLayout string order disagrees with chronological order: %q should not sort after %q", es, fs) - } -} - -func TestInsertCaptureZeroRetentionAndMaxEventsMeansUnbounded(t *testing.T) { - s := openTest(t) - for i := range 10 { - if _, err := s.InsertCapture(t.Context(), CapturedEvent{Source: "src", Body: "{}"}, 0, 0); err != nil { - t.Fatalf("InsertCapture[%d]: %v", i, err) - } - } - got, err := s.ListCaptures(t.Context(), 100) - if err != nil { - t.Fatalf("ListCaptures: %v", err) - } - if len(got) != 10 { - t.Fatalf("row count = %d, want 10 (retention=0, maxEvents=0 disables both prunes)", len(got)) - } -} diff --git a/internal/store/interface.go b/internal/store/interface.go index 3e3b7574a..3f0c618f0 100644 --- a/internal/store/interface.go +++ b/internal/store/interface.go @@ -61,21 +61,3 @@ var _ ChannelStatusStore = (*Store)(nil) // Compile-time check: *Store satisfies workflow.Store. var _ workflow.Store = (*Store)(nil) - -// Compile-time check: *Store satisfies CaptureStore. -var _ CaptureStore = (*Store)(nil) - -// Compile-time check: *Store satisfies MappingStore. -var _ MappingStore = (*Store)(nil) - -// Compile-time check: *Store satisfies BindingStore. -var _ BindingStore = (*Store)(nil) - -// Compile-time check: *Store satisfies BindingDispatcher. -var _ BindingDispatcher = (*Store)(nil) - -// Compile-time check: *Store satisfies BindingTaskCreator. -var _ BindingTaskCreator = (*Store)(nil) - -// Compile-time check: *Store satisfies PlaybookDispatcher. -var _ PlaybookDispatcher = (*Store)(nil) diff --git a/internal/store/mappings.go b/internal/store/mappings.go deleted file mode 100644 index 51e7221bd..000000000 --- a/internal/store/mappings.go +++ /dev/null @@ -1,162 +0,0 @@ -package store - -import ( - "context" - "database/sql" - "encoding/json" - "errors" - "fmt" - "time" - - "github.com/samcharles93/archie-core/internal/domain/mapping" -) - -const mappingsSchema = ` -CREATE TABLE IF NOT EXISTS field_mappings ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - name TEXT NOT NULL DEFAULT '', - source_hint TEXT NOT NULL DEFAULT '', - fields_json TEXT NOT NULL DEFAULT '[]', - created_at TEXT NOT NULL, - updated_at TEXT NOT NULL -); -` - -// ErrMappingNotFound is returned by UpdateMapping and DeleteMapping when no -// row matches the given ID. GetMapping uses (nil, nil) instead, matching -// TaskByID's convention -- "not found" is the normal answer to "does a -// mapping with this ID currently exist," not an error. - -// mappingTimeLayout follows captureTimeLayout's reasoning: fixed-width so -// string and chronological order agree, even though nothing here prunes on -// a string comparison today -- consistency with the rest of the store's -// timestamp columns. -const mappingTimeLayout = time.RFC3339 - -// InsertMapping persists a new mapping and stamps CreatedAt/UpdatedAt to -// now, ignoring any caller-supplied values. -func (s *Store) InsertMapping(ctx context.Context, m mapping.Mapping) (int64, error) { - fieldsJSON, err := json.Marshal(m.Fields) - if err != nil { - return 0, fmt.Errorf("store: marshal mapping fields: %w", err) - } - now := time.Now().UTC().Format(mappingTimeLayout) - res, err := s.db.ExecContext(ctx, ` - INSERT INTO field_mappings (name, source_hint, fields_json, created_at, updated_at) - VALUES (?, ?, ?, ?, ?)`, - m.Name, m.SourceHint, string(fieldsJSON), now, now) - if err != nil { - return 0, err - } - return res.LastInsertId() -} - -// GetMapping returns the mapping with the given ID, or (nil, nil) if none -// exists. -func (s *Store) GetMapping(ctx context.Context, id int64) (*mapping.Mapping, error) { - row := s.db.QueryRowContext(ctx, ` - SELECT id, name, source_hint, fields_json, created_at, updated_at - FROM field_mappings WHERE id=?`, id) - m, err := scanMapping(row) - if errors.Is(err, sql.ErrNoRows) { - return nil, nil - } - if err != nil { - return nil, err - } - return m, nil -} - -// ListMappings returns every mapping, newest first. -func (s *Store) ListMappings(ctx context.Context) (out []mapping.Mapping, retErr error) { - rows, err := s.db.QueryContext(ctx, ` - SELECT id, name, source_hint, fields_json, created_at, updated_at - FROM field_mappings ORDER BY id DESC`) - if err != nil { - return nil, err - } - defer func() { retErr = errors.Join(retErr, rows.Close()) }() - - for rows.Next() { - m, err := scanMappingRow(rows) - if err != nil { - return nil, err - } - out = append(out, *m) - } - return out, rows.Err() -} - -// UpdateMapping replaces the name, source hint and fields of an existing -// mapping and bumps UpdatedAt to now. Returns ErrMappingNotFound if m.ID -// does not exist. -func (s *Store) UpdateMapping(ctx context.Context, m mapping.Mapping) error { - fieldsJSON, err := json.Marshal(m.Fields) - if err != nil { - return fmt.Errorf("store: marshal mapping fields: %w", err) - } - res, err := s.db.ExecContext(ctx, ` - UPDATE field_mappings SET name=?, source_hint=?, fields_json=?, updated_at=? - WHERE id=?`, - m.Name, m.SourceHint, string(fieldsJSON), time.Now().UTC().Format(mappingTimeLayout), m.ID) - if err != nil { - return err - } - n, err := res.RowsAffected() - if err != nil { - return err - } - if n == 0 { - return ErrMappingNotFound - } - return nil -} - -// DeleteMapping removes a mapping by ID. Returns ErrMappingNotFound if it -// does not exist. -func (s *Store) DeleteMapping(ctx context.Context, id int64) error { - res, err := s.db.ExecContext(ctx, `DELETE FROM field_mappings WHERE id=?`, id) - if err != nil { - return err - } - n, err := res.RowsAffected() - if err != nil { - return err - } - if n == 0 { - return ErrMappingNotFound - } - return nil -} - -// mappingScanner is satisfied by both *sql.Row and *sql.Rows, so -// scanMapping's column list stays in exactly one place. -type mappingScanner interface { - Scan(dest ...any) error -} - -func scanMapping(row mappingScanner) (*mapping.Mapping, error) { - return scanMappingRow(row) -} - -func scanMappingRow(row mappingScanner) (*mapping.Mapping, error) { - var m mapping.Mapping - var fieldsJSON, createdAt, updatedAt string - if err := row.Scan(&m.ID, &m.Name, &m.SourceHint, &fieldsJSON, &createdAt, &updatedAt); err != nil { - return nil, err - } - if err := json.Unmarshal([]byte(fieldsJSON), &m.Fields); err != nil { - return nil, fmt.Errorf("store: unmarshal mapping fields: %w", err) - } - created, err := time.Parse(mappingTimeLayout, createdAt) - if err != nil { - return nil, fmt.Errorf("store: unrecognised mapping created_at %q: %w", createdAt, err) - } - updated, err := time.Parse(mappingTimeLayout, updatedAt) - if err != nil { - return nil, fmt.Errorf("store: unrecognised mapping updated_at %q: %w", updatedAt, err) - } - m.CreatedAt = created.UTC() - m.UpdatedAt = updated.UTC() - return &m, nil -} diff --git a/internal/store/mappings_test.go b/internal/store/mappings_test.go deleted file mode 100644 index da7486b36..000000000 --- a/internal/store/mappings_test.go +++ /dev/null @@ -1,145 +0,0 @@ -package store - -import ( - "errors" - "testing" - - "github.com/samcharles93/archie-core/internal/domain/mapping" -) - -func testFields() []mapping.Field { - return []mapping.Field{ - {Name: "title", Path: "issue.title", Type: mapping.TypeString, Required: true}, - {Name: "count", Path: "count", Type: mapping.TypeNumber}, - } -} - -func TestInsertMappingRoundTrips(t *testing.T) { - s := openTest(t) - id, err := s.InsertMapping(t.Context(), mapping.Mapping{ - Name: "sentry issue opened", - SourceHint: "sentry", - Fields: testFields(), - }) - if err != nil { - t.Fatalf("InsertMapping: %v", err) - } - if id == 0 { - t.Fatalf("InsertMapping returned zero id") - } - - got, err := s.GetMapping(t.Context(), id) - if err != nil { - t.Fatalf("GetMapping: %v", err) - } - if got == nil { - t.Fatalf("GetMapping returned nil for a just-inserted row") - } - if got.ID != id || got.Name != "sentry issue opened" || got.SourceHint != "sentry" { - t.Fatalf("round-tripped mapping = %+v", got) - } - if len(got.Fields) != 2 || got.Fields[0].Name != "title" || got.Fields[0].Path != "issue.title" || - got.Fields[0].Type != mapping.TypeString || !got.Fields[0].Required { - t.Fatalf("round-tripped fields = %+v", got.Fields) - } - if got.CreatedAt.IsZero() || got.UpdatedAt.IsZero() { - t.Fatalf("CreatedAt/UpdatedAt must be stamped, got %+v", got) - } -} - -func TestGetMappingMissingReturnsNilNoError(t *testing.T) { - s := openTest(t) - got, err := s.GetMapping(t.Context(), 999) - if err != nil { - t.Fatalf("GetMapping: %v", err) - } - if got != nil { - t.Fatalf("GetMapping for a missing id = %+v, want nil", got) - } -} - -func TestListMappingsOrdersNewestFirst(t *testing.T) { - s := openTest(t) - for i := range 3 { - if _, err := s.InsertMapping(t.Context(), mapping.Mapping{Name: "m", Fields: testFields()}); err != nil { - t.Fatalf("InsertMapping[%d]: %v", i, err) - } - } - got, err := s.ListMappings(t.Context()) - if err != nil { - t.Fatalf("ListMappings: %v", err) - } - if len(got) != 3 { - t.Fatalf("ListMappings = %d rows, want 3", len(got)) - } - if got[0].ID <= got[1].ID || got[1].ID <= got[2].ID { - t.Fatalf("ListMappings not newest-first: ids = %d, %d, %d", got[0].ID, got[1].ID, got[2].ID) - } -} - -func TestUpdateMappingChangesFieldsAndBumpsUpdatedAt(t *testing.T) { - s := openTest(t) - id, err := s.InsertMapping(t.Context(), mapping.Mapping{Name: "orig", Fields: testFields()}) - if err != nil { - t.Fatalf("InsertMapping: %v", err) - } - before, err := s.GetMapping(t.Context(), id) - if err != nil || before == nil { - t.Fatalf("GetMapping before update: %+v, %v", before, err) - } - - newFields := []mapping.Field{{Name: "renamed", Path: "a.b", Type: mapping.TypeBool}} - if err := s.UpdateMapping(t.Context(), mapping.Mapping{ - ID: id, Name: "renamed mapping", SourceHint: "github", Fields: newFields, - }); err != nil { - t.Fatalf("UpdateMapping: %v", err) - } - - after, err := s.GetMapping(t.Context(), id) - if err != nil || after == nil { - t.Fatalf("GetMapping after update: %+v, %v", after, err) - } - if after.Name != "renamed mapping" || after.SourceHint != "github" { - t.Fatalf("updated mapping = %+v", after) - } - if len(after.Fields) != 1 || after.Fields[0].Name != "renamed" { - t.Fatalf("updated fields = %+v", after.Fields) - } - if !after.UpdatedAt.After(before.UpdatedAt) && !after.UpdatedAt.Equal(before.UpdatedAt) { - t.Fatalf("UpdatedAt did not advance: before=%v after=%v", before.UpdatedAt, after.UpdatedAt) - } -} - -func TestUpdateMappingMissingReturnsErrMappingNotFound(t *testing.T) { - s := openTest(t) - err := s.UpdateMapping(t.Context(), mapping.Mapping{ID: 999, Name: "x", Fields: testFields()}) - if !errors.Is(err, ErrMappingNotFound) { - t.Fatalf("UpdateMapping on missing id = %v, want ErrMappingNotFound", err) - } -} - -func TestDeleteMappingRemovesRow(t *testing.T) { - s := openTest(t) - id, err := s.InsertMapping(t.Context(), mapping.Mapping{Name: "m", Fields: testFields()}) - if err != nil { - t.Fatalf("InsertMapping: %v", err) - } - if err := s.DeleteMapping(t.Context(), id); err != nil { - t.Fatalf("DeleteMapping: %v", err) - } - got, err := s.GetMapping(t.Context(), id) - if err != nil { - t.Fatalf("GetMapping after delete: %v", err) - } - if got != nil { - t.Fatalf("GetMapping after delete = %+v, want nil", got) - } -} - -func TestDeleteMappingMissingReturnsErrMappingNotFound(t *testing.T) { - s := openTest(t) - err := s.DeleteMapping(t.Context(), 999) - if !errors.Is(err, ErrMappingNotFound) { - t.Fatalf("DeleteMapping on missing id = %v, want ErrMappingNotFound", err) - } -} diff --git a/internal/store/playbook_dispatches.go b/internal/store/playbook_dispatches.go deleted file mode 100644 index 97da05e2f..000000000 --- a/internal/store/playbook_dispatches.go +++ /dev/null @@ -1,62 +0,0 @@ -package store - -import ( - "context" - "time" -) - -// playbookDispatchesSchema is the durable idempotency ledger for -// side-effecting playbook actions (docs/prds/eda-playbook-engine.md gap 2). -// It copies binding_dispatches' conventions exactly: a durable table whose -// PRIMARY KEY is the structural (playbook_id, playbook_version, event_id, -// action_id) tuple, written with INSERT OR IGNORE so a duplicate is a no-op -// write rather than a constraint error. -const playbookDispatchesSchema = ` -CREATE TABLE IF NOT EXISTS playbook_dispatches ( - playbook_id TEXT NOT NULL, - playbook_version TEXT NOT NULL, - event_id TEXT NOT NULL, - action_id TEXT NOT NULL, - dispatched_at TEXT NOT NULL, - PRIMARY KEY (playbook_id, playbook_version, event_id, action_id) -); -` - -// RecordPlaybookDispatch writes one (playbook, version, event, action) dedup -// row. INSERT OR IGNORE + RowsAffected is the dedup test: a duplicate is a -// no-op write and returns ErrAlreadyDispatched rather than a constraint -// error. The row is written and committed BEFORE the action's side effect is -// invoked by the coordinator, which is the deliberate reverse of -// binding_dispatches: an at-most-once ledger for non-revocable side effects. -func (s *Store) RecordPlaybookDispatch( - ctx context.Context, - playbookID string, - playbookVersion string, - eventID string, - actionID string, -) error { - res, err := s.db.ExecContext(ctx, ` - INSERT OR IGNORE INTO playbook_dispatches (playbook_id, playbook_version, event_id, action_id, dispatched_at) - VALUES (?, ?, ?, ?, ?)`, - playbookID, playbookVersion, eventID, actionID, - time.Now().UTC().Format(bindingTimeLayout)) - if err != nil { - return err - } - n, err := res.RowsAffected() - if err != nil { - return err - } - if n == 0 { - return ErrAlreadyDispatched - } - return nil -} - -// DeletePlaybookDispatches removes every ledger row for the given playbook, -// mirroring DeleteBinding's row cleanup so a recreated playbook does not -// inherit stale dedup state. -func (s *Store) DeletePlaybookDispatches(ctx context.Context, playbookID string) error { - _, err := s.db.ExecContext(ctx, `DELETE FROM playbook_dispatches WHERE playbook_id = ?`, playbookID) - return err -} diff --git a/internal/store/playbook_dispatches_test.go b/internal/store/playbook_dispatches_test.go deleted file mode 100644 index 75b85bc41..000000000 --- a/internal/store/playbook_dispatches_test.go +++ /dev/null @@ -1,73 +0,0 @@ -package store - -import ( - "errors" - "testing" -) - -func TestRecordPlaybookDispatchIsIdempotent(t *testing.T) { - s := openTest(t) - ctx := t.Context() - if err := s.RecordPlaybookDispatch(ctx, "pb.yaml", "abc123", "archie:acme/widget/7", "notify"); err != nil { - t.Fatalf("first RecordPlaybookDispatch: %v", err) - } - err := s.RecordPlaybookDispatch(ctx, "pb.yaml", "abc123", "archie:acme/widget/7", "notify") - if !errors.Is(err, ErrAlreadyDispatched) { - t.Fatalf("second RecordPlaybookDispatch = %v, want ErrAlreadyDispatched", err) - } -} - -func TestRecordPlaybookDispatchKeyIsAllFourComponents(t *testing.T) { - s := openTest(t) - ctx := t.Context() - - if err := s.RecordPlaybookDispatch(ctx, "pb", "v1", "e1", "notify"); err != nil { - t.Fatalf("record (pb, v1, e1, notify): %v", err) - } - // Every component of the PRIMARY KEY distinguishes a row: a mutant key - // missing any one of the four would collapse distinct dispatches here. - if err := s.RecordPlaybookDispatch(ctx, "pb", "v1", "e1", "build"); err != nil { - t.Fatalf("record (pb, v1, e1, build) = %v, want success (action_id is a key component)", err) - } - if err := s.RecordPlaybookDispatch(ctx, "pb", "v1", "e2", "notify"); err != nil { - t.Fatalf("record (pb, v1, e2, notify) = %v, want success (event_id is a key component)", err) - } - if err := s.RecordPlaybookDispatch(ctx, "pb", "v2", "e1", "notify"); err != nil { - t.Fatalf("record (pb, v2, e1, notify) = %v, want success (playbook_version is a key component)", err) - } - if err := s.RecordPlaybookDispatch(ctx, "pb2", "v1", "e1", "notify"); err != nil { - t.Fatalf("record (pb2, v1, e1, notify) = %v, want success (playbook_id is a key component)", err) - } - if err := s.RecordPlaybookDispatch(ctx, "pb", "v1", "e1", "notify"); !errors.Is(err, ErrAlreadyDispatched) { - t.Fatalf("re-record (pb, v1, e1, notify) = %v, want ErrAlreadyDispatched", err) - } -} - -func TestDeletePlaybookDispatchesRemovesOnlyThatPlaybook(t *testing.T) { - s := openTest(t) - ctx := t.Context() - if err := s.RecordPlaybookDispatch(ctx, "pb.yaml", "v1", "archie:acme/widget/7", "notify"); err != nil { - t.Fatalf("RecordPlaybookDispatch pb.yaml: %v", err) - } - if err := s.RecordPlaybookDispatch(ctx, "other.yaml", "v2", "archie:acme/widget/8", "notify"); err != nil { - t.Fatalf("RecordPlaybookDispatch other.yaml: %v", err) - } - - if err := s.DeletePlaybookDispatches(ctx, "pb.yaml"); err != nil { - t.Fatalf("DeletePlaybookDispatches: %v", err) - } - - var deleted, other int - if err := s.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM playbook_dispatches WHERE playbook_id=?`, "pb.yaml").Scan(&deleted); err != nil { - t.Fatalf("COUNT pb.yaml: %v", err) - } - if err := s.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM playbook_dispatches WHERE playbook_id=?`, "other.yaml").Scan(&other); err != nil { - t.Fatalf("COUNT other.yaml: %v", err) - } - if deleted != 0 { - t.Fatalf("playbook_dispatches rows for pb.yaml = %d, want 0", deleted) - } - if other != 1 { - t.Fatalf("playbook_dispatches rows for other.yaml = %d, want 1 (delete must not touch other playbooks)", other) - } -} diff --git a/internal/store/store.go b/internal/store/store.go index 09e92d550..066ead888 100644 --- a/internal/store/store.go +++ b/internal/store/store.go @@ -20,8 +20,7 @@ import ( ) type Store struct { - db *sql.DB - bindingsCipher BindingCipher + db *sql.DB } // taskSchemaVersion is the newest schema this binary opens. ValidateFile @@ -32,16 +31,7 @@ const taskSchemaVersion = 4 // OpenOption configures the store at open time. type OpenOption func(*openOptions) -type openOptions struct { - bindingsCipher BindingCipher -} - -// WithBindingCipher installs an at-rest encryption cipher for binding secrets -// (docs/prds/binding-secret-encryption.md). When omitted, binding secrets are -// persisted as plaintext -- legacy behaviour, unchanged. -func WithBindingCipher(c BindingCipher) OpenOption { - return func(o *openOptions) { o.bindingsCipher = c } -} +type openOptions struct{} // Open opens (creating if needed) the SQLite database and its schema. func Open(ctx context.Context, path string, opts ...OpenOption) (*Store, error) { @@ -57,13 +47,13 @@ func Open(ctx context.Context, path string, opts ...OpenOption) (*Store, error) return nil, err } db.SetMaxOpenConns(1) - if _, err := db.ExecContext(ctx, schema+eventsSchema+capturesSchema+mappingsSchema+bindingsSchema+playbookDispatchesSchema+configSnapshotSchema+channelStatusSchema+applyStatusSchema+resourcesSchema+identitiesSchema); err != nil { + if _, err := db.ExecContext(ctx, schema+eventsSchema+configSnapshotSchema+channelStatusSchema+applyStatusSchema+resourcesSchema+identitiesSchema); err != nil { return nil, errors.Join(fmt.Errorf("store: init schema: %w", err), db.Close()) } if err := migrateTasks(ctx, db); err != nil { return nil, errors.Join(fmt.Errorf("store: migrate: %w", err), db.Close()) } - return &Store{db: db, bindingsCipher: o.bindingsCipher}, nil + return &Store{db: db}, nil } func sqliteDSN(path string) string { @@ -94,10 +84,6 @@ func migrateTasks(ctx context.Context, db *sql.DB) error { if err != nil { return err } - bindingColumns, err := tableColumns(ctx, tx, "bindings") - if err != nil { - return err - } // events is created by `CREATE TABLE IF NOT EXISTS` (eventsSchema), which // is a no-op against a database that already has the table. On an existing // archie.db this read plus the `events` arm below is therefore the ONLY @@ -117,25 +103,22 @@ func migrateTasks(ctx context.Context, db *sql.DB) error { {"tasks", "retry_count", `ALTER TABLE tasks ADD COLUMN retry_count INTEGER NOT NULL DEFAULT 0`}, {"tasks", "source", `ALTER TABLE tasks ADD COLUMN source TEXT NOT NULL DEFAULT 'forge'`}, {"tasks", "identity", `ALTER TABLE tasks ADD COLUMN identity TEXT NOT NULL DEFAULT ''`}, - {"tasks", "binding_id", `ALTER TABLE tasks ADD COLUMN binding_id INTEGER NOT NULL DEFAULT 0`}, + {"tasks", "binding_id", `ALTER TABLE tasks ADD COLUMN binding_id TEXT NOT NULL DEFAULT ''`}, {"tasks", "binding_version", `ALTER TABLE tasks ADD COLUMN binding_version INTEGER NOT NULL DEFAULT 0`}, {"tasks", "review_payload", `ALTER TABLE tasks ADD COLUMN review_payload TEXT NOT NULL DEFAULT ''`}, {"tasks", "workflow_definition_version", `ALTER TABLE tasks ADD COLUMN workflow_definition_version INTEGER NOT NULL DEFAULT 0`}, {"tasks", "workflow_definition_digest", `ALTER TABLE tasks ADD COLUMN workflow_definition_digest TEXT NOT NULL DEFAULT ''`}, {"tasks", "workflow_definition_yaml", `ALTER TABLE tasks ADD COLUMN workflow_definition_yaml TEXT NOT NULL DEFAULT ''`}, - {"bindings", "owner", `ALTER TABLE bindings ADD COLUMN owner TEXT NOT NULL DEFAULT ''`}, - {"bindings", "repo", `ALTER TABLE bindings ADD COLUMN repo TEXT NOT NULL DEFAULT ''`}, {"events", "attempt", `ALTER TABLE events ADD COLUMN attempt INTEGER NOT NULL DEFAULT 0`}, {"events", "actor_id", `ALTER TABLE events ADD COLUMN actor_id TEXT NOT NULL DEFAULT ''`}, {"events", "actor_kind", `ALTER TABLE events ADD COLUMN actor_kind TEXT NOT NULL DEFAULT ''`}, {"events", "principal_id", `ALTER TABLE events ADD COLUMN principal_id TEXT NOT NULL DEFAULT ''`}, } for _, migration := range migrations { + // Only tasks and events remain here; the event-capture tables moved + // to internal/infrastructure/edastore, which owns their schema. present := columns - switch migration.table { - case "bindings": - present = bindingColumns - case "events": + if migration.table == "events" { present = eventsColumns } if present[migration.column] { @@ -248,7 +231,11 @@ CREATE TABLE IF NOT EXISTS tasks ( retry_count INTEGER NOT NULL DEFAULT 0, source TEXT NOT NULL DEFAULT 'forge', identity TEXT NOT NULL DEFAULT '', - binding_id INTEGER NOT NULL DEFAULT 0, + -- binding_id carries the id of the edastore binding that produced this + -- task, or "" for a task nobody bound. It is TEXT because bindings are + -- PocketBase records; a database created before that stores the same + -- values in an INTEGER-affinity column, which SQLite keeps as TEXT. + binding_id TEXT NOT NULL DEFAULT '', binding_version INTEGER NOT NULL DEFAULT 0, review_payload TEXT NOT NULL DEFAULT '', workflow_definition_version INTEGER NOT NULL DEFAULT 0, @@ -344,7 +331,7 @@ func (s *Store) EnqueueChatTask(ctx context.Context, owner, repo, title, body, w // a future repair pass could backfill. This is the same // best-effort-provenance pattern the rest of the task lifecycle uses // for fields added after the row's primary insert. -func (s *Store) EnqueueBindingTask(ctx context.Context, owner, repo, title, body, wf, identity string, bindingID int64, bindingVersion int) (*workflow.Task, error) { +func (s *Store) EnqueueBindingTask(ctx context.Context, owner, repo, title, body, wf, identity, bindingID string, bindingVersion int) (*workflow.Task, error) { t, err := s.EnqueueChatTask(ctx, owner, repo, title, body, wf, identity) if err != nil { return nil, err diff --git a/internal/store/store_test.go b/internal/store/store_test.go index 59de7c265..5d1a24eeb 100644 --- a/internal/store/store_test.go +++ b/internal/store/store_test.go @@ -486,7 +486,7 @@ func TestTasksBindingColumnsRoundTrip(t *testing.T) { } if _, err := s.db.ExecContext(ctx, `UPDATE tasks SET binding_id=?, binding_version=? WHERE id=?`, - int64(42), 3, task.ID); err != nil { + "rbind0000000001", 3, task.ID); err != nil { t.Fatalf("UPDATE binding provenance: %v", err) } @@ -501,8 +501,8 @@ func TestTasksBindingColumnsRoundTrip(t *testing.T) { if got == nil { t.Fatalf("%s: nil task", name) } - if got.BindingID != 42 || got.BindingVersion != 3 { - t.Fatalf("%s: BindingID=%d BindingVersion=%d, want 42/3", + if got.BindingID != "rbind0000000001" || got.BindingVersion != 3 { + t.Fatalf("%s: BindingID=%q BindingVersion=%d, want rbind0000000001/3", name, got.BindingID, got.BindingVersion) } } @@ -511,7 +511,7 @@ func TestTasksBindingColumnsRoundTrip(t *testing.T) { if err != nil { t.Fatalf("Tasks: %v", err) } - if len(listed) == 0 || listed[0].BindingID != 42 || listed[0].BindingVersion != 3 { + if len(listed) == 0 || listed[0].BindingID != "rbind0000000001" || listed[0].BindingVersion != 3 { t.Fatalf("Tasks() round-trip: %+v", listed) } } diff --git a/internal/webui/api_binding.go b/internal/webui/api_binding.go index 5490c9658..85d48cb63 100644 --- a/internal/webui/api_binding.go +++ b/internal/webui/api_binding.go @@ -4,7 +4,6 @@ import ( "encoding/json" "errors" "net/http" - "strconv" "github.com/samcharles93/archie-core/internal/domain/binding" "github.com/samcharles93/archie-core/internal/domain/storecontract" @@ -16,7 +15,7 @@ import ( type bindingRequest struct { Name string `json:"name"` Matcher binding.Matcher `json:"matcher"` - MappingID int64 `json:"mapping_id"` + MappingID string `json:"mapping_id"` Workflow string `json:"workflow"` // Owner and Repo optionally pin the binding to one configured repo, // for multi-repo deployments. Both empty is valid (falls back to the @@ -104,8 +103,8 @@ func (s *Server) handleBindingGet(w http.ResponseWriter, r *http.Request) { http.Error(w, "bindings not configured", http.StatusServiceUnavailable) return } - id, err := strconv.ParseInt(r.PathValue("id"), 10, 64) - if err != nil { + id := r.PathValue("id") + if id == "" { http.Error(w, "invalid binding id", http.StatusBadRequest) return } @@ -131,8 +130,8 @@ func (s *Server) handleBindingUpdate(w http.ResponseWriter, r *http.Request) { http.Error(w, "bindings not configured", http.StatusServiceUnavailable) return } - id, err := strconv.ParseInt(r.PathValue("id"), 10, 64) - if err != nil { + id := r.PathValue("id") + if id == "" { http.Error(w, "invalid binding id", http.StatusBadRequest) return } @@ -194,8 +193,8 @@ func (s *Server) handleBindingDelete(w http.ResponseWriter, r *http.Request) { http.Error(w, "bindings not configured", http.StatusServiceUnavailable) return } - id, err := strconv.ParseInt(r.PathValue("id"), 10, 64) - if err != nil { + id := r.PathValue("id") + if id == "" { http.Error(w, "invalid binding id", http.StatusBadRequest) return } @@ -219,8 +218,8 @@ func (s *Server) handleBindingApprove(w http.ResponseWriter, r *http.Request) { http.Error(w, "bindings not configured", http.StatusServiceUnavailable) return } - id, err := strconv.ParseInt(r.PathValue("id"), 10, 64) - if err != nil { + id := r.PathValue("id") + if id == "" { http.Error(w, "invalid binding id", http.StatusBadRequest) return } diff --git a/internal/webui/api_binding_test.go b/internal/webui/api_binding_test.go index 85a9f520c..91ebe44a9 100644 --- a/internal/webui/api_binding_test.go +++ b/internal/webui/api_binding_test.go @@ -5,13 +5,13 @@ import ( "log/slog" "net/http" "path/filepath" - "strconv" "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" ) @@ -25,19 +25,20 @@ func bindingTestServer(t *testing.T) *Server { t.Fatal(err) } t.Cleanup(func() { _ = s.Close() }) + eda := edastore.OpenTest(t) return &Server{ Store: s, Log: slog.New(slog.DiscardHandler), - Mappings: s, - Captures: s, - Bindings: s, + Mappings: eda, + Captures: eda, + Bindings: eda, ControlPlane: workflowControlPlane(t, workflow.WorkflowDefinitionCollection{Definitions: []workflow.WorkflowDefinitionEntry{{ID: "implement", YAML: "id: implement\nsteps:\n - type: implement.prepare\n"}}}), } } // seedMapping inserts one payload mapping and returns its row ID, so // binding tests have a valid non-zero mapping_id without hand-rolling SQL. -func seedMapping(t *testing.T, srv *Server, name string) int64 { +func seedMapping(t *testing.T, srv *Server, name string) string { t.Helper() id, err := srv.Mappings.InsertMapping(t.Context(), mapping.Mapping{ Name: name, @@ -54,7 +55,7 @@ func seedMapping(t *testing.T, srv *Server, name string) int64 { // binding.Validate and server-side workflow validation. The Secret is 32 // bytes (above the 16-byte floor) so length never accidentally trips // validation in a test that isn't about secret length. -func validBindingRequest(suffix, source string, mappingID int64) map[string]any { +func validBindingRequest(suffix, source, mappingID string) map[string]any { return map[string]any{ "name": "binding " + suffix, "matcher": map[string]any{"source": source}, @@ -76,7 +77,7 @@ func TestHandleBindingCreateAndGet(t *testing.T) { if err := json.Unmarshal(w.Body.Bytes(), &created); err != nil { t.Fatalf("unmarshal created: %v", err) } - if created.ID == 0 { + if created.ID == "" { t.Fatalf("created.ID = 0; body = %s", w.Body.String()) } if created.Status != binding.StatusDraft { @@ -86,7 +87,7 @@ func TestHandleBindingCreateAndGet(t *testing.T) { t.Fatalf("created.Secret = %q, want \"\" (response must strip secret)", created.Secret) } - w = doJSON(t, srv, http.MethodGet, "/api/bindings/"+strconv.FormatInt(created.ID, 10), nil) + w = doJSON(t, srv, http.MethodGet, "/api/bindings/"+created.ID, nil) if w.Code != http.StatusOK { t.Fatalf("get status = %d, want %d; body = %s", w.Code, http.StatusOK, w.Body.String()) } @@ -95,7 +96,7 @@ func TestHandleBindingCreateAndGet(t *testing.T) { t.Fatalf("unmarshal got: %v", err) } if got.ID != created.ID { - t.Fatalf("got.ID = %d, want %d", got.ID, created.ID) + t.Fatalf("got.ID = %q, want %q", got.ID, created.ID) } if got.Secret != "" { t.Fatalf("get.Secret = %q, want \"\"", got.Secret) @@ -128,7 +129,7 @@ func TestHandleBindingCreateAndUpdateRoundTripsOwnerRepo(t *testing.T) { updateReq := validBindingRequest("a", "sentry", mappingID) updateReq["owner"] = "other-org" updateReq["repo"] = "other-repo" - w = doJSON(t, srv, http.MethodPatch, "/api/bindings/"+strconv.FormatInt(created.ID, 10), updateReq) + w = doJSON(t, srv, http.MethodPatch, "/api/bindings/"+created.ID, updateReq) if w.Code != http.StatusOK { t.Fatalf("update status = %d, want %d; body = %s", w.Code, http.StatusOK, w.Body.String()) } @@ -256,7 +257,7 @@ func TestHandleBindingUpdatePreservesOtherFields(t *testing.T) { // pending_approval yet, an edit on a draft row correctly stays // draft. This test pins the editable-fields half of the contract. update := validBindingRequest("renamed", "sentry", mappingID) - w = doJSON(t, srv, http.MethodPatch, "/api/bindings/"+strconv.FormatInt(created.ID, 10), update) + w = doJSON(t, srv, http.MethodPatch, "/api/bindings/"+created.ID, update) if w.Code != http.StatusOK { t.Fatalf("patch status = %d, want %d; body = %s", w.Code, http.StatusOK, w.Body.String()) } @@ -268,7 +269,7 @@ func TestHandleBindingUpdatePreservesOtherFields(t *testing.T) { t.Fatalf("updated.Name = %q, want %q", updated.Name, "binding renamed") } if updated.MappingID != mappingID { - t.Fatalf("updated.MappingID = %d, want %d", updated.MappingID, mappingID) + t.Fatalf("updated.MappingID = %q, want %q", updated.MappingID, mappingID) } // Status MUST not regress from a state the caller never asked for. if updated.Status != binding.StatusDraft && updated.Status != binding.StatusPendingApproval { @@ -291,7 +292,7 @@ func TestHandleBindingUpdateWithEmptySecretPreservesExisting(t *testing.T) { update := validBindingRequest("renamed", "sentry", mappingID) update["secret"] = "" - w = doJSON(t, srv, http.MethodPatch, "/api/bindings/"+strconv.FormatInt(created.ID, 10), update) + w = doJSON(t, srv, http.MethodPatch, "/api/bindings/"+created.ID, update) if w.Code != http.StatusOK { t.Fatalf("patch status = %d, want %d (empty secret must mean 'keep existing', not fail validation); body = %s", w.Code, http.StatusOK, w.Body.String()) } @@ -315,7 +316,7 @@ func TestHandleBindingApproveFromDraftRejected(t *testing.T) { // draft is NOT a valid source state for approve; the binding must // first land in pending_approval (via PATCH). Approve from draft // returns ErrBindingTransition -> 409. - w = doJSON(t, srv, http.MethodPost, "/api/bindings/"+strconv.FormatInt(created.ID, 10)+"/approve", nil) + w = doJSON(t, srv, http.MethodPost, "/api/bindings/"+created.ID+"/approve", nil) if w.Code != http.StatusConflict { t.Fatalf("status = %d, want %d; body = %s", w.Code, http.StatusConflict, w.Body.String()) } @@ -335,7 +336,7 @@ func TestHandleBindingApproveHappyPath(t *testing.T) { t.Fatalf("created status = %q, want %q", created.Status, binding.StatusDraft) } - w = doJSON(t, srv, http.MethodPatch, "/api/bindings/"+strconv.FormatInt(created.ID, 10), validBindingRequest("renamed", "sentry", mappingID)) + w = doJSON(t, srv, http.MethodPatch, "/api/bindings/"+created.ID, validBindingRequest("renamed", "sentry", mappingID)) if w.Code != http.StatusOK { t.Fatalf("patch status = %d, want %d; body = %s", w.Code, http.StatusOK, w.Body.String()) } @@ -345,7 +346,7 @@ func TestHandleBindingApproveHappyPath(t *testing.T) { t.Fatalf("patched status = %q, want %q", patched.Status, binding.StatusPendingApproval) } - w = doJSON(t, srv, http.MethodPost, "/api/bindings/"+strconv.FormatInt(created.ID, 10)+"/approve", nil) + w = doJSON(t, srv, http.MethodPost, "/api/bindings/"+created.ID+"/approve", nil) if w.Code != http.StatusOK { t.Fatalf("approve status = %d, want %d; body = %s", w.Code, http.StatusOK, w.Body.String()) } @@ -367,11 +368,11 @@ func TestHandleBindingEditOnArmedDropsToPendingApproval(t *testing.T) { _ = json.Unmarshal(w.Body.Bytes(), &created) // Drive it to armed via the happy path. - _ = doJSON(t, srv, http.MethodPatch, "/api/bindings/"+strconv.FormatInt(created.ID, 10), validBindingRequest("a", "sentry", mappingID)) - _ = doJSON(t, srv, http.MethodPost, "/api/bindings/"+strconv.FormatInt(created.ID, 10)+"/approve", nil) + _ = doJSON(t, srv, http.MethodPatch, "/api/bindings/"+created.ID, validBindingRequest("a", "sentry", mappingID)) + _ = doJSON(t, srv, http.MethodPost, "/api/bindings/"+created.ID+"/approve", nil) // Now edit. Status must drop back to pending_approval. - w = doJSON(t, srv, http.MethodPatch, "/api/bindings/"+strconv.FormatInt(created.ID, 10), validBindingRequest("a-edited", "sentry", mappingID)) + w = doJSON(t, srv, http.MethodPatch, "/api/bindings/"+created.ID, validBindingRequest("a-edited", "sentry", mappingID)) if w.Code != http.StatusOK { t.Fatalf("patch status = %d, want %d; body = %s", w.Code, http.StatusOK, w.Body.String()) } @@ -397,11 +398,11 @@ func TestHandleBindingDeleteRemovesRow(t *testing.T) { var created binding.Binding _ = json.Unmarshal(w.Body.Bytes(), &created) - w = doJSON(t, srv, http.MethodDelete, "/api/bindings/"+strconv.FormatInt(created.ID, 10), nil) + w = doJSON(t, srv, http.MethodDelete, "/api/bindings/"+created.ID, nil) if w.Code != http.StatusNoContent { t.Fatalf("delete status = %d, want %d; body = %s", w.Code, http.StatusNoContent, w.Body.String()) } - w = doJSON(t, srv, http.MethodGet, "/api/bindings/"+strconv.FormatInt(created.ID, 10), nil) + w = doJSON(t, srv, http.MethodGet, "/api/bindings/"+created.ID, nil) if w.Code != http.StatusNotFound { t.Fatalf("get after delete status = %d, want %d", w.Code, http.StatusNotFound) } @@ -428,7 +429,7 @@ func TestHandleBindingMutationsRequireCSRFHeader(t *testing.T) { if err := json.Unmarshal(w.Body.Bytes(), &created); err != nil { t.Fatalf("unmarshal created binding: %v; body = %s", err, w.Body.String()) } - id := strconv.FormatInt(created.ID, 10) + id := created.ID tests := []struct { name, method, path string diff --git a/internal/webui/api_capture_test.go b/internal/webui/api_capture_test.go index 79f19dddc..d1fd68eb9 100644 --- a/internal/webui/api_capture_test.go +++ b/internal/webui/api_capture_test.go @@ -10,6 +10,7 @@ import ( "testing" "time" + "github.com/samcharles93/archie-core/internal/infrastructure/edastore" "github.com/samcharles93/archie-core/internal/store" ) @@ -25,16 +26,18 @@ func captureTestServer(t *testing.T) *Server { } t.Cleanup(func() { _ = s.Close() }) return &Server{ - Store: s, - Log: slog.New(slog.DiscardHandler), - Captures: s, + 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), } } // seedCapture inserts a captured row directly through the CaptureStore. // These tests cover the list read; the write path itself lives in // internal/infrastructure/captureintake and is tested there. -func seedCapture(t *testing.T, srv *Server, source string) int64 { +func seedCapture(t *testing.T, srv *Server, source string) string { t.Helper() id, err := srv.Captures.InsertCapture(t.Context(), store.CapturedEvent{ ReceivedAt: time.Now().UTC(), diff --git a/internal/webui/api_mapping.go b/internal/webui/api_mapping.go index 2b5f62ab4..1a0cd343a 100644 --- a/internal/webui/api_mapping.go +++ b/internal/webui/api_mapping.go @@ -5,7 +5,6 @@ import ( "encoding/json" "errors" "net/http" - "strconv" "github.com/samcharles93/archie-core/internal/domain/mapping" "github.com/samcharles93/archie-core/internal/domain/storecontract" @@ -73,8 +72,8 @@ func (s *Server) handleMappingGet(w http.ResponseWriter, r *http.Request) { http.Error(w, "mappings not configured", http.StatusServiceUnavailable) return } - id, err := strconv.ParseInt(r.PathValue("id"), 10, 64) - if err != nil { + id := r.PathValue("id") + if id == "" { http.Error(w, "invalid mapping id", http.StatusBadRequest) return } @@ -99,8 +98,8 @@ func (s *Server) handleMappingUpdate(w http.ResponseWriter, r *http.Request) { http.Error(w, "mappings not configured", http.StatusServiceUnavailable) return } - id, err := strconv.ParseInt(r.PathValue("id"), 10, 64) - if err != nil { + id := r.PathValue("id") + if id == "" { http.Error(w, "invalid mapping id", http.StatusBadRequest) return } @@ -140,8 +139,8 @@ func (s *Server) handleMappingDelete(w http.ResponseWriter, r *http.Request) { http.Error(w, "mappings not configured", http.StatusServiceUnavailable) return } - id, err := strconv.ParseInt(r.PathValue("id"), 10, 64) - if err != nil { + id := r.PathValue("id") + if id == "" { http.Error(w, "invalid mapping id", http.StatusBadRequest) return } @@ -161,7 +160,7 @@ func (s *Server) handleMappingDelete(w http.ResponseWriter, r *http.Request) { // against a real captured event before saving anything -- Fields is loose // input, not a saved mapping ID, per docs/prds/payload-field-mapping.md. type mappingPreviewRequest struct { - CaptureID int64 `json:"capture_id"` + CaptureID string `json:"capture_id"` Fields []mapping.Field `json:"fields"` } @@ -201,7 +200,7 @@ func (s *Server) handleMappingPreview(w http.ResponseWriter, r *http.Request) { // exactly one reader, the dashboard list view, so a by-ID lookup was never // needed until preview), so this scans the newest window rather than // adding a new store method for a single low-volume caller. -func (s *Server) captureByID(ctx context.Context, id int64) (*storecontract.CapturedEvent, error) { +func (s *Server) captureByID(ctx context.Context, id string) (*storecontract.CapturedEvent, error) { captures, err := s.Captures.ListCaptures(ctx, mappingCaptureScanWindow(s.CaptureMaxEvents)) if err != nil { return nil, err diff --git a/internal/webui/api_mapping_test.go b/internal/webui/api_mapping_test.go index bc0896e65..d5306b9a0 100644 --- a/internal/webui/api_mapping_test.go +++ b/internal/webui/api_mapping_test.go @@ -7,10 +7,10 @@ import ( "net/http" "net/http/httptest" "path/filepath" - "strconv" "testing" "github.com/samcharles93/archie-core/internal/domain/mapping" + "github.com/samcharles93/archie-core/internal/infrastructure/edastore" "github.com/samcharles93/archie-core/internal/store" ) @@ -24,11 +24,12 @@ func mappingTestServer(t *testing.T) *Server { t.Fatal(err) } t.Cleanup(func() { _ = s.Close() }) + eda := edastore.OpenTest(t) return &Server{ Store: s, Log: slog.New(slog.DiscardHandler), - Mappings: s, - Captures: s, + Mappings: eda, + Captures: eda, } } @@ -86,11 +87,11 @@ func TestHandleMappingCreateAndGet(t *testing.T) { if err := json.Unmarshal(w.Body.Bytes(), &created); err != nil { t.Fatalf("unmarshal created mapping: %v", err) } - if created.ID == 0 || created.Name != "sentry issue opened" { + if created.ID == "" || created.Name != "sentry issue opened" { t.Fatalf("created mapping = %+v", created) } - w = doJSON(t, srv, http.MethodGet, "/api/mappings/"+strconv.FormatInt(created.ID, 10), nil) + w = doJSON(t, srv, http.MethodGet, "/api/mappings/"+created.ID, nil) if w.Code != http.StatusOK { t.Fatalf("get status = %d, want %d; body = %s", w.Code, http.StatusOK, w.Body.String()) } @@ -151,7 +152,7 @@ func TestHandleMappingUpdate(t *testing.T) { var created mapping.Mapping _ = json.Unmarshal(w.Body.Bytes(), &created) - w = doJSON(t, srv, http.MethodPatch, "/api/mappings/"+strconv.FormatInt(created.ID, 10), map[string]any{ + w = doJSON(t, srv, http.MethodPatch, "/api/mappings/"+created.ID, map[string]any{ "name": "renamed", "fields": []mapping.Field{{Name: "b", Path: "b", Type: mapping.TypeBool}}, }) @@ -159,7 +160,7 @@ func TestHandleMappingUpdate(t *testing.T) { t.Fatalf("update status = %d, want %d; body = %s", w.Code, http.StatusOK, w.Body.String()) } - w = doJSON(t, srv, http.MethodGet, "/api/mappings/"+strconv.FormatInt(created.ID, 10), nil) + w = doJSON(t, srv, http.MethodGet, "/api/mappings/"+created.ID, nil) var got mapping.Mapping _ = json.Unmarshal(w.Body.Bytes(), &got) if got.Name != "renamed" || len(got.Fields) != 1 || got.Fields[0].Name != "b" { @@ -187,11 +188,11 @@ func TestHandleMappingDelete(t *testing.T) { var created mapping.Mapping _ = json.Unmarshal(w.Body.Bytes(), &created) - w = doJSON(t, srv, http.MethodDelete, "/api/mappings/"+strconv.FormatInt(created.ID, 10), nil) + w = doJSON(t, srv, http.MethodDelete, "/api/mappings/"+created.ID, nil) if w.Code != http.StatusNoContent { t.Fatalf("delete status = %d, want %d; body = %s", w.Code, http.StatusNoContent, w.Body.String()) } - w = doJSON(t, srv, http.MethodGet, "/api/mappings/"+strconv.FormatInt(created.ID, 10), nil) + w = doJSON(t, srv, http.MethodGet, "/api/mappings/"+created.ID, nil) if w.Code != http.StatusNotFound { t.Fatalf("get after delete status = %d, want %d", w.Code, http.StatusNotFound) } @@ -235,7 +236,7 @@ func TestHandleMappingPreviewResolvesAgainstARealCapture(t *testing.T) { func TestHandleMappingPreviewUnknownCaptureReturns404(t *testing.T) { srv := mappingTestServer(t) w := doJSON(t, srv, http.MethodPost, "/api/mappings/preview", map[string]any{ - "capture_id": 999, + "capture_id": "rabsent00000000", "fields": []mapping.Field{{Name: "a", Path: "a", Type: mapping.TypeString}}, }) if w.Code != http.StatusNotFound { @@ -284,7 +285,7 @@ func TestHandleMappingMutationsRequireCSRFHeader(t *testing.T) { if err := json.Unmarshal(w.Body.Bytes(), &created); err != nil { t.Fatalf("unmarshal created mapping: %v; body = %s", err, w.Body.String()) } - id := strconv.FormatInt(created.ID, 10) + id := created.ID tests := []struct { name, method, path string diff --git a/internal/webui/remote_store_test.go b/internal/webui/remote_store_test.go index b7335dd88..445fbd101 100644 --- a/internal/webui/remote_store_test.go +++ b/internal/webui/remote_store_test.go @@ -21,6 +21,7 @@ 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/staterpc" "github.com/samcharles93/archie-core/internal/store" ) @@ -43,15 +44,17 @@ func newRemoteTestServer(t *testing.T) *Server { t.Fatalf("listen: %v", err) } server := grpc.NewServer() - // The same concrete *store.Store satisfies every interface the server's - // per-surface accessors need; leaving one nil makes ListMappings/ListBindings - // fail closed with err*Unavailable, which is the real composition's wiring. + // Two stores, as in the real composition: the task store serves the task + // 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) staterpc.RegisterServer(server, staterpc.Deps{ Tasks: st, - Captures: st, - Mappings: st, - Bindings: st, - BindingDispatcher: st, + Captures: eda, + Mappings: eda, + Bindings: eda, + BindingDispatcher: eda, BindingTaskCreator: st, Log: slog.New(slog.DiscardHandler), }) diff --git a/proto/state/v1/state.proto b/proto/state/v1/state.proto index 891e27728..c24340147 100644 --- a/proto/state/v1/state.proto +++ b/proto/state/v1/state.proto @@ -231,7 +231,7 @@ message Task { int64 watch_comment_id = 20; string source = 21; string identity = 22; - int64 binding_id = 23; + string binding_id = 23; int64 binding_version = 24; google.protobuf.Timestamp created_at = 25; google.protobuf.Timestamp updated_at = 26; @@ -280,7 +280,7 @@ message Event { // CapturedEvent mirrors internal/store.CapturedEvent. message CapturedEvent { - int64 id = 1; + string id = 1; google.protobuf.Timestamp received_at = 2; string source = 3; string remote_addr = 4; @@ -300,7 +300,7 @@ message MappingField { // Mapping mirrors internal/domain/mapping.Mapping. message Mapping { - int64 id = 1; + string id = 1; string name = 2; string source_hint = 3; repeated MappingField fields = 4; @@ -315,10 +315,10 @@ message BindingMatcher { // Binding mirrors internal/domain/binding.Binding. message Binding { - int64 id = 1; + string id = 1; string name = 2; BindingMatcher matcher = 3; - int64 mapping_id = 4; + string mapping_id = 4; string workflow = 5; string owner = 6; string repo = 7; @@ -610,7 +610,7 @@ message InsertCaptureRequest { int64 retention_seconds = 2; int64 max_events = 3; } -message InsertCaptureResponse { int64 id = 1; } +message InsertCaptureResponse { string id = 1; } message ListCapturesRequest { int64 limit = 1; } message ListCapturesResponse { repeated CapturedEvent captures = 1; } @@ -619,9 +619,9 @@ message StreamCapturesRequest { int64 limit = 1; } message StreamCapturesResponse { CapturedEvent capture = 1; } message InsertMappingRequest { Mapping mapping = 1; } -message InsertMappingResponse { int64 id = 1; } +message InsertMappingResponse { string id = 1; } -message GetMappingRequest { int64 id = 1; } +message GetMappingRequest { string id = 1; } message GetMappingResponse { Mapping mapping = 1; bool found = 2; @@ -633,13 +633,13 @@ message ListMappingsResponse { repeated Mapping mappings = 1; } message UpdateMappingRequest { Mapping mapping = 1; } message UpdateMappingResponse {} -message DeleteMappingRequest { int64 id = 1; } +message DeleteMappingRequest { string id = 1; } message DeleteMappingResponse {} message InsertBindingRequest { Binding binding = 1; } -message InsertBindingResponse { int64 id = 1; } +message InsertBindingResponse { string id = 1; } -message GetBindingRequest { int64 id = 1; } +message GetBindingRequest { string id = 1; } message GetBindingResponse { Binding binding = 1; bool found = 2; @@ -651,19 +651,20 @@ message ListBindingsResponse { repeated Binding bindings = 1; } message UpdateBindingRequest { Binding binding = 1; } message UpdateBindingResponse {} -message DeleteBindingRequest { int64 id = 1; } +message DeleteBindingRequest { string id = 1; } message DeleteBindingResponse {} -message ApproveBindingRequest { int64 id = 1; } +message ApproveBindingRequest { string id = 1; } message ApproveBindingResponse {} message ArmedBindingsForSourceRequest { string source = 1; } message ArmedBindingsForSourceResponse { repeated Binding bindings = 1; } message RecordDispatchRequest { - int64 binding_id = 1; + string binding_id = 1; int64 binding_version = 2; - int64 capture_id = 3; + string capture_id = 3; + // task_id addresses the SQLite-owned task tables, which are not migrating. int64 task_id = 4; } message RecordDispatchResponse {} @@ -698,7 +699,7 @@ message EnqueueBindingTaskRequest { string body = 4; string workflow = 5; string identity = 6; - int64 binding_id = 7; + string binding_id = 7; int64 binding_version = 8; } message EnqueueBindingTaskResponse { Task task = 1; }