store

package
v0.2.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 26, 2026 License: Apache-2.0 Imports: 10 Imported by: 0

README

haistack-store (pkg/store)

Storage contract layer for the haistack monorepo.

What it does

Think of pkg/types as “how we represent a FHIR resource in memory.”
pkg/store is “how we save, find, and track changes to those resources — without caring whether the database is SQLite, Postgres, or something else.”

This package does not talk to a database directly. It defines interfaces (contracts) such as:

  • save, read, update, and delete a resource
  • keep version history
  • index data for search
  • record change events for sync
  • store files, audit logs, background jobs, and more
  • store canonical terminology resources and their disposable lookup projections

Actual database code lives in separate packages (pkg/sqlite, pkg/postgres). Application code depends on store.ResourceStore, not on a specific backend. That makes it easy to swap implementations or test with in-memory fakes.

How it fits in the ecosystem

pkg/store is the persistence seam of haistack. Higher layers depend on interfaces defined here; database packages implement them. No SQL, no HTTP, no FHIR business rules — only contracts and shared record types built on pkg/types.ResourceEnvelope.

flowchart LR
  subgraph upstream["Upstream consumers"]
    CORE["pkg/core"]
    RUN["pkg/runtime"]
    JOBS["pkg/jobs"]
    AUDIT["pkg/audit"]
    SYNC["pkg/sync"]
    SRCH["pkg/search"]
    TERM["pkg/terminology"]
  end

  subgraph store_pkg["pkg/store"]
    IF["Interfaces & record types"]
    WS["WriteSession / WriteSessionProvider"]
  end

  subgraph downstream["Downstream adapters"]
    SQLITE["pkg/sqlite"]
    PG["pkg/postgres"]
    MEM["tests / mem fakes"]
  end

  CORE --> IF
  RUN --> IF
  JOBS --> IF
  AUDIT --> IF
  SYNC --> IF
  SRCH --> IF
  TERM --> IF
  IF --> WS
  WS --> SQLITE
  WS --> PG
  IF --> MEM
Direction Component Role relative to pkg/store
Upstream pkg/types Defines ResourceEnvelope — the payload every resource store method accepts
Upstream pkg/core Orchestrates multi-store writes through WriteSession; assigns version policy upstream of SQLite
Upstream pkg/runtime Opens backends and exposes store accessors to services
Upstream pkg/search Produces SearchIndexEntry values consumed by SearchStore.Index
Upstream pkg/sync Reads EventStore, updates CursorStore, applies InboxStore idempotency
Upstream pkg/jobs Uses JobStore for durable queue state
Upstream pkg/audit Shapes records appended to AuditStore
Downstream pkg/sqlite Embedded implementation: resource, history, outbox, search, jobs, audit, …
Downstream pkg/postgres Tenant-scoped server implementation with global event log and ID registry
Downstream Test fakes In-memory implementations in tests (pkg/store/store_test.go, pkg/testkit)

Keeping this boundary stable lets you run the same core and runtime code against SQLite on a device and Postgres in the cloud.

Usage modes

Application reads and writes via ResourceStore

When: You need the latest FHIR resource for a type/id pair, or a simple CRUD path in a tool that already manages versioning elsewhere.

How: Obtain store.ResourceStore from a backend (db.ResourceStore() or tdb.ResourceStore()). Use Create, Read, Update, Delete, and Exists. Prefer pkg/core for product writes so history and events stay consistent.

Atomic multi-table writes (WriteSession)

When: A single logical change must touch current state, history, search index, and outbox/event log together.

How: Call WriteSessionProvider.BeginWrite(ctx), use session-scoped stores, then Commit or Rollback. Both sqlite.DB and postgres.TenantDB implement WriteSessionProvider.

session, err := db.BeginWrite(ctx)
if err != nil { /* … */ }
defer func() { _ = session.Rollback(ctx) }()

if err := session.ResourceStore().Create(ctx, envelope); err != nil { return err }
if err := session.HistoryStore().AppendVersion(ctx, version); err != nil { return err }
if err := session.EventStore().Append(ctx, event); err != nil { return err }
return session.Commit(ctx)
Sync replay and cursor checkpoints

When: A worker replays local or global changes since a sequence number and must resume safely after restarts.

How: Read with EventStore.ReadSince(ctx, afterSequence, limit), process events, then persist progress with CursorStore.UpsertCursor. Cursors are independent of events so multiple consumers can track different positions.

events, err := eventStore.ReadSince(ctx, lastSeq, 100)
// … apply or forward …
_ = cursorStore.UpsertCursor(ctx, store.Cursor{
    Name:     "edge-sync",
    Position: fmt.Sprintf("%d", events[len(events)-1].Sequence),
    UpdatedAt: time.Now(),
})
Conflict and ID registry coordination

When: Server-side sync detects version mismatches or needs authoritative ID registration per tenant.

How: Append ConflictStore records on conflict outcomes; use IDRegistryStore.Check, Reserve, and Register during server write pipelines (postgres.ApplyWrite integrates registry on accepted creates). Reconciliation policy stays in core/sync — store only persists facts.

Operational and compliance storage

When: Background reindex jobs, security audit trails, analytics events, or module registration metadata must survive process restarts.

How: Use JobStore, AuditStore, AnalyticsStore, and ModuleStore accessors from the backend. Scheduling semantics live in pkg/jobs; audit field shaping lives in pkg/audit.

Terminology and definitions (server)

When: Canonical CodeSystem/ValueSet records and compiled lookup projections are part of tenant data.

How: Use TerminologyStore on backends that implement it (Postgres). TerminologyWriteSession optionally joins terminology projections to the same transaction as a resource write.

Testing with store contracts only

When: Unit tests for core, search, or sync logic without spinning up SQLite/Postgres.

How: Implement minimal fakes satisfying the interfaces you need, or use patterns from pkg/testkit/storetest. Depend on store.ResourceStore, not concrete DB types, so tests stay portable.

What it does not do

  • Parse FHIR JSON — use pkg/types
  • Assign version numbers or enforce business rules — use pkg/core or your app layer
  • Parse FHIR search queries — use pkg/search
  • Run SQL or manage schemas — use pkg/sqlite or pkg/postgres

pkg/store is the middle layer: it defines what can be persisted and how to call it. Backends decide where data actually goes.

When to use it

  • When writing or reading FHIR resources through a stable API
  • When you need history, search indexes, or change events alongside current state
  • When building sync, audit, or background-job features on top of shared storage contracts
  • When you want tests to use fake stores instead of a real database

Mental model

When a Patient is saved, several things usually happen:

  1. Current state — store the latest Patient (ResourceStore)
  2. History — remember this was version 3 (HistoryStore)
  3. Search index — index "family=Doe" so search works (SearchStore)
  4. Change event — emit “Patient/pat-1 was updated” for sync (EventStore)

pkg/store defines separate interfaces for each of those jobs, plus helpers for sync cursors, conflicts, files, audit trails, and jobs.

Usage

Open a backend and get a store:

import (
    "github.com/degoke/haistack/pkg/sqlite"
)

db, err := sqlite.Open(sqlite.Options{Path: "data.db"})
resources := db.ResourceStore() // satisfies store.ResourceStore

On a server you might use pkg/postgres instead — same interfaces, different backend.

Save and read a resource:

// envelope comes from pkg/types
err := resources.Create(ctx, envelope)

patient, err := resources.Read(ctx, "Patient", "pat-1")

Compose a full write (typical pattern):

Higher-level code (or a WriteSession) often does all of this together:

resources.Create(ctx, envelope)

history.AppendVersion(ctx, store.ResourceVersion{
    ResourceType: envelope.ResourceType,
    ID:           envelope.ID,
    VersionID:    envelope.VersionID,
    Action:       store.VersionActionCreate,
    Timestamp:    time.Now(),
    Resource:     envelope,
    Hash:         envelope.Hash,
})

events.Append(ctx, store.ResourceEvent{
    ResourceType: envelope.ResourceType,
    ID:           envelope.ID,
    VersionID:    envelope.VersionID,
    Action:       store.EventActionCreate,
    Timestamp:    time.Now(),
    Hash:         envelope.Hash,
})

search.Index(ctx, store.SearchIndexEntry{
    ResourceType: "Patient",
    ID:           "pat-1",
    Fields:       map[string]string{"family": "Doe"},
})

On delete: remove from ResourceStore, append a tombstone to history, emit a delete event, and remove from the search index.

Read a specific history version:

ver, err := history.GetVersion(ctx, "Patient", "pat-1", "uuid-version-id")
if ver.Deleted {
    // tombstone — no Resource snapshot
}

Simple search index lookup (not FHIR search parsing):

ids, err := search.Lookup(ctx, "string.family", "Doe")

Sync and background work:

  • EventStore + CursorStore — replay changes and resume where you left off
  • ConflictStore — record “local vs remote version mismatch”
  • JobStore — queue work like reindexing
  • AuditStore — record who did what for compliance

