feat(state-store): stand up archie-state-store binary and own archie.db (archie-core-8cda.4.3) (#771)

This commit is contained in:
sam authored and GitHub committed 2026-09-07 03:41:32 +10:00
1 parent 2b102b04a2
commit e6a2e5b3b4
8 files changed
+499 -9

No files matched your search

+2
View File
@@ -161,10 +161,12 @@ tasks:
generates:
- "{{.BIN_DIR}}/archied"
- "{{.BIN_DIR}}/archie-gateway"
- "{{.BIN_DIR}}/archie-state-store"
- "{{.BIN_DIR}}/archie-agent"
cmds:
- go build -ldflags "-X github.com/samcharles93/archie-core/internal/app/archied.gatewayVersion={{.GATEWAY_VERSION}} -X github.com/samcharles93/archie-core/internal/app/archied.runtimeVersion={{.RUNTIME_VERSION}} -X github.com/samcharles93/archie-core/internal/installtype.buildType=binary" -o {{.BIN_DIR}}/archied ./cmd/archied
- go build -ldflags "-X github.com/samcharles93/archie-core/internal/app/archied.gatewayVersion={{.GATEWAY_VERSION}} -X github.com/samcharles93/archie-core/internal/installtype.buildType=binary" -o {{.BIN_DIR}}/archie-gateway ./cmd/archie-gateway
- go build -o {{.BIN_DIR}}/archie-state-store ./cmd/archie-state-store
- go build -ldflags "-X github.com/samcharles93/archie-core/internal/app/agentworker.version={{.RUNTIME_VERSION}} -X github.com/samcharles93/archie-core/internal/installtype.buildType=binary" -o {{.BIN_DIR}}/archie-agent ./cmd/archie-agent
test:
+45
View File
@@ -0,0 +1,45 @@
// Command archie-state-store hosts the State Store's gRPC contract and owns
// the single archie.db SQLite file. It is the .4.3 companion to the daemon's
// in-process State Store server: the same StateStoreService .4.2 serves, but
// extracted into its own process with its own store lifecycle.
//
// The gateway's session SQLite is owned by the separate archie-gateway process
// and is untouched here. See docs/prds/state-store-contract.md (rev. 2c) §5,
// §9 and §11.
package main
import (
"context"
"flag"
"fmt"
"os"
"os/signal"
"path/filepath"
"syscall"
"github.com/samcharles93/archie-core/internal/app/archied"
)
func main() { os.Exit(run()) }
func run() int {
base, err := os.UserConfigDir()
if err != nil {
fmt.Fprintln(os.Stderr, err)
return 1
}
var options archied.StateStoreOptions
flag.StringVar(&options.Config, "config", filepath.Join(base, "archie", "config.toml"), "configuration file or directory")
flag.StringVar(&options.Overlay, "config-overlay", "", "configuration overlay file or directory")
flag.StringVar(&options.Listen, "listen", "127.0.0.1:9090", "state store gRPC listen address")
flag.StringVar(&options.Token, "token", "", "bearer token required for a non-loopback listener (defaults to [services.state].target_token)")
flag.StringVar(&options.ReadyAddr, "ready-addr", "", "optional readiness HTTP listen address (e.g. 127.0.0.1:9091)")
flag.Parse()
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
if err := archied.RunStateStore(ctx, options); err != nil {
fmt.Fprintln(os.Stderr, err)
return 1
}
return 0
}
+6 -2
View File
@@ -268,8 +268,12 @@ gate_max_failures = 5
# [services.state]
# target = "" # empty (default) = local *store.Store adapter.
# # This surface is consumed by the upcoming
# # standalone archie-state-store binary (.4.3); the
# target_token = "..." # bearer token for a NON-loopback listener. The standalone
# # archie-state-store server validates this; a loopback
# # bind (127.0.0.1/::1/localhost) needs no token. Non-loopback
# # without a token fails closed (docs/prds/state-store-contract.md §9).
# # This surface is consumed by the standalone
# # archie-state-store binary (.4.3); the
# # daemon does not read it yet -- it still serves the
# # State Store gRPC service in-process today.
+8
View File
@@ -34,6 +34,7 @@ Edit API keys in `~/.config/archie/env` or directly in `config.toml`, then launc
```bash
archie-gateway -config ~/.config/archie/config.toml -listen 127.0.0.1:8585 &
archie-state-store -config ~/.config/archie/config.toml -listen 127.0.0.1:9090 &
archied -config ~/.config/archie/config.toml
# or via systemd:
systemctl --user start archied
@@ -42,3 +43,10 @@ systemctl --user start archied
The templates use the extracted Gateway Service by default. Start
`archie-gateway` before `archied`; it owns the conversation SQLite file and
serves the `ChatContract` gRPC API on the configured target.
The State Store service (`archie-state-store`) is `.4.3`: it owns the single
`archie.db` task SQLite file and serves the `StateStore` gRPC contract. It is
not yet consumed by the daemon (which still serves the store in-process), so
running it now is only needed once the daemon points at it — the loopback
bind above is the safe default, and a non-loopback bind requires a bearer
token (`--token` / `STATE_STORE_TOKEN` / `[services.state].target_token`).
+23
View File
@@ -43,6 +43,29 @@ RestartSec=5s
WantedBy=default.target
```
Create the State Store unit beside it. It owns the single `archie.db` SQLite
file and serves the `StateStore` gRPC contract. It is not yet consumed by the
daemon during the `.4.2`/`.4.3` split (the daemon still serves in-process), so
the loopback bind with no token is the correct default; a non-loopback bind
requires a bearer token via `--token`/`STATE_STORE_TOKEN` or
`[services.state].target_token` and fails closed without one:
```ini
[Unit]
Description=Archie State Store Service
After=network.target
[Service]
Type=simple
ExecStart=%h/.local/bin/archie-state-store -config %h/.config/archie/config.toml -listen 127.0.0.1:9090 -ready-addr 127.0.0.1:9091
EnvironmentFile=-%h/.config/archie/env
Restart=on-failure
RestartSec=5s
[Install]
WantedBy=default.target
```
---
## 2. Enabling User Linger (`loginctl`)
+257
View File
@@ -0,0 +1,257 @@
// 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"
"crypto/subtle"
"encoding/json"
"fmt"
"net"
"net/http"
"strings"
"time"
"google.golang.org/grpc"
"github.com/samcharles93/archie-core/internal/domain/health"
"github.com/samcharles93/archie-core/internal/infrastructure/readiness"
"github.com/samcharles93/archie-core/internal/infrastructure/staterpc"
"github.com/samcharles93/archie-core/internal/store"
)
// 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
}
// 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, false); err != nil {
return err
}
b.log = b.log.With("component", "state-store")
if err := b.openStateStore(ctx); err != nil {
return err
}
token := options.Token
if token == "" {
token = b.cfg.Services.State.TargetToken
}
opts, loopback, err := stateStoreServerOpts(options.Listen, token)
if err != nil {
return err
}
listener, err := (&net.ListenConfig{}).Listen(ctx, "tcp", options.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 options.ReadyAddr != "" {
if err := b.startStateStoreReadiness(ctx, options.ReadyAddr); err != nil {
return err
}
}
return serveStateStore(ctx, listener, b.stateStoreDeps(), opts)
}
// 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
}
st, err := openProductionTaskStore(ctx, taskDBPath(cfg.DBPath), store.WithBindingCipher(bindingCipher))
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 store.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() staterpc.Deps {
deps := staterpc.Deps{Tasks: b.st, Log: b.log}
if cs, ok := b.st.(store.CaptureStore); ok {
deps.Captures = cs
}
if ms, ok := b.st.(store.MappingStore); ok {
deps.Mappings = ms
}
if bs, ok := b.st.(store.BindingStore); ok {
deps.Bindings = bs
}
if bd, ok := b.st.(store.BindingDispatcher); ok {
deps.BindingDispatcher = bd
}
if btc, ok := b.st.(store.BindingTaskCreator); ok {
deps.BindingTaskCreator = btc
}
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)
})
listener, err := (&net.ListenConfig{}).Listen(ctx, "tcp", readyAddr)
if err != nil {
return fmt.Errorf("listen for state store readiness: %w", err)
}
srv := &http.Server{Handler: mux, ReadHeaderTimeout: 5 * time.Second}
go func() {
if err := srv.Serve(listener); err != nil && err != http.ErrServerClosed {
b.log.Error("state store readiness server stopped", "err", err)
}
}()
b.addCleanup(func() {
shutdownCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 2*time.Second)
defer cancel()
_ = srv.Shutdown(shutdownCtx)
})
b.log.Info("state store readiness listening", "addr", "http://"+listener.Addr().String())
return nil
}
// 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.
func stateStoreServerOpts(listen, token string) (opts []grpc.ServerOption, loopback bool, err error) {
loopback, err = stateStoreListenIsLoopback(listen)
if err != nil {
return nil, false, err
}
if loopback {
return nil, 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,
)
}
return []grpc.ServerOption{grpc.ChainUnaryInterceptor(staterpc.UnaryTokenInterceptor(constantTimeTokenValidator(token)))}, false, nil
}
// stateStoreListenIsLoopback reports whether listen's host is a loopback
// address. Both literal loopback IPs (127.0.0.1, ::1) and the "localhost"
// hostname count; everything else (including the wildcard 0.0.0.0 and DNS
// names) is treated as network-reachable and therefore non-loopback.
func stateStoreListenIsLoopback(listen string) (bool, error) {
host, _, err := net.SplitHostPort(listen)
if err != nil {
return false, fmt.Errorf("state store listen address must be host:port: %w", err)
}
if strings.EqualFold(host, "localhost") {
return true, nil
}
ip := net.ParseIP(host)
if ip == nil {
return false, nil
}
return ip.IsLoopback(), nil
}
// constantTimeTokenValidator returns a staterpc.TokenValidator that accepts
// exactly the configured token, compared in constant time so a timing side
// channel cannot leak how many bytes matched (mirrors the daemon's
// StateStoreTokens.Validate).
func constantTimeTokenValidator(token string) staterpc.TokenValidator {
return func(candidate string) bool {
return subtle.ConstantTimeCompare([]byte(token), []byte(candidate)) == 1
}
}
+145
View File
@@ -0,0 +1,145 @@
package archied
import (
"context"
"net"
"path/filepath"
"testing"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
pb "github.com/samcharles93/archie-core/internal/contracts/state/v1"
"github.com/samcharles93/archie-core/internal/store"
)
func TestStateStoreListenIsLoopback(t *testing.T) {
tests := []struct {
name string
listen string
want bool
}{
{"loopback ipv4", "127.0.0.1:9090", true},
{"loopback ipv6", "[::1]:9090", true},
{"localhost hostname", "localhost:9090", true},
{"localhost uppercase", "LOCALHOST:9090", true},
{"wildcard", "0.0.0.0:9090", false},
{"private ip", "192.168.1.10:9090", false},
{"dns name", "store.example.com:9090", false},
{"empty host", ":9090", false},
{"malformed", "127.0.0.1", false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := stateStoreListenIsLoopback(tt.listen)
if tt.name == "malformed" {
if err == nil {
t.Fatalf("stateStoreListenIsLoopback(%q) = (%v, nil), want error", tt.listen, got)
}
return
}
if err != nil {
t.Fatalf("stateStoreListenIsLoopback(%q): %v", tt.listen, err)
}
if got != tt.want {
t.Fatalf("stateStoreListenIsLoopback(%q) = %v, want %v", tt.listen, got, tt.want)
}
})
}
}
func TestStateStoreServerOptsLoopbackIsInsecure(t *testing.T) {
opts, loopback, err := stateStoreServerOpts("127.0.0.1:9090", "")
if err != nil {
t.Fatalf("stateStoreServerOpts(loopback, no token) error: %v", err)
}
if !loopback {
t.Fatal("loopback listener should report loopback")
}
if len(opts) != 0 {
t.Fatalf("loopback listener should have no server opts, got %d", len(opts))
}
}
func TestStateStoreServerOptsNonLoopbackRequiresToken(t *testing.T) {
if _, _, err := stateStoreServerOpts("0.0.0.0:9090", ""); err == nil {
t.Fatal("non-loopback listener without a token should fail closed")
}
opts, loopback, err := stateStoreServerOpts("0.0.0.0:9090", "secret")
if err != nil {
t.Fatalf("non-loopback listener with a token error: %v", err)
}
if loopback {
t.Fatal("non-loopback listener should not report loopback")
}
if len(opts) != 1 {
t.Fatalf("non-loopback listener should install one server option (the token interceptor), got %d", len(opts))
}
}
func TestStateStoreServerOptsMalformedListen(t *testing.T) {
if _, _, err := stateStoreServerOpts("not-an-address", ""); err == nil {
t.Fatal("malformed listen address should error")
}
}
func TestConstantTimeTokenValidator(t *testing.T) {
validate := constantTimeTokenValidator("correct-token")
if !validate("correct-token") {
t.Fatal("validator should accept the configured token")
}
if validate("wrong-token") {
t.Fatal("validator should reject a different token")
}
if validate("") {
t.Fatal("validator should reject an empty token")
}
}
// TestServeStateStoreServesContract verifies the standalone composition's
// serveStateStore + stateStoreDeps wiring actually serves the StateStore gRPC
// contract over a real loopback listener: the same service .4.2 serves
// in-process, now extracted into its own process. A read-only StatusCounts
// call proves the service is registered and wired to the opened store.
func TestServeStateStoreServesContract(t *testing.T) {
dir := t.TempDir()
st, err := store.Open(t.Context(), filepath.Join(dir, "tasks.sqlite"))
if err != nil {
t.Fatalf("open temp store: %v", err)
}
defer st.Close()
b := newBootstrap()
b.st = st
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
listener, err := (&net.ListenConfig{}).Listen(ctx, "tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("listen: %v", err)
}
defer listener.Close()
serveCh := make(chan error, 1)
go func() { serveCh <- serveStateStore(ctx, listener, b.stateStoreDeps(), nil) }()
conn, err := grpc.NewClient("passthrough:///"+listener.Addr().String(), grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
t.Fatalf("dial: %v", err)
}
defer conn.Close()
client := pb.NewStateStoreServiceClient(conn)
if _, err := client.StatusCounts(t.Context(), &pb.StatusCountsRequest{}); err != nil {
t.Fatalf("StatusCounts over gRPC: %v", err)
}
cancel()
select {
case err := <-serveCh:
if err != nil {
t.Fatalf("serveStateStore returned: %v", err)
}
case <-t.Context().Done():
t.Fatal("serveStateStore did not return after cancel")
}
}
+13 -7
View File
@@ -5,17 +5,23 @@ type Services struct {
Gateway ServiceConnection `toml:"gateway" yaml:"gateway"`
// State selects the State Store contract adapter. Unlike Gateway, an
// empty Target means local (the *store.Store in-process adapter): the
// State Store service is not yet extracted into its own process. This
// is the ratified presence-based [services.state].target surface
// (docs/prds/state-store-contract.md §10), consumed by the upcoming
// standalone archie-state-store binary (.4.3) -- the daemon does not
// read it yet, so it remains dead configuration until that consumer
// lands. Setting Target would dial the gRPC StateStoreService.
// State Store service is not yet extracted into its own process. The
// standalone archie-state-store binary (.4.3) is the consumer of
// [services.state].target_token; the daemon does not read it yet, so
// it remains dead configuration until the daemon points at the
// extracted store. Setting Target would dial the gRPC StateStoreService.
State ServiceConnection `toml:"state" yaml:"state"`
}
// ServiceConnection is the archie-gateway process's gRPC address. It does not
// ServiceConnection is a contract adapter's gRPC address plus the bearer
// token a client presents when the target is non-loopback. It does not
// register services or start listeners. Changes require a daemon restart.
type ServiceConnection struct {
Target string `toml:"target" yaml:"target"`
// TargetToken is the bearer token a client (daemon or agent) presents
// when dialing a non-loopback service target, and the standalone
// archie-state-store server validates. Empty means no token, which is
// the loopback-only, daemon-only listener topology permitted without
// auth (docs/prds/state-store-contract.md §9).
TargetToken string `toml:"target_token" yaml:"target_token"`
}