The event-capture tables (captures, mappings, bindings, binding_dispatches,
playbook_dispatches) now live in PocketBase-owned collections and their ids
are opaque record ids rather than autoincrement integers. The task lifecycle
stays on SQLite: tasks/transitions/events carry FIFO claim ordering, id-cursor
pagination and the task-grant map, none of which gain anything from being
hand-editable. binding_dispatches.task_id is the single seam and stays an
integer addressing that store.
BREAKING: CapturedEvent.Id, Mapping.Id, Binding.Id and Binding.MappingId are
strings on the wire, as are the ids in the capture/mapping/binding requests.
RecordDispatchRequest.task_id is deliberately unchanged.
What the collections buy, beyond storage: a payload nobody has modelled yet is
inspectable, a mapping is editable at runtime, and a binding's relation to its
mapping is enforced. The old schema declared no FOREIGN KEY on that link, so a
dangling mapping_id was previously possible and is now refused.
Behaviour preserved deliberately, each recovered from the SQLite version
rather than reimplemented from memory:
- draft -> pending_approval -> armed, with approval only from
pending_approval and an edit always returning a binding for re-approval
- one binding per source, guarded on insert, update and approve
- an empty secret on update keeps the stored one, so an edit form that does
not echo it back cannot silently disarm a binding
- ErrMappingNotFound / ErrBindingNotFound on a missing delete target
- sentinels are re-exported from storecontract, never redefined: staterpc
matches on exact canonical message to rehydrate them, so a second
definition would break errors.Is across the wire invisibly
Two implementation notes worth keeping:
- at-most-once dispatch is now a unique index rather than INSERT OR IGNORE.
Only the unique-violation maps to ErrAlreadyDispatched; any other save
error is returned, because treating them all as "already recorded" would
turn the ledger into a silent at-least-once dispatcher.
- captures store received_at themselves at nanosecond precision in a
fixed-width layout. PocketBase autodates are millisecond and record ids
are random, so same-millisecond captures would otherwise order
arbitrarily; the old store got insertion order free from autoincrement.
- ListUndispatchedCaptures is raw SQL: the anti-join is a subquery and
PocketBase's filter DSL is not SQL. A read fires no hooks either way.
Adds tool_calls, which had no persistence at all: tool calls only ever reached
the on-disk task log, readable as text but never queryable or watchable.
Nothing writes it yet.
The binding secret cipher moves with the bindings it protects.
450 lines
18 KiB
Go
450 lines
18 KiB
Go
// state_store.go composes the standalone archie-state-store process. It mirrors
|
|
// gateway.go / cmd/archie-gateway: the binary is a thin main that passes
|
|
// process inputs into RunStateStore, which owns the single archie.db SQLite
|
|
// file, registers every StateStore gRPC handler (the same service .4.2 serves
|
|
// in-process on the daemon), and shuts down cleanly on ctx cancellation.
|
|
//
|
|
// See docs/prds/state-store-contract.md (rev. 2c) -- the single authoritative
|
|
// design surface -- and in particular §5 (binary layout), §9 (transport
|
|
// security boundary) and §11 (the store service owns its own DB lifecycle).
|
|
package archied
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"net"
|
|
"net/http"
|
|
"path/filepath"
|
|
"time"
|
|
|
|
"google.golang.org/grpc"
|
|
|
|
"github.com/samcharles93/archie-core/internal/app/controlplane"
|
|
"github.com/samcharles93/archie-core/internal/config"
|
|
"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"
|
|
"github.com/samcharles93/archie-core/internal/store"
|
|
)
|
|
|
|
func configuredIdentityNames(cfg config.Config) []string {
|
|
if len(cfg.Identities) == 0 {
|
|
name := cfg.BotUser
|
|
if name == "" {
|
|
name = "archie"
|
|
}
|
|
return []string{name}
|
|
}
|
|
names := make([]string, 0, len(cfg.Identities))
|
|
for _, value := range cfg.Identities {
|
|
names = append(names, value.Name)
|
|
}
|
|
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
|
|
Overlay string
|
|
// Listen is the gRPC listen address. Loopback binds (127.0.0.1, ::1,
|
|
// localhost) serve insecure with no token; any non-loopback address
|
|
// requires a non-empty token (or TLS), else the process fails closed
|
|
// (state-store-contract.md §9).
|
|
Listen string
|
|
// Token is the bearer token the State Store server validates for a
|
|
// non-loopback listener. Empty falls back to [services.state].target_token.
|
|
Token string
|
|
// ReadyAddr, when non-empty, starts an HTTP readiness surface on the
|
|
// address: GET /healthz (liveness) and GET /health/detailed (the
|
|
// state_db probe). Empty disables it.
|
|
ReadyAddr string
|
|
// AdminAddr, when non-empty, starts the read-only operator dashboard on
|
|
// the address. It co-tenants on the same SQLite file this process already
|
|
// owns, so it needs no lock and no database of its own. Empty disables it.
|
|
AdminAddr string
|
|
}
|
|
|
|
// RunStateStore owns the single archie.db SQLite file, registers every
|
|
// StateStore gRPC handler, and serves until ctx is cancelled. It opens only
|
|
// the task store -- the gateway's session SQLite is owned by the separate
|
|
// archie-gateway process and is deliberately untouched (state-store-contract
|
|
// rev. 2c §12 step 8). The store service owns its own DB lifecycle, so
|
|
// b.cleanup() is the sole owner closing b.st here (in-process owner).
|
|
func RunStateStore(ctx context.Context, options StateStoreOptions) error {
|
|
b := newBootstrap()
|
|
defer b.cleanup()
|
|
if err := b.loadConfig(ctx, options.Config, options.Overlay); err != nil {
|
|
return err
|
|
}
|
|
listen, err := resolveServiceListen("state", options.Listen, b.cfg.Services.Get(config.ServiceNameState).Listen)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
b.log = b.log.With("component", "state-store", "listen", listen)
|
|
if err := b.openStateStore(ctx); err != nil {
|
|
return err
|
|
}
|
|
identityStore, ok := b.st.(interface {
|
|
BootstrapIdentities(context.Context, []string) error
|
|
})
|
|
if !ok {
|
|
return fmt.Errorf("state store does not support identity bootstrap")
|
|
}
|
|
legacyNames := configuredIdentityNames(b.cfg)
|
|
if err := identityStore.BootstrapIdentities(ctx, legacyNames); err != nil {
|
|
return fmt.Errorf("bootstrap identities: %w", err)
|
|
}
|
|
resources, ok := b.st.(controlplane.ResourceStore)
|
|
if !ok {
|
|
return fmt.Errorf("state store does not support control-plane resources")
|
|
}
|
|
// The validating side's control plane, built here at the composition root
|
|
// before the first definition is read or replaced.
|
|
control, err := openStateStoreControlPlane(resources)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
_, skipped, err := control.ImportConfig(ctx, b.cfg)
|
|
if err != nil {
|
|
return fmt.Errorf("import control-plane resources: %w", err)
|
|
}
|
|
b.reportUnseededResources(skipped)
|
|
|
|
token := options.Token
|
|
if token == "" {
|
|
token = b.cfg.Services.ResolvedToken(config.ServiceNameState, b.secrets.Getenv)
|
|
}
|
|
grants := &staterpc.TaskGrants{}
|
|
//nolint:contextcheck // grpc.StreamServerInterceptor has no context.Context parameter; TaskGrants.StreamInterceptor derives its context from stream.Context() instead
|
|
opts, loopback, err := stateStoreServerOpts(listen, token, grants)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
listener, err := (&net.ListenConfig{}).Listen(ctx, "tcp", listen)
|
|
if err != nil {
|
|
return fmt.Errorf("listen for state store: %w", err)
|
|
}
|
|
defer listener.Close()
|
|
b.log.Info("archie-state-store running", "addr", listener.Addr().String(), "token_required", !loopback)
|
|
|
|
if err := b.startOptionalSurfaces(ctx, options); err != nil {
|
|
return err
|
|
}
|
|
|
|
deps := b.stateStoreDeps(grants)
|
|
deps.ControlPlane = control
|
|
return serveStateStore(ctx, listener, deps, opts)
|
|
}
|
|
|
|
// reportUnseededResources logs every kind ImportConfig could not seed.
|
|
//
|
|
// Reported, not fatal: a stale TOML value in a setting the database owns must
|
|
// not stop this process from starting (docs/prds/runtime-control-plane.md,
|
|
// "Bootstrap, migration, and recovery"). The kind stays ABSENT rather than
|
|
// half-written, so the file document's value is the one in effect for every
|
|
// reader -- the layering leaves a kind with no stored value alone
|
|
// (controlplane.resourceReader) -- and the operator's fix is still the file.
|
|
// Whether the value may RUN is decided where it is used: boot.runtimeConfig
|
|
// validates the effective document and refuses to start archied or the Gateway
|
|
// with one it cannot run. The seed is retried on this process's next start, so
|
|
// a corrected config.toml takes effect when archie-state-store restarts.
|
|
//
|
|
// It is a method rather than a loop in RunStateStore because the boot sequence
|
|
// is at its complexity budget: the branch belongs to the report's own policy,
|
|
// not to the sequence that triggers it.
|
|
func (b *boot) reportUnseededResources(skipped []controlplane.SeedSkip) {
|
|
for _, skip := range skipped {
|
|
b.log.Error("control-plane resource not seeded; the kind stays absent and the file's value is the one in effect",
|
|
"kind", skip.Kind, "err", skip.Err)
|
|
}
|
|
}
|
|
|
|
// openStateStoreControlPlane builds the State Store's control plane server: the
|
|
// validating side of the workflow step vocabulary, registered here at the
|
|
// composition root before the first definition is read or replaced. The same
|
|
// provider set (internal/infrastructure/workflowsteps) is what archie-agent
|
|
// registers before it compiles one, so within one build a definition this
|
|
// server admits is compilable there; a skewed deploy is only fixed by a
|
|
// matching deploy.
|
|
//
|
|
// It is separate from RunStateStore so that function stays within its
|
|
// complexity budget, and step_vocabulary_test.go pins both the call to
|
|
// stepVocabulary below and RunStateStore's call to this function.
|
|
func openStateStoreControlPlane(resources controlplane.ResourceStore) (*controlplane.Server, error) {
|
|
steps, err := stepVocabulary()
|
|
if err != nil {
|
|
return nil, fmt.Errorf("register workflow step vocabulary: %w", err)
|
|
}
|
|
server, err := controlplane.NewServer(resources, steps)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("build control plane server: %w", err)
|
|
}
|
|
return server, nil
|
|
}
|
|
|
|
// openStateStore opens the single task-store SQLite file exactly once for
|
|
// service ownership. It resolves secrets (for the binding cipher) but does
|
|
// NOT open gateway chat sessions -- those live in the separate archie-gateway
|
|
// process on their own SQLite file and are out of state-store scope.
|
|
func (b *boot) openStateStore(ctx context.Context) error {
|
|
cfg, log := b.cfg, b.log
|
|
secrets, err := configuredSecretRegistry(&cfg, log)
|
|
if err != nil {
|
|
log.Error("configure secrets", "err", err)
|
|
return err
|
|
}
|
|
b.secrets = secrets
|
|
bindingCipher, err := bindingCipherFromConfig(cfg, secrets)
|
|
if err != nil {
|
|
log.Error("configure bindings cipher", "err", err)
|
|
return err
|
|
}
|
|
// Claim the database before opening it. This process is the file's owner
|
|
// for as long as it lives, and the claim is what an offline recovery
|
|
// command checks before it rewrites the file: without it, "the State Store
|
|
// is stopped" is a rule the operator is trusted to have followed rather
|
|
// than a fact the command can verify. A second State Store on the same
|
|
// database fails here, which is the single-owner invariant stated instead
|
|
// of merely documented.
|
|
path := taskDBPath(cfg.DBPath)
|
|
ownership, err := store.AcquireOwnership(path)
|
|
if err != nil {
|
|
log.Error("claim state store ownership", "err", err)
|
|
return err
|
|
}
|
|
b.addCleanup(func() {
|
|
if err := ownership.Release(); err != nil {
|
|
log.Error("release state store ownership", "err", err)
|
|
}
|
|
})
|
|
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
|
|
}
|
|
b.st = st
|
|
b.addCleanup(func() {
|
|
if err := st.Close(); err != nil {
|
|
log.Error("close state store", "err", err)
|
|
}
|
|
})
|
|
return nil
|
|
}
|
|
|
|
// stateStoreDeps assembles the store surfaces the StateStore service fronts.
|
|
// b.st is the narrow storecontract.TaskStore; the wide *store.Store also implements
|
|
// the capture/mapping/binding surfaces, so each is asserted here (the same
|
|
// pattern the daemon's wireWebStoreSurfaces uses) and a store that lacks one
|
|
// degrades that group rather than aborting boot.
|
|
func (b *boot) stateStoreDeps(grants *staterpc.TaskGrants) staterpc.Deps {
|
|
deps := staterpc.Deps{Tasks: b.st, Log: b.log, Grants: grants}
|
|
if identities, ok := b.st.(identity.Repository); ok {
|
|
deps.Identities = identities
|
|
}
|
|
// Subject bindings are asserted separately from the repository facade: only
|
|
// the authenticating path resolves a verified subject, and a store that
|
|
// cannot is one where the dashboard cannot name its caller rather than one
|
|
// that fails to boot.
|
|
if bindings, ok := b.st.(identity.SubjectBinding); ok {
|
|
deps.SubjectBindings = bindings
|
|
}
|
|
// Task logs live in the state directory, which this process owns, and the
|
|
// dashboard process owns no such directory -- so this is where a task-log
|
|
// read is served from (docs/prds/ui-service-boundary.md). The reader is
|
|
// the daemon's own registry, built over the same state-directory
|
|
// derivation this process uses for its SQLite file; both resolve from the
|
|
// same configured DBPath, so they agree on where archie keeps its state.
|
|
//
|
|
// The nil check is on the registry, not on the interface it is assigned
|
|
// to: a nil *logging.TaskRegistry stored in this field produces a non-nil
|
|
// interface holding a nil pointer, which the server's own
|
|
// `deps.TaskLogs == nil` guard would not catch. Leaving the field unset is
|
|
// what makes the RPC answer Unavailable -- the honest "this process cannot
|
|
// read logs" -- instead of depending on nil-receiver behaviour to notice.
|
|
if b.taskLogs != nil {
|
|
deps.TaskLogs = b.taskLogs
|
|
}
|
|
// The event-capture contracts are served by the PocketBase store, not the
|
|
// task store: those tables moved. BindingTaskCreator stays below on the
|
|
// 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
|
|
}
|
|
if css, ok := b.st.(storecontract.ConfigSnapshotStore); ok {
|
|
deps.ConfigSnapshots = css
|
|
}
|
|
if as, ok := b.st.(storecontract.ApplyStatusStore); ok {
|
|
deps.ApplyStatus = as
|
|
}
|
|
if cs, ok := b.st.(storecontract.ChannelStatusStore); ok {
|
|
deps.ChannelStatus = cs
|
|
}
|
|
return deps
|
|
}
|
|
|
|
// serveStateStore registers the StateStore gRPC service and serves it until
|
|
// ctx ends, draining in-flight calls before returning (mirroring serveGateway
|
|
// in gateway.go, minus the gateway's session-store argument).
|
|
func serveStateStore(ctx context.Context, listener net.Listener, deps staterpc.Deps, opts []grpc.ServerOption) error {
|
|
server := grpc.NewServer(opts...)
|
|
staterpc.RegisterServer(server, deps)
|
|
serveErr := make(chan error, 1)
|
|
go func() { serveErr <- server.Serve(listener) }()
|
|
select {
|
|
case <-ctx.Done():
|
|
timer := time.AfterFunc(10*time.Second, server.Stop)
|
|
server.GracefulStop()
|
|
timer.Stop()
|
|
return nil
|
|
case err := <-serveErr:
|
|
return err
|
|
}
|
|
}
|
|
|
|
// startStateStoreReadiness starts a minimal HTTP readiness surface on
|
|
// readyAddr: GET /healthz and /health answer 200 as a liveness probe (the
|
|
// process is up), while GET /health/detailed runs the state_db readiness probe
|
|
// and answers 503 when the store is degraded. It is the standalone process's
|
|
// counterpart to the daemon's /healthz + /health/detailed (internal/webui).
|
|
func (b *boot) startStateStoreReadiness(ctx context.Context, readyAddr string) error {
|
|
registry := health.NewRegistry(readiness.NewStoreProbe(b.st))
|
|
mux := http.NewServeMux()
|
|
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) {
|
|
w.WriteHeader(http.StatusOK)
|
|
_, _ = w.Write([]byte("ok"))
|
|
})
|
|
mux.HandleFunc("GET /health", func(w http.ResponseWriter, _ *http.Request) {
|
|
w.WriteHeader(http.StatusOK)
|
|
_, _ = w.Write([]byte("ok"))
|
|
})
|
|
mux.HandleFunc("GET /health/detailed", func(w http.ResponseWriter, r *http.Request) {
|
|
report := registry.Run(r.Context())
|
|
w.Header().Set("Content-Type", "application/json")
|
|
if report.Status != health.StatusOK {
|
|
w.WriteHeader(http.StatusServiceUnavailable)
|
|
}
|
|
_ = json.NewEncoder(w).Encode(report)
|
|
})
|
|
return b.serveHealth(ctx, readyAddr, mux, "state store readiness")
|
|
}
|
|
|
|
// startOptionalSurfaces starts the HTTP surfaces this process serves beside
|
|
// the gRPC contract, each enabled only by its own flag.
|
|
//
|
|
// They are gathered here rather than branched inline because RunStateStore is
|
|
// at its complexity budget: a surface that is off by default belongs to its
|
|
// own decision, not to the boot sequence that triggers it -- the same reason
|
|
// reportUnseededResources is a method.
|
|
func (b *boot) startOptionalSurfaces(ctx context.Context, options StateStoreOptions) error {
|
|
if options.ReadyAddr != "" {
|
|
if err := b.startStateStoreReadiness(ctx, options.ReadyAddr); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
if options.AdminAddr != "" {
|
|
if err := b.startStateAdmin(ctx, options.AdminAddr); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// startStateAdmin starts the read-only operator dashboard on adminAddr.
|
|
//
|
|
// It is started here, inside the process that already holds the database's
|
|
// ownership claim (openStateStore above), because that claim is what makes a
|
|
// second reader safe to co-tenant: a separate admin process would be a second
|
|
// opener of a single-owner file. The surface exposes view collections only and
|
|
// refuses the routes that could write, so the StateStoreService contract this
|
|
// process serves stays the only writer of task state.
|
|
func (b *boot) startStateAdmin(ctx context.Context, adminAddr string) error {
|
|
admin, err := stateadmin.New(stateadmin.Config{
|
|
DBPath: taskDBPath(b.cfg.DBPath),
|
|
DataDir: filepath.Join(filepath.Dir(taskDBPath(b.cfg.DBPath)), "admin"),
|
|
})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
b.addCleanup(func() {
|
|
if err := admin.Close(); err != nil {
|
|
b.log.Error("close state admin", "err", err)
|
|
}
|
|
})
|
|
handler, err := admin.Handler()
|
|
if err != nil {
|
|
return fmt.Errorf("build state admin handler: %w", err)
|
|
}
|
|
return b.serveHealth(ctx, adminAddr, handler, "state store admin")
|
|
}
|
|
|
|
// stateStoreServerOpts applies the transport security boundary (§9): a
|
|
// loopback listener is served insecure with no token; any non-loopback
|
|
// address requires a bearer token, else the process fails closed. It cannot
|
|
// enforce TLS/mTLS (an operator decision), so it narrows the non-loopback
|
|
// path to token auth -- the same confinement philosophy as the gateway's
|
|
// loopback-only --listen rule.
|
|
//
|
|
// The keepalive enforcement policy is not part of that boundary and is
|
|
// installed on both listeners: a loopback State Store serves the same dialers
|
|
// as a remote one (staterpc.Dial installs the client keepalive on every target,
|
|
// loopback included), and grpc's default policy would answer their idle
|
|
// watches with GOAWAY too_many_pings. See staterpc.ServerKeepaliveOption.
|
|
func stateStoreServerOpts(listen, token string, grants *staterpc.TaskGrants) (opts []grpc.ServerOption, loopback bool, err error) {
|
|
loopback, err = staterpc.TargetIsLoopback(listen)
|
|
if err != nil {
|
|
return nil, false, err
|
|
}
|
|
keepalive := staterpc.ServerKeepaliveOption()
|
|
if loopback {
|
|
return []grpc.ServerOption{keepalive}, true, nil
|
|
}
|
|
if token == "" {
|
|
return nil, false, fmt.Errorf(
|
|
"state store listen address %q is non-loopback; non-loopback exposure requires a bearer token (--token / [services.state].target_token) or TLS, mirroring the gateway's --listen confinement (docs/prds/state-store-contract.md §9)",
|
|
listen,
|
|
)
|
|
}
|
|
// grants.UnaryInterceptor/StreamInterceptor separate the daemon's own
|
|
// administrative token (full access) from a container's task-scoped
|
|
// grant (Update/Transition/InsertEvent on its own task ID only), rather
|
|
// than the single all-or-nothing token check this replaced.
|
|
return []grpc.ServerOption{
|
|
keepalive,
|
|
grpc.ChainUnaryInterceptor(grants.UnaryInterceptor(token)),
|
|
grpc.ChainStreamInterceptor(grants.StreamInterceptor(token)),
|
|
}, false, nil
|
|
}
|