Interface overview

Interface Purpose
ResourceStore Latest copy of each resource
HistoryStore All past versions
SearchStore Fast lookup data (not full search parsing)
EventStore Change feed for sync and replay
CursorStore “Where did the sync worker stop?”
ConflictStore Record sync/write conflicts
BinaryStore Small inline binary payloads
BlobStore Larger blobs or external storage references
MaterializedViewStore Read-optimized projections
ReportingTableStore Tenant-scoped analytics reporting table snapshots
AnalyticsStore Operational/product analytics events
AuditStore Security/compliance audit trail
JobStore Background task queue
ModuleStore Registered plugins/extensions
IDRegistryStore Authoritative ID registration
WriteSessionProvider Atomic write across resource, history, search, and events
TerminologyStore Canonical CodeSystem/ValueSet records and compiled projections

Where it fits

Layer Role
types Canonical JSON and ResourceEnvelope
store Persistence contracts (this package)
sqlite Embedded local implementation
postgres Tenant-scoped edge/cloud implementation
core Business rules and write pipelines
search FHIR search parsing (produces index entries for SearchStore)

Limits

  • Contracts and record types only — no database adapters in this package
  • No FHIR search parsing, version assignment policy, or conflict reconciliation
  • No in-memory production adapter yet (pkg/store/memory is future work)
  • BinaryStore, BlobStore, and operational stores are defined here; not every backend implements every interface

Documentation

Overview

Package store defines haistack-store, the storage contract layer for the haistack runtime.

haistack-store gives every downstream package one stable set of interfaces for resource persistence, history, indexing, events, transactions, binaries, cursors, conflicts, and operational storage without coupling the rest of the system to SQLite, Postgres, Redis, OpenSearch, or any other backend. Implementations live in separate packages (for example pkg/sqlite for embedded local storage and pkg/postgres for tenant-scoped edge/cloud storage).

This package defines contracts and shared record types only:

  • It depends on pkg/types for types.ResourceEnvelope and nothing else for FHIR shape.
  • It does not own FHIR business rules, version assignment policy, search parsing, FHIRPath, HTTP concerns, scheduling policy, or reconciliation logic.
  • Canonical FHIR JSON stays in types.ResourceEnvelope.JSON; no alternate canonicalization rules are defined here.

Design principles

Current-state vs history:

  • ResourceStore holds the latest version of each resource (CRUD on current state).
  • HistoryStore holds immutable version history; delete is current-state removal plus a historical tombstone (ResourceVersion with Action=delete and Deleted=true).
  • VersionID assignment is caller-owned; stores persist what they are given.

Index vs search:

  • SearchStore is index-oriented persistence only (tokens, fields, prepared lookups).
  • Raw FHIR search expressions are parsed outside this package (for example pkg/search).

Events vs cursors:

  • EventStore is append-only local change events for replay, sync, and projections.
  • CursorStore persists consumer checkpoints independently so workers can resume safely.
  • InboxStore records applied remote operation ids for idempotent sync replay.

Transactions:

  • Transactor exposes optional low-level BeginTx/Commit/Rollback for backends that support SQL-style transactions.
  • WriteSessionProvider coordinates a higher-level atomic write across ResourceStore, HistoryStore, SearchStore, and EventStore in one session.
  • Not every adapter must implement transactional scopes; in-memory or read-only backends may omit them.

Policy stays upstream:

  • ConflictStore records conflicts; reconciliation rules live in pkg/core or sync layers.
  • JobStore persists job state; retry, scheduling, and worker execution live in pkg/jobs (and package-specific workers such as search reindex / sync jobs).
  • ModuleStore registers module metadata; activation and code loading live elsewhere.
  • AnalyticsStore and AuditStore append records; shared event shaping and emit helpers live in pkg/audit; reporting and compliance workflows live elsewhere.

Core resource contracts

ResourceStore — current-state CRUD for FHIR resources:

  • Create(ctx, res) inserts a new resource envelope.
  • Read(ctx, resourceType, id) returns the latest envelope or an error when absent.
  • Update(ctx, res) replaces the current envelope for the given type and id.
  • Delete(ctx, resourceType, id) removes the current record (history tombstones use HistoryStore separately).
  • Exists(ctx, resourceType, id) reports whether a current record is present.

HistoryStore — immutable lifecycle history:

  • AppendVersion(ctx, version) appends one ResourceVersion entry.
  • GetHistory(ctx, resourceType, id) returns ordered history for one resource.
  • GetVersion(ctx, resourceType, id, versionID) returns one history entry or an error containing "resource not found".

ResourceVersion fields:

  • ResourceType, ID, VersionID — resource identity for this history entry.
  • Action — VersionActionCreate, VersionActionUpdate, or VersionActionDelete.
  • Timestamp — when the version was recorded.
  • Resource — optional envelope snapshot (typically omitted for delete tombstones).
  • Hash — content digest copied from the envelope or supplied by the caller.
  • Deleted — true for delete tombstone entries (Action should be VersionActionDelete).

SearchStore — search-index persistence:

  • Index(ctx, entry) upserts SearchIndexEntry metadata or tokens for one resource.
  • RemoveIndex(ctx, resourceType, id) drops all indexed data for that resource.
  • Lookup(ctx, key, value) returns candidate resource IDs for a simple key/value pair.
  • QueryPrepared(ctx, query, args) runs a backend-specific prepared lookup plan (PreparedQuery.Name identifies the plan; args carry bound parameters).

EventStore — append-only local change events:

  • Append(ctx, event) stores a ResourceEvent and returns it with Sequence assigned when the caller left Sequence unset.
  • ReadSince(ctx, afterSequence, limit) reads events after a checkpoint for replay or sync.

ResourceEvent fields mirror history at the change-notification layer: Sequence, ResourceType, ID, VersionID, Action (EventActionCreate/Update/Delete), Timestamp, and Hash.

Sync and coordination contracts

CursorStore — named consumer checkpoints:

  • GetCursor(ctx, name) reads one Cursor (Position may be empty for a fresh consumer).
  • UpsertCursor(ctx, cursor) creates or replaces a checkpoint.
  • DeleteCursor(ctx, name) removes a checkpoint.

ConflictStore — first-class conflict records:

  • Append(ctx, record) stores a ConflictRecord.
  • List(ctx, resourceType, resourceID) returns conflicts for one resource.
  • Resolve(ctx, id, resolvedAt) marks a conflict resolved without deleting history.

IDRegistryStore — authoritative ID registration (typically tenant-scoped in adapters):

  • Check(ctx, resourceType, id) reports whether an id is already registered.
  • Reserve(ctx, resourceType, id) holds an id during an in-flight write.
  • Register(ctx, resourceType, id) commits a successful registration.

IDRegistryEntry and IDRegistryResult are supporting record types for registration outcomes; adapters may return them from higher-level write pipelines outside these interface methods.

Media contracts

BinaryStore — small inline binary payloads keyed by stable string:

  • Put(ctx, obj), Get(ctx, key), Delete(ctx, key).
  • BinaryObject carries Key, ContentType, Size, Hash, Data, and CreatedAt.

BlobStore — larger blobs or opaque backend references:

  • Put(ctx, obj), Get(ctx, key), Head(ctx, key), Delete(ctx, key).
  • BlobStoreWithStream.PutStream(ctx, key, contentType, size, r) uploads from an io.Reader without requiring the caller to materialize []byte. PutBlob and PutBlobFromPath use PutStream when available and otherwise fall back to Put.
  • BlobStoreWithOpen.Open(ctx, key) streams a payload. OpenBlob uses Open when available and otherwise wraps Get. Postgres BYTEA Open still materializes inline data, follows in-store Location pointers, and errors on a URI Location with no payload.
  • BlobObject adds Location for an opaque backend locator without exposing object-storage SDK types. Head returns metadata without payload bytes when the backend supports it.

BinaryStore is for compact payloads stored inline; BlobStore is for larger content or externally referenced storage. Put remains the small-payload API; streaming backends should implement BlobStoreWithStream so lakehouse parquet upload stays O(buffer).

Projection and operations contracts

MaterializedViewStore — persisted read-optimized projections:

  • Upsert(ctx, record), Get(ctx, viewName, key), Delete(ctx, viewName, key), ListKeys(ctx, viewName).
  • MaterializedViewRecord holds ViewName, Key, Payload, Version, and UpdatedAt.
  • Projection logic and refresh policy remain outside this package.

ReportingTableStore — tenant-scoped analytics reporting table snapshots:

  • Refresh(ctx, meta, rows) atomically replaces all rows for one view/version snapshot.
  • QueryRows(ctx, viewName, viewVersion) reads the stored row set in refresh order.
  • GetMeta(ctx, viewName, viewVersion) returns schema and refresh metadata.
  • Distinct from MaterializedViewStore: rows remain query-oriented JSON objects instead of per-key opaque payload records.

