Files
archie/internal/store/resources.go
T
sam c833081544 feat(postgres): port events/identities/status surfaces, fix shipped defects
CHECKPOINT -- the full State Store port is in progress; this lands the
compile-clean core so the review pass has a diff to work against. Remaining:
advisory-lock ownership, event-insert serialization, maintenance, and the
ported test battery.

Two corrections to behaviour that already shipped, not new features:
- UpdateTask wrote park_reason raw where SQLite applies clip(park_reason,
  4000); the PostgreSQL adapter now clips before binding (clip.go).
- tasks.review_cursor existed on the protobuf wire and in workflow.Task but
  not in the PostgreSQL schema; 0004 adds it as a NEW migration rather than
  amending 0001 because a dev database may already have applied 0001 and
  goose tracks version numbers, not checksums.

Also moves the control-plane Resource/ResourceWrite types and their sentinels
into storecontract so the postgres package can stop importing internal/store
(they stay aliased there for daemon callers).
2026-09-24 02:17:44 +10:00

128 lines
5.4 KiB
Go

package store
import (
"context"
"database/sql"
"errors"
"fmt"
"time"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
)
// Resource types and their sentinels moved to storecontract (the producer-owned
// contract) so the PostgreSQL implementation can reference them without linking
// this SQLite package. These aliases keep daemon-side callers (the control
// plane) and the in-package tests unchanged.
var (
ErrResourceNotFound = storecontract.ErrResourceNotFound
ErrResourceVersionConflict = storecontract.ErrResourceVersionConflict
)
type Resource = storecontract.Resource
type ResourceWrite = storecontract.ResourceWrite
const resourcesSchema = `
CREATE TABLE IF NOT EXISTS resources (
kind TEXT PRIMARY KEY, value BLOB NOT NULL, version INTEGER NOT NULL, updated_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS resource_history (
id INTEGER PRIMARY KEY AUTOINCREMENT, kind TEXT NOT NULL, value BLOB NOT NULL,
version INTEGER NOT NULL, actor TEXT NOT NULL, source TEXT NOT NULL,
request_id TEXT NOT NULL, expected_version INTEGER NOT NULL,
current_version INTEGER NOT NULL, at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_resource_history_kind_version ON resource_history(kind, version);
-- The request-ID idempotency key is per kind, not global: a resource write
-- replays only the same kind's prior write (resourceByRequest). A database
-- written before v4 carries the old global UNIQUE as a column constraint;
-- migrateResourceHistoryToPerKindRequestIDs rebuilds it to this shape.
CREATE UNIQUE INDEX IF NOT EXISTS idx_resource_history_kind_request ON resource_history(kind, request_id);
`
func (s *Store) Resource(ctx context.Context, kind string) (Resource, error) {
var r Resource
err := s.db.QueryRowContext(ctx, `SELECT kind,value,version,updated_at FROM resources WHERE kind=?`, kind).
Scan(&r.Kind, &r.Value, &r.Version, sqliteTime{&r.At})
if errors.Is(err, sql.ErrNoRows) {
return Resource{}, ErrResourceNotFound
}
return r, err
}
// ResourceHistory returns kind's revisions newest first, each carrying the
// audit record written with it. limit caps the rows; zero or less returns
// every revision. An unknown kind has no history, which is not an error.
func (s *Store) ResourceHistory(ctx context.Context, kind string, limit int) ([]Resource, error) {
if limit <= 0 {
limit = -1
}
rows, err := s.db.QueryContext(ctx, `SELECT kind,value,version,actor,source,request_id,expected_version,current_version,at FROM resource_history WHERE kind=? ORDER BY version DESC LIMIT ?`, kind, limit)
if err != nil {
return nil, err
}
defer func() { _ = rows.Close() }()
var history []Resource
for rows.Next() {
var r Resource
if err := rows.Scan(&r.Kind, &r.Value, &r.Version, &r.Actor, &r.Source, &r.RequestID, &r.ExpectedVersion, &r.CurrentVersion, sqliteTime{&r.At}); err != nil {
return nil, err
}
history = append(history, r)
}
return history, rows.Err()
}
func (s *Store) PutResource(ctx context.Context, w ResourceWrite) (_ Resource, retErr error) {
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return Resource{}, err
}
defer func() { _ = tx.Rollback() }()
if existing, ok, err := resourceByRequest(ctx, tx, w.Kind, w.RequestID); err != nil {
return Resource{}, err
} else if ok {
return existing, nil
}
var current int64
err = tx.QueryRowContext(ctx, `SELECT version FROM resources WHERE kind=?`, w.Kind).Scan(&current)
if err != nil && !errors.Is(err, sql.ErrNoRows) {
return Resource{}, err
}
if current != w.ExpectedVersion {
return Resource{}, fmt.Errorf("%w: expected %d, current %d", ErrResourceVersionConflict, w.ExpectedVersion, current)
}
if w.At.IsZero() {
w.At = time.Now().UTC()
}
next := current + 1
at := w.At.UTC().Format(time.RFC3339Nano)
if _, err := tx.ExecContext(ctx, `INSERT INTO resources(kind,value,version,updated_at) VALUES(?,?,?,?) ON CONFLICT(kind) DO UPDATE SET value=excluded.value,version=excluded.version,updated_at=excluded.updated_at`, w.Kind, w.Value, next, at); err != nil {
return Resource{}, err
}
if _, err := tx.ExecContext(ctx, `INSERT INTO resource_history(kind,value,version,actor,source,request_id,expected_version,current_version,at) VALUES(?,?,?,?,?,?,?,?,?)`, w.Kind, w.Value, next, w.Actor, w.Source, w.RequestID, w.ExpectedVersion, current, at); err != nil {
return Resource{}, err
}
if err := tx.Commit(); err != nil {
return Resource{}, err
}
return Resource{Kind: w.Kind, Value: append([]byte(nil), w.Value...), Version: next, Actor: w.Actor, Source: w.Source, RequestID: w.RequestID, ExpectedVersion: w.ExpectedVersion, CurrentVersion: current, At: w.At.UTC()}, nil
}
// resourceByRequest replays one prior write by its request ID, so a retried
// replace is idempotent instead of a second revision. The key is (kind,
// request ID), not the request ID alone: the API is per kind, so an ID reused
// across kinds must write the new kind rather than silently replay the first
// kind's resource (archie-core-fcvd).
func resourceByRequest(ctx context.Context, tx *sql.Tx, kind, requestID string) (Resource, bool, error) {
var r Resource
err := tx.QueryRowContext(ctx, `SELECT kind,value,version,actor,source,request_id,expected_version,current_version,at FROM resource_history WHERE kind=? AND request_id=?`, kind, requestID).
Scan(&r.Kind, &r.Value, &r.Version, &r.Actor, &r.Source, &r.RequestID, &r.ExpectedVersion, &r.CurrentVersion, sqliteTime{&r.At})
if errors.Is(err, sql.ErrNoRows) {
return Resource{}, false, nil
}
return r, err == nil, err
}