AnalyticsStore — operational or product analytics events:

  • Append(ctx, event) stores an AnalyticsEvent.
  • QueryPrepared(ctx, query, args) reads events through a backend-specific prepared query.
  • Does not compute aggregates or define dashboards.

AuditStore — compliance and security audit trail:

  • Append(ctx, record) stores an append-only AuditRecord.
  • List(ctx, query) returns records filtered by AuditQuery (resource, actor, time range, limit). Distinct from AnalyticsStore: audit entries capture actor, action, and outcome for compliance review.

SessionService — agent sessions (Google ADK SessionService analogue):

  • CreateSession, GetSession, ListEventsAfter, ListSessions, DeleteSession, AppendEvent.
  • Session-scoped state plus optional app:/user: prefixed state deltas on events.
  • Backed by hai_agent_session / hai_agent_session_event tables in SQLite and Postgres.

JobStore — durable background job queue:

  • Enqueue(ctx, job), ClaimNext(ctx, jobType), Update(ctx, job), Get(ctx, id).
  • Optional JobCASStore.UpdateIf compare-and-swaps using UpdatedAt.
  • Optional JobDeleter.Delete removes a row (used to abandon a failed kickoff).
  • JobRecord tracks Type, Payload, Status (pending/running/completed/failed), Attempts, CreatedAt, UpdatedAt, RunAfter, and LastError.
  • Retry and scheduling policy remain outside this package.

ModuleStore — runtime module registration metadata:

  • Register(ctx, module), Get(ctx, name), List(ctx), Unregister(ctx, name).
  • ModuleRecord holds Name, Version, Metadata, and RegisteredAt.
  • Does not load code or enforce which modules are active.

NodeRegistryStore — edge and cloud node registration for sync coordination:

  • Register(ctx, node), Get(ctx, nodeID), List(ctx), Unregister(ctx, nodeID).
  • NodeRecord holds NodeID, Metadata, and RegisteredAt.
  • Does not perform heartbeat, lease, or leader election.

Transaction boundaries

Transaction and Transactor — optional low-level transactions:

  • BeginTx(ctx) returns a Transaction with Commit() and Rollback().
  • When supported, all writes through the transaction-scoped stores must commit atomically according to the backend's rules.

WriteSession and WriteSessionProvider — coordinated atomic writes:

  • BeginWrite(ctx) returns a WriteSession exposing ResourceStore(), HistoryStore(), SearchStore(), and EventStore() bound to one unit of work.
  • Commit(ctx) or Rollback(ctx) finishes the session.
  • Adapters such as pkg/sqlite.Session and pkg/postgres write pipelines implement this pattern for local and tenant-scoped atomic resource writes.

Typical flows

Simple resource read:

envelope, err := resourceStore.Read(ctx, "Patient", "pat-1")

Full local write path (composed by pkg/core or an adapter session):

  1. resourceStore.Create or Update with types.ResourceEnvelope
  2. historyStore.AppendVersion with matching ResourceVersion
  3. eventStore.Append with matching ResourceEvent
  4. searchStore.Index with extracted SearchIndexEntry fields
  5. On delete: resourceStore.Delete, history tombstone, delete event, searchStore.RemoveIndex

Sync replay:

events, err := eventStore.ReadSince(ctx, cursorPosition, limit)
… process events …
cursorStore.UpsertCursor(ctx, store.Cursor{Name: worker, Position: lastSequence})

Conflict capture (policy elsewhere):

conflictStore.Append(ctx, store.ConflictRecord{…})
… later …
conflictStore.Resolve(ctx, id, time.Now())

Atomic write session:

session, err := provider.BeginWrite(ctx)
session.ResourceStore().Create(ctx, envelope)
session.HistoryStore().AppendVersion(ctx, version)
session.EventStore().Append(ctx, event)
session.SearchStore().Index(ctx, entry)
session.Commit(ctx)

Integration with other packages

pkg/types — ResourceEnvelope is the only FHIR resource container crossing store boundaries. Hash, VersionID, and LastUpdated on envelopes are derived in pkg/types; stores persist them as supplied.

pkg/sqlite — embedded local implementation of core contracts (ResourceStore, HistoryStore, SearchStore, EventStore via outbox, CursorStore, ConflictStore, BinaryStore) plus transaction-scoped Session for atomic offline writes.

pkg/postgres — tenant-scoped edge/cloud implementation covering the broader contract surface (including BlobStore, MaterializedViewStore, ReportingTableStore, AnalyticsStore, JobStore, AuditStore, ModuleStore, NodeRegistryStore, IDRegistryStore, and WriteSession-style pipelines).

pkg/core — orchestrates business rules, version assignment, and write pipelines on top of store interfaces without importing backend packages directly in hot paths where possible.

pkg/search — parses FHIR search parameters and produces index entries or queries; it does not implement SearchStore.

In-memory test doubles and future pkg/store/memory adapters implement subsets of these interfaces for tests and lightweight deployments.

File layout

  • doc.go — package documentation (this file).
  • resource.go — ResourceStore.
  • history.go — HistoryStore, ResourceVersion, VersionAction.
  • search.go — SearchStore, SearchIndexEntry, PreparedQuery.
  • events.go — EventStore, ResourceEvent, EventAction.
  • transaction.go — Transaction, Transactor.
  • write_session.go — WriteSession, WriteSessionProvider.
  • id_registry.go — IDRegistryStore, IDRegistryEntry, IDRegistryResult.
  • binary.go — BinaryStore, BinaryObject.
  • blob.go — BlobStore, BlobObject, BlobStoreWithStream, BlobStoreWithOpen, PutBlob, PutBlobFromPath, OpenBlob.
  • cursor.go — CursorStore, Cursor.
  • inbox.go — InboxStore for sync idempotency.
  • conflict.go — ConflictStore, ConflictRecord.
  • materialized_view.go — MaterializedViewStore, MaterializedViewRecord.
  • reporting_table.go — ReportingTableStore, ReportingTableMeta, ReportingColumn.
  • analytics.go — AnalyticsStore, AnalyticsEvent.
  • audit.go — AuditStore, AuditRecord, AuditQuery.
  • job.go — JobStore, JobRecord, JobStatus.
  • module.go — ModuleStore, ModuleRecord.
  • node_registry.go — NodeRegistryStore, NodeRecord.

Testing

store_test.go contains contract-focused tests: compile-time interface satisfaction checks using in-memory implementations, JSON round-trip tests for record types, tombstone history representation, cursor empty/non-empty positions, transaction commit/rollback, composed write paths, and behavioral tests for each store interface. Backend-specific correctness belongs in pkg/sqlite and pkg/postgres tests.

Out of scope (MVP)

Concrete database adapters (except as separate packages), in-memory production adapters (pkg/store/memory is future work), tenant models embedded in every interface, bulk import/export APIs, streaming query interfaces, object-storage SDK types, FHIR search parsing, version assignment policy, conflict reconciliation, job execution engines, analytics aggregation, and audit retention workflows.

Index

Constants

View Source
const (
	SessionAuthorUser       = "user"
	SessionAuthorModel      = "model"
	SessionAuthorTool       = "tool"
	SessionAuthorSystem     = "system"
	SessionAuthorCompaction = "compaction"
)

SessionEventAuthor identifies who produced an event (ADK-style roles).

View Source
const SessionEventMetadataCompaction = "compaction"

SessionEventMetadataCompaction marks a checkpoint event that summarizes prior history.

View Source
const SessionMetadataActiveTokensEstimate = "activeTokensEstimate"

SessionMetadataActiveTokensEstimate records the estimated active context tokens after compaction.

View Source
const SessionMetadataCompactionBasisTailEventID = "basisTailEventId"

SessionMetadataCompactionBasisTailEventID is the last active tail event id when compaction was planned.

View Source
const SessionMetadataCoveredEventCount = "coveredEventCount"

SessionMetadataCoveredEventCount is the number of events summarized into a compaction checkpoint.

View Source
const SessionMetadataLastCoveredEventID = "lastCoveredEventId"

SessionMetadataLastCoveredEventID is the id of the last event included in the compaction summary.

Variables

View Source
var ErrNotFound = errors.New("resource not found")

ErrNotFound indicates a resource does not exist in the current store.

View Source
var ErrSessionEventNotFound = errors.New("session event not found")

ErrSessionEventNotFound indicates the referenced event id is not in the session.

View Source
var ErrSessionNotFound = errors.New("session not found")

ErrSessionNotFound indicates the session key does not exist in the tenant scope.

View Source
var ErrUnsupportedFeature = errors.New("store: unsupported search feature")

ErrUnsupportedFeature indicates a search index operation the backend does not implement.

Functions

func ContextWithTerminologyInstalls

func ContextWithTerminologyInstalls(ctx context.Context, installs TerminologyInstallStore) context.Context

ContextWithTerminologyInstalls overrides the terminology opt-in store for one call tree.

func ContextWithTerminologyScope

func ContextWithTerminologyScope(ctx context.Context, scopeID string) context.Context

ContextWithTerminologyScope overrides the tenant terminology overlay scope for one call tree.

func PutBlob

func PutBlob(ctx context.Context, blobs BlobStore, key, contentType string, size int64, r io.Reader) error

PutBlob writes a blob. When blobs implements BlobStoreWithStream, the payload is streamed; otherwise PutBlob reads the full reader into memory and calls Put.

func PutBlobFromPath

func PutBlobFromPath(ctx context.Context, blobs BlobStore, key, contentType, path string) error

PutBlobFromPath streams a file into BlobStore without the caller loading it via os.ReadFile. Backends that do not implement BlobStoreWithStream still buffer the file inside PutBlob.

func TerminologyScopeFromContext

func TerminologyScopeFromContext(ctx context.Context) string

TerminologyScopeFromContext returns a per-request terminology overlay scope when set.

Types

type AgentSession added in v0.2.1

type AgentSession struct {
	ID        string         `json:"id"`
	TenantID  string         `json:"tenantId"`
	AppName   string         `json:"appName"`
	UserID    string         `json:"userId"`
	Subject   string         `json:"subject,omitempty"`
	State     map[string]any `json:"state"`
	Events    []SessionEvent `json:"events,omitempty"`
	CreatedAt time.Time      `json:"createdAt"`
	UpdatedAt time.Time      `json:"updatedAt"`
}

AgentSession is a conversation thread (Google ADK Session analogue).

type AnalyticsEvent

type AnalyticsEvent struct {
	ID         string             `json:"id"`
	Name       string             `json:"name"`
	Timestamp  time.Time          `json:"timestamp"`
	Dimensions map[string]string  `json:"dimensions,omitempty"`
	Values     map[string]float64 `json:"values,omitempty"`
	Payload    []byte             `json:"payload,omitempty"`
}

AnalyticsEvent is an append-only operational or product analytics record.

type AnalyticsStore

type AnalyticsStore interface {
	Append(ctx context.Context, event AnalyticsEvent) error
	QueryPrepared(ctx context.Context, query PreparedQuery, args map[string]string) ([]AnalyticsEvent, error)
}

AnalyticsStore appends analytics events and reads them through prepared queries. It does not compute aggregates or define reporting semantics.

type AppendEventParams added in v0.2.1

type AppendEventParams struct {
	TenantID  string
	AppName   string
	UserID    string
	SessionID string
	Event     SessionEvent
}

AppendEventParams appends one event and merges StateDelta into session state.

type AuditQuery

type AuditQuery struct {
	ResourceType   string    `json:"resourceType,omitempty"`
	ResourceID     string    `json:"resourceId,omitempty"`
	Actor          string    `json:"actor,omitempty"`
	Action         string    `json:"action,omitempty"`
	Outcome        string    `json:"outcome,omitempty"`
	Tenant         string    `json:"tenant,omitempty"`
	Subject        string    `json:"subject,omitempty"`
	ViewName       string    `json:"viewName,omitempty"`
	ToolName       string    `json:"toolName,omitempty"`
	ConversationID string    `json:"conversationId,omitempty"`
	After          time.Time `json:"after,omitempty"`
	Before         time.Time `json:"before,omitempty"`
	Limit          int       `json:"limit,omitempty"`
}

AuditQuery selects audit records with simple lookup filters.

type AuditRecord

type AuditRecord struct {
	ID             string            `json:"id"`
	Timestamp      time.Time         `json:"timestamp"`
	Actor          string            `json:"actor"`
	Action         string            `json:"action"`
	ResourceType   string            `json:"resourceType,omitempty"`
	ResourceID     string            `json:"resourceId,omitempty"`
	Outcome        string            `json:"outcome,omitempty"`
	Tenant         string            `json:"tenant,omitempty"`
	Subject        string            `json:"subject,omitempty"`
	ViewName       string            `json:"viewName,omitempty"`
	ToolName       string            `json:"toolName,omitempty"`
	ConversationID string            `json:"conversationId,omitempty"`
	ModuleName     string            `json:"moduleName,omitempty"`
	BlobKey        string            `json:"blobKey,omitempty"`
	Details        map[string]string `json:"details,omitempty"`
}

AuditRecord is an append-only compliance or security audit entry.

type AuditStore

type AuditStore interface {
	Append(ctx context.Context, record AuditRecord) error
	List(ctx context.Context, query AuditQuery) ([]AuditRecord, error)
}

AuditStore appends audit records and lists them for review pipelines.

type AuthDeviceRecord

type AuthDeviceRecord struct {
	DeviceID          string            `json:"deviceId"`
	TenantID          string            `json:"tenantId"`
	Status            string            `json:"status"`
	Trusted           bool              `json:"trusted"`
	Metadata          map[string]string `json:"metadata,omitempty"`
	LinkedPrincipalID string            `json:"linkedPrincipalId,omitempty"`
	CreatedAt         time.Time         `json:"createdAt"`
	UpdatedAt         time.Time         `json:"updatedAt"`
}

AuthDeviceRecord stores tenant-scoped device trust state.

type AuthPolicyRecord

type AuthPolicyRecord struct {
	TenantID  string    `json:"tenantId"`
	Name      string    `json:"name"`
	Format    string    `json:"format"`
	Version   string    `json:"version"`
	Body      []byte    `json:"body"`
	Active    bool      `json:"active"`
	CreatedAt time.Time `json:"createdAt"`
	UpdatedAt time.Time `json:"updatedAt"`
}

AuthPolicyRecord stores one persisted policy document.

type AuthPrincipalRecord

type AuthPrincipalRecord struct {
	ID          string            `json:"id"`
	Kind        string            `json:"kind"`
	DisplayName string            `json:"displayName,omitempty"`
	Attributes  map[string]string `json:"attributes,omitempty"`
	CreatedAt   time.Time         `json:"createdAt"`
	UpdatedAt   time.Time         `json:"updatedAt"`
}

AuthPrincipalRecord stores one principal identity used by pkg/auth.

type AuthRoleRecord

type AuthRoleRecord struct {
	Name        string    `json:"name"`
	Permissions []string  `json:"permissions,omitempty"`
	CreatedAt   time.Time `json:"createdAt"`
	UpdatedAt   time.Time `json:"updatedAt"`
}

AuthRoleRecord stores one named role and its permissions.

type AuthSnapshot

type AuthSnapshot struct {
	TenantID   string                    `json:"tenantId"`
	Principals []AuthPrincipalRecord     `json:"principals,omitempty"`
	Roles      []AuthRoleRecord          `json:"roles,omitempty"`
	Bindings   []AuthTenantBindingRecord `json:"bindings,omitempty"`
	Devices    []AuthDeviceRecord        `json:"devices,omitempty"`
	Policy     *AuthPolicyRecord         `json:"policy,omitempty"`
}

AuthSnapshot is the tenant-scoped auth dataset needed to hydrate pkg/auth.

type AuthStore

type AuthStore interface {
	UpsertPrincipal(ctx context.Context, principal AuthPrincipalRecord) error
	GetPrincipal(ctx context.Context, id string) (*AuthPrincipalRecord, error)
	ListPrincipals(ctx context.Context) ([]AuthPrincipalRecord, error)
	DeletePrincipal(ctx context.Context, id string) error

	UpsertRole(ctx context.Context, role AuthRoleRecord) error
	GetRole(ctx context.Context, name string) (*AuthRoleRecord, error)
	ListRoles(ctx context.Context) ([]AuthRoleRecord, error)
	DeleteRole(ctx context.Context, name string) error

	UpsertTenantBinding(ctx context.Context, binding AuthTenantBindingRecord) error
	GetTenantBinding(ctx context.Context, principalID string) (*AuthTenantBindingRecord, error)
	ListTenantBindings(ctx context.Context) ([]AuthTenantBindingRecord, error)
	DeleteTenantBinding(ctx context.Context, principalID string) error

	UpsertDevice(ctx context.Context, device AuthDeviceRecord) error
	GetDevice(ctx context.Context, deviceID string) (*AuthDeviceRecord, error)
	ListDevices(ctx context.Context) ([]AuthDeviceRecord, error)
	DeleteDevice(ctx context.Context, deviceID string) error

	UpsertPolicy(ctx context.Context, policy AuthPolicyRecord) error
	GetPolicy(ctx context.Context, name string) (*AuthPolicyRecord, error)
	GetActivePolicy(ctx context.Context) (*AuthPolicyRecord, error)
	ListPolicies(ctx context.Context) ([]AuthPolicyRecord, error)
	DeletePolicy(ctx context.Context, name string) error

	Snapshot(ctx context.Context) (*AuthSnapshot, error)
}

AuthStore persists and loads auth identities, roles, bindings, devices, and policy documents for one tenant context.

type AuthTenantBindingRecord

type AuthTenantBindingRecord struct {
	TenantID    string    `json:"tenantId"`
	PrincipalID string    `json:"principalId"`
	Roles       []string  `json:"roles,omitempty"`
	CreatedAt   time.Time `json:"createdAt"`
	UpdatedAt   time.Time `json:"updatedAt"`
}

AuthTenantBindingRecord links a principal to roles in one tenant.

type BinaryObject

type BinaryObject struct {
	Key         string    `json:"key"`
	ContentType string    `json:"contentType,omitempty"`
	Size        int64     `json:"size"`
	Hash        string    `json:"hash,omitempty"`
	Data        []byte    `json:"data,omitempty"`
	CreatedAt   time.Time `json:"createdAt"`
}

BinaryObject is a stored binary payload with lightweight metadata.

type BinaryStore

type BinaryStore interface {
	Put(ctx context.Context, obj BinaryObject) error
	Get(ctx context.Context, key string) (*BinaryObject, error)
	Delete(ctx context.Context, key string) error
}

BinaryStore stores and fetches binary payloads by stable key.

type BlobObject

type BlobObject struct {
	Key         string    `json:"key"`
	ContentType string    `json:"contentType,omitempty"`
	Size        int64     `json:"size"`
	Hash        string    `json:"hash,omitempty"`
	Data        []byte    `json:"data,omitempty"`
	Location    string    `json:"location,omitempty"`
	CreatedAt   time.Time `json:"createdAt"`
}

BlobObject is a stored blob payload or opaque backend reference. BinaryStore is intended for small inline payloads; BlobStore covers larger or externally referenced content without exposing object-storage SDK details.

func OpenBlob

func OpenBlob(ctx context.Context, blobs BlobStore, key string) (io.ReadCloser, *BlobObject, error)

OpenBlob opens a blob for reading. When blobs implements BlobStoreWithOpen, the payload is streamed; otherwise OpenBlob calls Get and wraps Data.

type BlobStore

type BlobStore interface {
	Put(ctx context.Context, obj BlobObject) error
	Get(ctx context.Context, key string) (*BlobObject, error)
	Head(ctx context.Context, key string) (*BlobObject, error)
	Delete(ctx context.Context, key string) error
}

BlobStore stores and fetches blob payloads by stable key.

type BlobStoreWithOpen

type BlobStoreWithOpen interface {
	BlobStore
	Open(ctx context.Context, key string) (io.ReadCloser, *BlobObject, error)
}

BlobStoreWithOpen optionally streams a blob payload. Head metadata is returned with Data omitted. Postgres hai_binary_object BYTEA still materializes in Open.

type BlobStoreWithStream

type BlobStoreWithStream interface {
	BlobStore
	PutStream(ctx context.Context, key, contentType string, size int64, r io.Reader) error
}

BlobStoreWithStream optionally uploads blob payloads from an io.Reader without requiring the caller to materialize the full object as []byte. Size may be 0 for an empty object. Backends that require Content-Length (for example S3 PutObject) should reject a negative size.

type ConditionalResourceStore

type ConditionalResourceStore interface {
	ResourceStore
	UpdateIfVersion(ctx context.Context, res *types.ResourceEnvelope, expectedVersion string) (bool, error)
	DeleteIfVersion(ctx context.Context, resourceType, id, expectedVersion string) (bool, error)
}

ConditionalResourceStore adds compare-and-write/delete operations. The comparison must happen in the same database statement/transaction as the mutation; a read followed by an ordinary Update is not equivalent.

type ConflictRecord

type ConflictRecord struct {
	ID              string     `json:"id"`
	ResourceType    string     `json:"resourceType"`
	ResourceID      string     `json:"resourceId"`
	LocalVersionID  string     `json:"localVersionId"`
	RemoteVersionID string     `json:"remoteVersionId"`
	Reason          string     `json:"reason"`
	CreatedAt       time.Time  `json:"createdAt"`
	ResolvedAt      *time.Time `json:"resolvedAt,omitempty"`
}

ConflictRecord captures a write or sync conflict as a first-class persistence record.

type ConflictStore

type ConflictStore interface {
	Append(ctx context.Context, record ConflictRecord) error
	List(ctx context.Context, resourceType, resourceID string) ([]ConflictRecord, error)
	Resolve(ctx context.Context, id string, resolvedAt time.Time) error
}

ConflictStore records and retrieves conflicts without embedding reconciliation policy.

type CreateSessionParams added in v0.2.1

type CreateSessionParams struct {
	TenantID     string
	AppName      string
	UserID       string
	SessionID    string
	Subject      string
	InitialState map[string]any
}

CreateSessionParams creates a new session row.

type Cursor

type Cursor struct {
	Name      string    `json:"name"`
	Position  string    `json:"position"`
	UpdatedAt time.Time `json:"updatedAt"`
}

Cursor is a named checkpoint for event consumers, sync workers, or indexers.

type CursorStore

type CursorStore interface {
	GetCursor(ctx context.Context, name string) (*Cursor, error)
	UpsertCursor(ctx context.Context, cursor Cursor) error
	DeleteCursor(ctx context.Context, name string) error
}

CursorStore persists consumer progress independently from event storage.

type DefinitionFilter

type DefinitionFilter struct {
	FHIRVersion        string
	DefinitionKind     DefinitionKind
	CanonicalURL       string
	PackageName        string
	ModuleName         string
	TargetResourceType string
}

DefinitionFilter selects definition resources from the catalog.

type DefinitionKind

type DefinitionKind string

DefinitionKind identifies a catalog entry kind for registry storage and compilation.

const (
	DefinitionKindStructureDefinition DefinitionKind = "structure-definition"
	DefinitionKindSearchParameter     DefinitionKind = "search-parameter"
	DefinitionKindCodeSystem          DefinitionKind = "code-system"
	DefinitionKindValueSet            DefinitionKind = "value-set"
	DefinitionKindConceptMap          DefinitionKind = "concept-map"
)

func DefinitionKindFromResourceType

func DefinitionKindFromResourceType(resourceType string) DefinitionKind

DefinitionKindFromResourceType maps a FHIR definition resource type to a catalog kind slug. Known MVP kinds are normalized; future kinds use a kebab-case slug derived from the type name.

type DefinitionResourceRecord

type DefinitionResourceRecord struct {
	CanonicalURL     string         `json:"canonicalUrl"`
	Version          string         `json:"version"`
	FHIRVersion      string         `json:"fhirVersion"`
	FHIRResourceType string         `json:"fhirResourceType"`
	DefinitionKind   DefinitionKind `json:"definitionKind"`
	Name             string         `json:"name"`
	Status           string         `json:"status"`
	PackageName      string         `json:"packageName,omitempty"`
	PackageVersion   string         `json:"packageVersion,omitempty"`
	ModuleName       string         `json:"moduleName,omitempty"`
	JSONData         []byte         `json:"jsonData"`
	InstalledAt      time.Time      `json:"installedAt"`
}

DefinitionResourceRecord stores one raw FHIR definition resource as JSON.

type DefinitionStore

type DefinitionStore interface {
	Upsert(ctx context.Context, record DefinitionResourceRecord, targets []DefinitionTargetRecord) error
	Get(ctx context.Context, canonicalURL, version string) (*DefinitionResourceRecord, error)
	List(ctx context.Context, filter DefinitionFilter) ([]DefinitionResourceRecord, error)
	Delete(ctx context.Context, canonicalURL, version string) error
}

DefinitionStore persists raw FHIR definition resources and their target mappings.

type DefinitionTargetRecord

type DefinitionTargetRecord struct {
	CanonicalURL       string `json:"canonicalUrl"`
	Version            string `json:"version"`
	TargetResourceType string `json:"targetResourceType"`
	TargetRole         string `json:"targetRole"`
}

DefinitionTargetRecord indexes a definition against one target resource type.

type DeleteSessionParams added in v0.2.1

type DeleteSessionParams struct {
	TenantID  string
	AppName   string
	UserID    string
	SessionID string
}

DeleteSessionParams deletes a session and its events.

type DeliveryListQuery

type DeliveryListQuery struct {
	SubscriptionID string
	EventSequence  int64
	Limit          int
}

DeliveryListQuery filters delivery log reads.

type DeliveryRecord

type DeliveryRecord struct {
	ID             string         `json:"id"`
	SubscriptionID string         `json:"subscriptionId"`
	EventSequence  int64          `json:"eventSequence"`
	Attempt        int            `json:"attempt"`
	Status         DeliveryStatus `json:"status"`
	ResponseStatus int            `json:"responseStatus,omitempty"`
	ResponseBody   string         `json:"responseBody,omitempty"`
	ErrorMessage   string         `json:"errorMessage,omitempty"`
	CreatedAt      time.Time      `json:"createdAt"`
	UpdatedAt      time.Time      `json:"updatedAt"`
}

DeliveryRecord is an append-only delivery log entry.

type DeliveryStatus

type DeliveryStatus string

DeliveryStatus describes one delivery attempt outcome.

const (
	DeliveryStatusPending  DeliveryStatus = "pending"
	DeliveryStatusSuccess  DeliveryStatus = "success"
	DeliveryStatusFailed   DeliveryStatus = "failed"
	DeliveryStatusRetrying DeliveryStatus = "retrying"
)

type EventAction

type EventAction string

EventAction describes a local resource change event.

const (
	EventActionCreate EventAction = "create"
	EventActionUpdate EventAction = "update"
	EventActionDelete EventAction = "delete"
)

type EventStore

type EventStore interface {
	Append(ctx context.Context, event ResourceEvent) (ResourceEvent, error)
	ReadSince(ctx context.Context, afterSequence int64, limit int) ([]ResourceEvent, error)
	LatestForResource(ctx context.Context, resourceType, id string) (*ResourceEvent, error)
}

EventStore appends local resource change events and reads them from a sequence checkpoint. Implementations assign Sequence on append when the caller leaves it unset.

type FullTextMatch

type FullTextMatch struct {
	IDs    []string
	Scores map[string]float64
}

FullTextMatch holds ranked full-text search matches.

type GetSessionConfig added in v0.2.1

type GetSessionConfig struct {
	// NumRecentEvents limits how many events are returned (0 = none, <0 invalid).
	NumRecentEvents int
	AfterTimestamp  time.Time
	// ActiveContextOnly returns only the latest compaction checkpoint (if any) and events after it.
	// Use for model context; omit or set false for the full append-only audit log.
	ActiveContextOnly bool
}

GetSessionConfig filters events when loading a session (ADK GetSessionConfig).

type GetSessionParams added in v0.2.1

type GetSessionParams struct {
	TenantID  string
	AppName   string
	UserID    string
	SessionID string
	Config    *GetSessionConfig
}

GetSessionParams loads a session and optional filtered events.

type HistoryStore

type HistoryStore interface {
	AppendVersion(ctx context.Context, version ResourceVersion) error
	GetHistory(ctx context.Context, resourceType, id string) ([]ResourceVersion, error)
	GetVersion(ctx context.Context, resourceType, id, versionID string) (ResourceVersion, error)
}

HistoryStore appends and reads immutable resource version history.

type IDRegistryEntry

type IDRegistryEntry struct {
	ResourceType string    `json:"resourceType"`
	ID           string    `json:"id"`
	RegisteredAt time.Time `json:"registeredAt"`
}

IDRegistryEntry records an authoritative resource ID registration for one tenant.

type IDRegistryResult

type IDRegistryResult struct {
	ResourceType string `json:"resourceType"`
	ID           string `json:"id"`
	Registered   bool   `json:"registered"`
}

IDRegistryResult summarizes the outcome of ID registration during a write.

type IDRegistryStore

type IDRegistryStore interface {
	Check(ctx context.Context, resourceType, id string) (bool, error)
	Reserve(ctx context.Context, resourceType, id string) error
	Register(ctx context.Context, resourceType, id string) error
}

IDRegistryStore reserves, checks, and registers resource IDs per tenant and resource type.

type InboxStore

type InboxStore interface {
	MarkApplied(ctx context.Context, id string, appliedAt time.Time) error
	IsApplied(ctx context.Context, id string) (bool, error)
	AppliedAt(ctx context.Context, id string) (*time.Time, error)
}

InboxStore tracks applied remote operations for idempotent sync replay. Device nodes use it for pull/apply dedupe by canonical event id; hub nodes may use it for push dedupe by client-generated event id.

type InboxWriteSession

type InboxWriteSession interface {
	InboxStore() InboxStore
}

InboxWriteSession is implemented by database-backed write sessions that can include inbox idempotency records in the same transaction as resource, history, and search changes.

type JobCASStore

type JobCASStore interface {
	UpdateIf(ctx context.Context, job JobRecord, expectedUpdatedAt time.Time) (bool, error)
}

JobCASStore optionally compare-and-swaps a job row using UpdatedAt. UpdateIf returns (false, nil) when the row exists but expectedUpdatedAt does not match the persisted value.

type JobDeleter

type JobDeleter interface {
	Delete(ctx context.Context, id string) error
}

JobDeleter optionally removes a job row.

type JobRecord

type JobRecord struct {
	ID        string    `json:"id"`
	Type      string    `json:"type"`
	Payload   []byte    `json:"payload,omitempty"`
	Status    JobStatus `json:"status"`
	Attempts  int       `json:"attempts"`
	CreatedAt time.Time `json:"createdAt"`
	UpdatedAt time.Time `json:"updatedAt"`
	RunAfter  time.Time `json:"runAfter,omitempty"`
	LastError string    `json:"lastError,omitempty"`
}

JobRecord is a durable background job entry.

type JobStatus

type JobStatus string

JobStatus describes persisted background job state.

const (
	JobStatusPending   JobStatus = "pending"
	JobStatusRunning   JobStatus = "running"
	JobStatusCompleted JobStatus = "completed"
	JobStatusFailed    JobStatus = "failed"
)

type JobStore

type JobStore interface {
	Enqueue(ctx context.Context, job JobRecord) error
	ClaimNext(ctx context.Context, jobType string) (*JobRecord, error)
	Update(ctx context.Context, job JobRecord) error
	Get(ctx context.Context, id string) (*JobRecord, error)
}

JobStore persists background jobs for workers to enqueue, claim, and update. Scheduling, retry, and execution policy remain outside this package.

type ListEventsAfterParams added in v0.2.1

type ListEventsAfterParams struct {
	TenantID     string
	AppName      string
	UserID       string
	SessionID    string
	AfterEventID string
}

ListEventsAfterParams returns session events strictly after AfterEventID in append order.

type ListSessionsParams added in v0.2.1

type ListSessionsParams struct {
	TenantID string
	AppName  string
	UserID   string
	Limit    int
}

ListSessionsParams lists session metadata for an app/user.

type MaterializedViewRecord

type MaterializedViewRecord struct {
	ViewName  string    `json:"viewName"`
	Key       string    `json:"key"`
	Payload   []byte    `json:"payload,omitempty"`
	Version   int64     `json:"version,omitempty"`
	UpdatedAt time.Time `json:"updatedAt"`
}

MaterializedViewRecord is a persisted projection entry for a named view.

type MaterializedViewStore

type MaterializedViewStore interface {
	Upsert(ctx context.Context, record MaterializedViewRecord) error
	Get(ctx context.Context, viewName, key string) (*MaterializedViewRecord, error)
	Delete(ctx context.Context, viewName, key string) error
	ListKeys(ctx context.Context, viewName string) ([]string, error)
}

MaterializedViewStore persists read-optimized projections independently from current-state resource storage. Callers own projection logic and refresh policy.

type ModuleRecord

type ModuleRecord struct {
	Name         string            `json:"name"`
	Version      string            `json:"version"`
	Metadata     map[string]string `json:"metadata,omitempty"`
	RegisteredAt time.Time         `json:"registeredAt"`
}

ModuleRecord describes a registered runtime module or extension.

type ModuleStore

type ModuleStore interface {
	Register(ctx context.Context, module ModuleRecord) error
	Get(ctx context.Context, name string) (*ModuleRecord, error)
	List(ctx context.Context) ([]ModuleRecord, error)
	Unregister(ctx context.Context, name string) error
}

ModuleStore persists module registration metadata without loading code or enforcing activation policy.

type NodeRecord

type NodeRecord struct {
	NodeID       string            `json:"nodeId"`
	Metadata     map[string]string `json:"metadata,omitempty"`
	RegisteredAt time.Time         `json:"registeredAt"`
}

NodeRecord describes a registered edge or cloud sync node.

type NodeRegistryStore

type NodeRegistryStore interface {
	Register(ctx context.Context, node NodeRecord) error
	Get(ctx context.Context, nodeID string) (*NodeRecord, error)
	List(ctx context.Context) ([]NodeRecord, error)
	Unregister(ctx context.Context, nodeID string) error
}

NodeRegistryStore persists node registration metadata for sync coordination.

type PackageInstallStore

type PackageInstallStore interface {
	MarkComplete(ctx context.Context, packageName, packageVersion string, completedAt time.Time) error
	IsComplete(ctx context.Context, packageName, packageVersion string) (bool, error)
}

PackageInstallStore tracks completed FHIR package version installs. MarkComplete is idempotent: it records the first completion timestamp only.

type PreparedQuery

type PreparedQuery struct {
	Name string `json:"name"`
}

PreparedQuery identifies a backend-specific prepared lookup or query plan.

type PushInboxStore

type PushInboxStore interface {
	InboxStore
	GetAckPayload(ctx context.Context, id string) ([]byte, bool, error)
	MarkAppliedWithPayload(ctx context.Context, id string, payload []byte, appliedAt time.Time) error
}

PushInboxStore extends InboxStore with durable acknowledgement storage for hub-side push idempotency. The payload is an opaque protocol acknowledgement so store does not depend on pkg/sync.

type ReferenceLink struct {
	TargetType string
	TargetID   string
	Literal    string
}

ReferenceLink is one indexed reference from a source resource.

type RegistryInstallFilter

type RegistryInstallFilter struct {
	TargetResourceType string
	DefinitionKind     DefinitionKind
	CanonicalURL       string
	Version            string
}

RegistryInstallFilter selects install/enablement rows.

type RegistryInstallRecord

type RegistryInstallRecord struct {
	DefinitionKind     DefinitionKind `json:"definitionKind"`
	CanonicalURL       string         `json:"canonicalUrl"`
	Version            string         `json:"version"`
	TargetResourceType string         `json:"targetResourceType"`
	Enabled            bool           `json:"enabled"`
	SourceModule       string         `json:"sourceModule,omitempty"`
	InstalledAt        time.Time      `json:"installedAt"`
}

RegistryInstallRecord tracks tenant/runtime enablement and installed definition references.

type RegistryInstallStore

type RegistryInstallStore interface {
	SetEnabled(ctx context.Context, record RegistryInstallRecord) error
	UpsertInstall(ctx context.Context, record RegistryInstallRecord) error
	ListEnabled(ctx context.Context) ([]RegistryInstallRecord, error)
	ListInstalled(ctx context.Context, filter RegistryInstallFilter) ([]RegistryInstallRecord, error)
	Delete(ctx context.Context, filter RegistryInstallFilter) error
}

RegistryInstallStore persists resource enablement and installed definition references.

type ReportingColumn

type ReportingColumn struct {
	Name string `json:"name"`
	Type string `json:"type"`
}

ReportingColumn describes one output column in a reporting table schema.

type ReportingTableMeta

type ReportingTableMeta struct {
	ViewName    string            `json:"viewName"`
	ViewVersion string            `json:"viewVersion"`
	Columns     []ReportingColumn `json:"columns"`
	RowCount    int               `json:"rowCount"`
	RefreshedAt time.Time         `json:"refreshedAt"`
}

ReportingTableMeta records the schema and refresh metadata for one view snapshot.

type ReportingTableStore

type ReportingTableStore interface {
	Refresh(ctx context.Context, meta ReportingTableMeta, rows []map[string]any) error
	QueryRows(ctx context.Context, viewName, viewVersion string) ([]map[string]any, error)
	GetMeta(ctx context.Context, viewName, viewVersion string) (*ReportingTableMeta, error)
}

ReportingTableStore persists tenant-scoped analytics reporting tables as queryable row sets keyed by view identity. Full refresh replaces all rows for a view version atomically.

type ResourceEvent

type ResourceEvent struct {
	Sequence     int64       `json:"sequence"`
	EventID      string      `json:"eventId,omitempty"`
	OriginNodeID string      `json:"originNodeId,omitempty"`
	LocalVersion string      `json:"localVersion,omitempty"`
	ResourceType string      `json:"resourceType"`
	ID           string      `json:"id"`
	VersionID    string      `json:"versionId"`
	Action       EventAction `json:"action"`
	Timestamp    time.Time   `json:"timestamp"`
	Hash         string      `json:"hash,omitempty"`
}

ResourceEvent is an append-only, typed resource change event for replay and sync pipelines.

type ResourceStore

type ResourceStore interface {
	Create(ctx context.Context, res *types.ResourceEnvelope) error
	Read(ctx context.Context, resourceType, id string) (*types.ResourceEnvelope, error)
	Update(ctx context.Context, res *types.ResourceEnvelope) error
	Delete(ctx context.Context, resourceType, id string) error
	Exists(ctx context.Context, resourceType, id string) (bool, error)
	ListIDs(ctx context.Context, resourceType string, limit, offset int) ([]string, error)
}

ResourceStore persists the current state of FHIR resources. Delete removes the current record; historical tombstones are recorded through HistoryStore.

type ResourceVersion

type ResourceVersion struct {
	ResourceType string                  `json:"resourceType"`
	ID           string                  `json:"id"`
	VersionID    string                  `json:"versionId"`
	Action       VersionAction           `json:"action"`
	Timestamp    time.Time               `json:"timestamp"`
	Resource     *types.ResourceEnvelope `json:"resource,omitempty"`
	Hash         string                  `json:"hash,omitempty"`
	Deleted      bool                    `json:"deleted"`
}

ResourceVersion is an immutable history entry for one resource version. Delete history is represented as Action=VersionActionDelete with Deleted=true. Callers must supply VersionID; this package does not assign versions.

type SearchAdvancedExecutor

type SearchAdvancedExecutor interface {
	SearchQueryExecutor
	LookupReferences(ctx context.Context, resourceType, fieldKey string, sourceIDs []string) (map[string][]ReferenceLink, error)
	LookupReferencing(ctx context.Context, sourceType, fieldKey, targetType, targetID string) ([]string, error)
	LookupFullText(ctx context.Context, resourceType, query string) (FullTextMatch, error)
}

SearchAdvancedExecutor extends typed lookups with advanced FHIR search operations. Postgres implements this interface; SQLite supports basic LookupMatch only.

type SearchIndexEntry

type SearchIndexEntry struct {
	ResourceType string            `json:"resourceType"`
	ID           string            `json:"id"`
	Fields       map[string]string `json:"fields,omitempty"`
}

SearchIndexEntry holds indexed metadata or prepared search tokens for one resource. Backends may persist extracted fields, token sets, or other index-oriented data. This package does not parse FHIR search expressions.

type SearchIndexMaintainer

type SearchIndexMaintainer interface {
	ListIndexedResourceIDs(ctx context.Context, resourceType string) ([]string, error)
}

SearchIndexMaintainer supports reindex orphan cleanup.

type SearchMatch

type SearchMatch struct {
	ResourceType string
	FieldKey     string
	Value        string
	Operator     string
}

SearchMatch identifies one typed predicate scoped to a resource type.

type SearchQueryExecutor

type SearchQueryExecutor interface {
	LookupMatch(ctx context.Context, match SearchMatch) ([]string, error)
	FieldValues(ctx context.Context, resourceType, fieldKey string, resourceIDs []string) (map[string]string, error)
}

SearchQueryExecutor executes typed index lookups for FHIR search. Postgres implements this interface; SQLite supports index writes and simple lookups only.

type SearchStore

type SearchStore interface {
	Index(ctx context.Context, entry SearchIndexEntry) error
	RemoveIndex(ctx context.Context, resourceType, id string) error
	Lookup(ctx context.Context, key, value string) ([]string, error)
	QueryPrepared(ctx context.Context, query PreparedQuery, args map[string]string) ([]string, error)
}

SearchStore persists search-index records and returns candidate resource IDs. It is index-oriented only; callers prepare lookup keys or queries outside this package.

type SessionEvent added in v0.2.1

type SessionEvent struct {
	ID           string            `json:"id"`
	InvocationID string            `json:"invocationId,omitempty"`
	Timestamp    time.Time         `json:"timestamp"`
	Author       string            `json:"author"`
	Partial      bool              `json:"partial,omitempty"`
	Content      string            `json:"content,omitempty"`
	ToolCallID   string            `json:"toolCallId,omitempty"`
	ToolCalls    []SessionToolCall `json:"toolCalls,omitempty"`
	StateDelta   map[string]any    `json:"stateDelta,omitempty"`
	Metadata     map[string]string `json:"metadata,omitempty"`
}

SessionEvent is one immutable step in a session history (message, tool, state change).

func ActiveContextEvents added in v0.2.1

func ActiveContextEvents(events []SessionEvent) []SessionEvent

ActiveContextEvents returns the minimal event slice stored on the harness after load: the latest compaction row (if any) plus tail events after lastCoveredEventId.

func ActiveContextView added in v0.2.1

func ActiveContextView(events []SessionEvent) (checkpointSummary string, active []SessionEvent)

ActiveContextView splits history into the latest checkpoint summary and replayable tail events. Checkpoints are append-only and may appear after the tail physically; tail selection uses lastCoveredEventId.

func LatestCompactionEvent added in v0.2.1

func LatestCompactionEvent(events []SessionEvent) (SessionEvent, bool)

LatestCompactionEvent returns the newest compaction checkpoint in append order.

type SessionService added in v0.2.1

type SessionService interface {
	CreateSession(ctx context.Context, params CreateSessionParams) (*AgentSession, error)
	GetSession(ctx context.Context, params GetSessionParams) (*AgentSession, error)
	ListEventsAfter(ctx context.Context, params ListEventsAfterParams) ([]SessionEvent, error)
	ListSessions(ctx context.Context, params ListSessionsParams) ([]SessionSummary, error)
	DeleteSession(ctx context.Context, params DeleteSessionParams) error
	AppendEvent(ctx context.Context, params AppendEventParams) (*SessionEvent, error)
	GetUserState(ctx context.Context, tenantID, appName, userID string) (map[string]any, error)
	GetAppState(ctx context.Context, tenantID, appName string) (map[string]any, error)
}

SessionService manages agent sessions and append-only event history (ADK SessionService).

type SessionSummary added in v0.2.1

type SessionSummary struct {
	ID        string    `json:"id"`
	TenantID  string    `json:"tenantId"`
	AppName   string    `json:"appName"`
	UserID    string    `json:"userId"`
	Subject   string    `json:"subject,omitempty"`
	UpdatedAt time.Time `json:"updatedAt"`
}

SessionSummary is returned from ListSessions without event payloads.

type SessionToolCall added in v0.2.1

type SessionToolCall struct {
	ID        string `json:"id"`
	Name      string `json:"name"`
	Arguments string `json:"arguments"`
}

SessionToolCall is a persisted tool invocation on a model event.

type SubscriptionDeliveryStore

type SubscriptionDeliveryStore interface {
	Append(ctx context.Context, record DeliveryRecord) error
	Update(ctx context.Context, record DeliveryRecord) error
	Get(ctx context.Context, id string) (*DeliveryRecord, error)
	List(ctx context.Context, query DeliveryListQuery) ([]DeliveryRecord, error)
}

SubscriptionDeliveryStore persists delivery attempt logs.

type SubscriptionListQuery

type SubscriptionListQuery struct {
	Status       SubscriptionStatus
	ResourceType string
	EventKind    string
	Limit        int
}

SubscriptionListQuery filters subscription registry reads.

type SubscriptionRecord

type SubscriptionRecord struct {
	ID           string             `json:"id"`
	Name         string             `json:"name"`
	Status       SubscriptionStatus `json:"status"`
	ResourceType string             `json:"resourceType"`
	EventKind    string             `json:"eventKind"`
	TriggerJSON  []byte             `json:"trigger"`
	ChannelJSON  []byte             `json:"channel"`
	RetryJSON    []byte             `json:"retryPolicy,omitempty"`
	CreatedAt    time.Time          `json:"createdAt"`
	UpdatedAt    time.Time          `json:"updatedAt"`
}

SubscriptionRecord is a persisted subscription definition.

type SubscriptionStatus

type SubscriptionStatus string

SubscriptionStatus describes whether a subscription participates in matching.

const (
	SubscriptionStatusActive   SubscriptionStatus = "active"
	SubscriptionStatusDisabled SubscriptionStatus = "disabled"
)

type SubscriptionStore

type SubscriptionStore interface {
	Create(ctx context.Context, record SubscriptionRecord) error
	Update(ctx context.Context, record SubscriptionRecord) error
	Get(ctx context.Context, id string) (*SubscriptionRecord, error)
	List(ctx context.Context, query SubscriptionListQuery) ([]SubscriptionRecord, error)
	Delete(ctx context.Context, id string) error
}

SubscriptionStore persists subscription definitions.

type TerminologyConceptRecord

type TerminologyConceptRecord struct {
	ScopeID, SystemURL, SystemVersion, Code, Display, Definition string
	Active, Abstract                                             bool
	ParentCode, PropertiesJSON, DesignationsJSON                 string
}

type TerminologyExpansionMemberRecord

type TerminologyExpansionMemberRecord struct {
	ScopeID, ValueSetURL, ValueSetVersion, SystemURL, SystemVersion, Code, Display string
	Inactive                                                                       bool
}

type TerminologyInstallFilter

type TerminologyInstallFilter struct {
	PackName     string
	CanonicalURL string
	Version      string
	ResourceType string
}

TerminologyInstallFilter selects terminology install rows.

type TerminologyInstallRecord

type TerminologyInstallRecord struct {
	PackName     string    `json:"packName"`
	PackVersion  string    `json:"packVersion"`
	CanonicalURL string    `json:"canonicalUrl"`
	Version      string    `json:"version"`
	ResourceType string    `json:"resourceType"`
	Enabled      bool      `json:"enabled"`
	SourceModule string    `json:"sourceModule,omitempty"`
	InstalledAt  time.Time `json:"installedAt"`
}

TerminologyInstallRecord tracks tenant opt-in to a global terminology pack.

func FilterTerminologyInstalls

func FilterTerminologyInstalls(rows []TerminologyInstallRecord, filter TerminologyInstallFilter) []TerminologyInstallRecord

FilterTerminologyInstalls returns rows matching the supplied filter fields. Empty filter fields are ignored.

type TerminologyInstallStore

type TerminologyInstallStore interface {
	SetEnabled(ctx context.Context, record TerminologyInstallRecord) error
	UpsertInstall(ctx context.Context, record TerminologyInstallRecord) error
	ListEnabled(ctx context.Context) ([]TerminologyInstallRecord, error)
	ListInstalled(ctx context.Context, filter TerminologyInstallFilter) ([]TerminologyInstallRecord, error)
	Delete(ctx context.Context, filter TerminologyInstallFilter) error
}

TerminologyInstallStore persists per-tenant terminology pack enablement.

func TerminologyInstallsFromContext

func TerminologyInstallsFromContext(ctx context.Context) TerminologyInstallStore

TerminologyInstallsFromContext returns a per-request terminology opt-in store when set.

type TerminologyInstallStoreFactory

type TerminologyInstallStoreFactory interface {
	ForTenant(ctx context.Context, tenantID string) (TerminologyInstallStore, error)
}

TerminologyInstallStoreFactory resolves per-tenant terminology opt-in stores.

type TerminologyResourceRecord

type TerminologyResourceRecord struct {
	ScopeID, ResourceType, ResourceID, CanonicalURL, Version, Status string
	ResourceJSON                                                     []byte
	ContentMode, SourceModule                                        string
}

TerminologyResourceRecord is the canonical source used to rebuild indexes.

type TerminologyStore

type TerminologyStore interface {
	FindResource(ctx context.Context, scopeID, resourceType, canonicalURL, version string) (*TerminologyResourceRecord, error)
	PutResource(ctx context.Context, record TerminologyResourceRecord) error
	DeleteResource(ctx context.Context, scopeID, resourceType, canonicalURL, version string) error
	ListResources(ctx context.Context, scopeID, resourceType string) ([]TerminologyResourceRecord, error)
	ReplaceCodeSystem(ctx context.Context, scopeID, systemURL, version string, concepts []TerminologyConceptRecord) error
	LookupConcept(ctx context.Context, scopeID, systemURL, version, code string) (*TerminologyConceptRecord, error)
	ReplaceValueSet(ctx context.Context, record TerminologyValueSetRecord, members []TerminologyExpansionMemberRecord) error
	GetValueSet(ctx context.Context, scopeID, url, version string) (*TerminologyValueSetRecord, error)
	ListValueSetMembers(ctx context.Context, scopeID, url, version string) ([]TerminologyExpansionMemberRecord, error)
	DeleteProjections(ctx context.Context, scopeID, resourceType, canonicalURL, version string) error
}

TerminologyStore persists canonical terminology metadata and disposable projections.

type TerminologyValueSetRecord

type TerminologyValueSetRecord struct {
	ScopeID, CanonicalURL, Version, Status, ComposeJSON string
	ExpansionJSON                                       []byte
	ExpansionTimestamp                                  string
	ExpansionFingerprint                                string
}

type TerminologyWriteSession

type TerminologyWriteSession interface{ TerminologyStore() TerminologyStore }

TerminologyWriteSession is optionally implemented by transaction sessions whose terminology projections share the resource write transaction.

type Transaction

type Transaction interface {
	Commit() error
	Rollback() error
}

Transaction commits or rolls back a unit of work for transaction-capable backends.

type Transactor

type Transactor interface {
	BeginTx(ctx context.Context) (Transaction, error)
}

Transactor begins transactional write scopes. Only backends that support atomic writes need to implement this interface.

When BeginTx is supported, all writes performed through the transaction-scoped store or session must commit atomically according to that backend's rules.

type VersionAction

type VersionAction string

VersionAction describes the lifecycle action recorded in resource history.

const (
	VersionActionCreate VersionAction = "create"
	VersionActionUpdate VersionAction = "update"
	VersionActionDelete VersionAction = "delete"
)

type WriteSession

type WriteSession interface {
	ResourceStore() ResourceStore
	HistoryStore() HistoryStore
	SearchStore() SearchStore
	EventStore() EventStore
	Commit(ctx context.Context) error
	Rollback(ctx context.Context) error
}

WriteSession coordinates transaction-scoped store access for one atomic write.

type WriteSessionProvider

type WriteSessionProvider interface {
	BeginWrite(ctx context.Context) (WriteSession, error)
}

WriteSessionProvider begins atomic write sessions.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL