runtime

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: 41 Imported by: 0

README

haistack-runtime (pkg/runtime)

Composition and lifecycle glue for the haistack monorepo.

What it does

haistack-runtime is the runtime composition library for HAIStack. It turns lower-level packages into a single runnable service graph with managed startup, background workers, optional HTTP serving, and deterministic shutdown.

Think of it as the layer that answers: which stores, which tenant, which capabilities, and how do they start and stop together?

Concern What runtime owns
Storage Open + migrate SQLite or Postgres; ensure tenant for Postgres
Registry Seed bundled R4 definitions; rebuild snapshot after module install
Modules Install filesystem module directories via pkg/modules
Core Wire core.ResourceService with validator, indexer, and outbox
Search Wire search.Service and optional reindex worker (Postgres)
Sync Wire sync.Engine and job processor when hub is configured
HTTP Build FHIR handler; optionally manage http.Server lifecycle
Jobs Poll reindex and sync background work under one runtime loop

It does not:

  • Parse FHIR JSON or implement CRUD rules (pkg/core)
  • Define store SQL or migrations (pkg/sqlite, pkg/postgres)
  • Serve as a standalone binary (no CLI in this package)
  • Implement cloud provider SDKs (adapter seams only)
  • Replace manual wiring in tests that need fine-grained control over one subsystem

When to use it

  • Building a local offline-first node (SQLite + optional sync hub)
  • Running a single-tenant edge server (Postgres all-in-one)
  • Composing a cloud deployment shape with injected external adapters
  • Integration tests that need a full stack without copy-pasting wiring from README examples
  • Embedding the FHIR handler in a custom HTTP server via Runtime.Handler()

Prefer manual wiring when you need only one package (e.g. core-only or search-only unit tests).

How it fits in the ecosystem

  cmd/haistack serve (or custom main)
              |
              v
       pkg/runtime.Builder -> Build/Start/Shutdown
              |
    +---------+---------+---------+---------+
    |         |         |         |         |
    v         v         v         v         v
 sqlite/   registry  modules    core     search
 postgres            install             + jobs
    |         |         |         |         |
    +---------+---------+---------+---------+
                        |
                        v
                  pkg/http.Handler()
                        |
            optional managed http.Server
                        |
            optional pkg/oauth (WithBuiltinOAuth)
Direction Package Relationship
Downstream http FHIR REST handler built from wired services
Downstream client Remote sync hub URL uses client sync sub-API
Peer sqlite / postgres Storage opened and migrated during Build
Peer modules Filesystem installs at build time
Peer sync Device engine when hub configured
Peer jobs Reindex and sync background processors
Peer oauth Optional built-in SMART authorization server
Out of scope auth middleware Use WithHTTPAuth / custom middleware on Handler()

Runtime answers composition and lifecycle; it does not implement FHIR business rules or SQL schemas.

Usage modes

These are how you embed runtime in a process. They complement Deployment modes (storage topology), which are inferred from builder flags.

1. Managed HTTP server (default CLI shape)

WithHTTP(addr) starts and stops http.Server inside Start / Shutdown:

rt, err := runtime.New().
    WithSQLite("/data/haistack.db").
    WithSearch().
    WithHTTP(":8080").
    Build(ctx)
err = rt.Start(ctx)
defer rt.Shutdown(ctx)
2. Embed handler only (custom server or multi-tenant gateway)

Skip WithHTTP and mount rt.Handler() on your own mux:

rt, err := runtime.New().
    WithPostgresAllInOne(dsn, "tenant-a").
    WithSearch().
    Build(ctx)
mux := http.NewServeMux()
mux.Handle("/fhir/", rt.Handler())

Use HTTPAddr() only when the managed server is enabled.

3. Build without start (tests and init probes)

Build performs migrations, module install, and service wiring — safe for tests that call services directly:

rt, err := runtime.New().WithSQLite(":memory:").WithSearch().Build(ctx)
svc := rt.Services().ResourceService
// no Start required for in-process CRUD tests
4. Offline SQLite device + HTTP sync hub

Local SQLite node with remote hub replication:

rt, err := runtime.New().
    WithSQLite("/data/device.db").
    WithSQLiteTenant("tenant-a").
    WithSync("https://hub.example.com").
    WithSyncNode("clinic-tablet-1").
    Build(ctx)

Hub must expose /sync/push and /sync/pull compatible with pkg/client.

5. Postgres hub with in-process sync.PostgresHub

Use WithSyncHub when the hub is co-located (integration tests, edge hub):

rt, err := runtime.New().
    WithPostgresAllInOne(dsn, "tenant-a").
    WithSyncHub(sync.NewPostgresHub(/* ... */)).
    WithSyncNode("device-1").
    Build(ctx)
6. Cloud seams without implementing providers here

Register adapter interfaces; provider SDKs live outside pkg/runtime:

rt, err := runtime.New().
    WithPostgresAllInOne(dsn, "tenant-a").
    WithExternalBlobStore(myBlobAdapter).
    WithExternalSearch(mySearchAdapter).
    WithSearch().
    Build(ctx)
blobs := rt.Services().BlobStore
7. Built-in OAuth reference host

Enable SMART authorization server routes for local Inferno-style testing:

rt, err := runtime.New().
    WithSQLite("/data/haistack.db").
    WithHTTP(":8080").
    WithBuiltinOAuth(runtime.BuiltinOAuthConfig{
        IssuerURL: "https://auth.example.test",
        TenantID:  "local",
    }).
    Build(ctx)

See pkg/oauth/OPERATIONS.md for production vs reference profiles.

Deployment modes

Modes are inferred at Build time from builder selections:

Mode Storage External adapters Typical use
local-sqlite SQLite Rejected Offline device, local dev, embedded nodes
edge-postgres-all-in-one Postgres (one tenant) Not used Edge/server deployment
cloud-postgres-plus-external-services Postgres (one tenant) Required for mode selection Cloud with S3/OpenSearch/etc. seams
Mode selection rules
  • Exactly one storage backend: WithSQLite or WithPostgresAllInOne, never both
  • Postgres requires a tenant ID
  • Any WithExternalBlobStore, WithExternalSearch, or WithExternalWarehouse with Postgres selects cloud mode
  • WithExternal* adapters on SQLite return ErrExternalAdapterInSQLite

Quick start

Local SQLite (MVP)
import (
    "context"
    "log"

    "github.com/degoke/haistack/pkg/runtime"
)

func main() {
    ctx := context.Background()

    rt, err := runtime.New().
        WithSQLite("/data/haistack.db").
        WithSearch().
        WithModules("modules/core").
        WithHTTP(":8080").
        Build(ctx)
    if err != nil {
        log.Fatal(err)
    }

    if err := rt.Start(ctx); err != nil {
        log.Fatal(err)
    }
    defer rt.Shutdown(ctx)

  // rt.Handler() is also available for custom servers
}
Edge Postgres (single tenant)
rt, err := runtime.New().
    WithPostgresAllInOne("postgres://user:pass@localhost/haistack?sslmode=disable", "tenant-a").
    WithPostgresSchema("fhir"). // optional; default is public
    WithSearch().
    WithModules("modules/core", "modules/scheduling").
    WithHTTP(":8080").
    Build(ctx)

Postgres mode with WithSearch also wires a background reindex worker and registers search.NewReindexNotifier on the registry manager so SearchParameter changes enqueue reindex jobs.

Builtin SMART OAuth (haistack serve)

When HTTP is enabled, WithBuiltinOAuth mounts pkg/oauth on the root handler (/oauth/*, /.well-known/*, mirrored under /fhir/.well-known/*, plus tenant routes at /t/{tenantId}/*). Stores use oauthstore.ApplySQLiteStores or ApplyPostgresStores with DB-backed rate limits. Signing keys persist in hai_oauth_signing_key when OAUTH_SIGNING_KEY_ENCRYPTION_SECRET is set (optional OAUTH_SIGNING_KEY_ROTATE=1 on startup keeps previous keys in JWKS); otherwise PEM files under {data-dir}/oauth or beside the SQLite database. Production mode enables /oauth/login session cookies via OAUTH_SESSION_SECRET and OAUTH_LOGIN_USERS, and background consent-session purge. The loopback haistack-app client is registered only when production is false.

rt, err := runtime.New().
    WithSQLite("/data/haistack.db").
    WithHTTP(":8080").
    WithBuiltinOAuth(runtime.BuiltinOAuthConfig{
        IssuerURL: "https://auth.example.test",
        TenantID:  "local",
    }).
    Build(ctx)

haistack serve enables this automatically when oauth.enabled is true. See pkg/oauth/OPERATIONS.md for production vs Inferno reference profiles.

Cloud Postgres + external adapters
rt, err := runtime.New().
    WithPostgresAllInOne(dsn, "tenant-a").
    WithExternalBlobStore(myBlobAdapter).
    WithExternalSearch(mySearchAdapter).
    WithExternalWarehouse(myWarehouseAdapter).
    WithSearch().
    WithHTTP(":8080").
    Build(ctx)

// Adapters are exposed on the service container:
rt.Services().BlobStore
rt.Services().ExternalSearch
rt.Services().Warehouse

Concrete provider implementations belong outside pkg/runtime. The adapter interfaces are stable seams for future wiring.

Builder reference

Method Purpose
New() Create a builder
WithSQLite(path) Embedded SQLite database path
WithSQLiteTenant(id) / WithSQLiteTerminologyScope(scope) Configure local sync and terminology namespaces
WithPostgresAllInOne(dsn, tenantID) Single-tenant Postgres
WithPostgresSchema(schema) Postgres schema for hai_* tables and migrations (default: public)
WithExternalBlobStore(adapter) Cloud blob store seam
WithExternalSearch(adapter) Cloud search seam
WithExternalWarehouse(adapter) Cloud analytics/reporting seam
WithFHIRPath(engine) Optional FHIRPath engine (default created if omitted)
WithSearch() Enable search indexing + query service
WithSync(hubURL) Device sync against remote HTTP hub
WithSyncHub(hub) Device sync with a pre-built sync.Hub (e.g. sync.PostgresHub)
WithSyncNode(nodeID) Device node ID (default: runtime-node)
WithModules(paths...) Install local module directories at build time
WithHTTP(addr) Managed HTTP listen address (optional)
WithBuiltinOAuth(cfg) Mount built-in SMART OAuth server with durable stores and FHIR bearer auth
WithHTTPAuth(...) / WithHTTPMiddleware(...) Configure managed HTTP authentication and policy middleware
WithHooks(...) Four-point intercept SPI (incoming, pre-storage, post-commit, outgoing)
WithHTTPRateLimit(config) Configure process-local managed HTTP rate limiting
WithModuleAuthorizer(authorizer) Authorize module installs and upgrades
WithModuleVerifier(verifier) Verify module signatures/content before install and upgrade
Build(ctx) Wire everything; returns *Runtime

Lifecycle

Build(ctx)  →  open DB, migrate, seed registry, install modules, wire services
Start(ctx)  →  background job loop + optional http.Server
Shutdown(ctx)  →  stop HTTP → stop workers → close adapters → close DB
Method Behavior
Build Heavy initialization; safe to call without starting HTTP
Start Starts workers/server; cancellation of its context stops workers; repeated calls return ErrAlreadyStarted
Shutdown Safe to call multiple times; respects context deadline
Handler() FHIR REST handler always built; usable without WithHTTP
HTTPAddr() Actual bound address after Start (useful with :0)
Services() ServiceContainer with managers and wired services
Mode() / Config() Effective mode and normalized config
Shutdown order
  1. Stop HTTP accept loop (http.Server.Shutdown)
  2. Cancel background job context and wait for goroutines
  3. Close CloseableAdapter implementations
  4. Close SQLite/Postgres connections

Build failures roll back partially opened resources before returning an error.

Service container

Runtime.Services() returns:

Field When set
RegistryManager Always
RegistrySnapshot Always (after build)
ModuleManager Always
ResourceService Always
SearchService When WithSearch()
SyncEngine When sync hub configured
FHIRPathEngine Always
BulkExportService When job store and blob store are wired
BulkImportService When job store and blob store are wired
SubscriptionManager Always
SubscriptionProcessor Always
SubscriptionMatcher Always (Engine + search Registry)
SubscriptionHandlers Always (in-process local delivery registry)
TenantDB Postgres modes
BlobStore, ExternalSearch, Warehouse Cloud mode adapters

Runtime.Handler() also wires HTTP-only adapters (not on ServiceContainer): default SDCService composes FHIRPath with CQL 1.5 (pkg/cql) for SDC operations, and MeasureEvaluateService for Measure/$evaluate-measure. Override with WithSDC on the builder when embedding custom behavior.

Search by mode

Mode WithSearch() behavior
SQLite Embedded/basic search via local SearchStore executor
Postgres Full search service + background reindex worker

Advanced FHIR search features (_include wildcards, _has, two-hop chains, uri, composites, FTS) remain Postgres-first per pkg/search. SQLite persists index rows and supports basic lookups.

Sync by mode

Mode Sync wiring
SQLite + WithSync / WithSyncHub Device node: local outbox/cursor/inbox + remote hub
Postgres (edge) Hub-side stores available; device engine only when sync explicitly configured

WithSync(hubURL) uses the pkg/client sync client over HTTP. WithSyncHub accepts any sync.Hub implementation, including sync.PostgresHub for device-to-Postgres-hub tests.

When search indexing is enabled alongside sync, the runtime bridges search.Indexer to sync.SearchIndexer so pull-apply can rebuild search rows.

Cloud adapter seams

Minimal interfaces for provider plugins:

type BlobStoreAdapter interface {
    Name() string
    BlobStore() store.BlobStore
}

type ExternalSearchAdapter interface {
    Name() string
    SearchExecutor() store.SearchQueryExecutor
}

type WarehouseAdapter interface {
    Name() string
    ReportingTables() store.ReportingTableStore
}

Implement CloseableAdapter when the adapter holds connections that must close on shutdown.

Errors

Error Cause
ErrNoStorage Neither SQLite nor Postgres configured
ErrConflictingStorage Both SQLite and Postgres configured
ErrMissingTenantID Postgres without tenant ID
ErrExternalAdapterInSQLite External adapter on SQLite
ErrSyncHubRequired Sync enabled without hub URL or hub
ErrAlreadyStarted Second Start call
ErrInvalidModeCombination Unsupported dependency set

Mental model

Builder selections  →  mode inference + validation
        ↓
Open + migrate store(s)
        ↓
Seed registry → install modules → rebuild snapshot
        ↓
FHIRPath + validator + indexer + ResourceService + SearchService + SyncEngine
        ↓
pkg/http handler (+ optional managed Server)
        ↓
Start: job loop + HTTP     Shutdown: reverse order

One line: pkg/runtime is the wiring and lifecycle layer — it knows how to assemble the stack for local, edge, and cloud shapes and keep it running.

Where it fits

Layer Role
runtime Composition, mode selection, lifecycle
sqlite / postgres Persistence implementations
registry FHIR definition catalog
modules Manifest-driven installs
core Resource CRUD and transactions
search Indexing and query execution
sync Device-to-hub replication
http FHIR REST transport adapter
jobs Background job claiming and dispatch

Testing

go test ./pkg/runtime/...

Postgres integration tests use testcontainers (postgres:16-alpine) or TEST_POSTGRES_DSN when Docker is unavailable.

Short mode skips Postgres-dependent tests:

go test ./pkg/runtime/... -short

Limits

  • Library-only; no cmd/haistack CLI in this package
  • One Postgres tenant per runtime instance
  • Cloud adapters are registration seams; provider SDKs are out of scope here
  • HTTP hub sync depends on a remote server exposing /sync/push and /sync/pull
  • Auth middleware and SMART flows are not wired by default (use Handler() with custom server middleware)

Documentation

Overview

Package runtime implements haistack-runtime, the composition and lifecycle library for HAIStack. It wires persistence, registry, modules, core, search, sync, and HTTP into three explicit deployment modes and owns startup, background workers, managed HTTP serving, and deterministic shutdown.

haistack-runtime is library-only. It does not ship a CLI or process supervisor. Callers construct a Builder, call Build to open stores and wire services, then Start and Shutdown to manage the runtime lifecycle.

Deployment modes

The effective mode is inferred and validated from builder selections at Build time:

  • ModeLocalSQLite — embedded SQLite as the only durable store. External blob, search, and warehouse adapters are rejected.
  • ModeEdgePostgresAllInOne — one Postgres tenant for resources, history, search, jobs, modules, audit, blobs, and sync/event stores. Uses internal Postgres-backed stores, not external services.
  • ModeCloudPostgresPlusExternalServices — Postgres for canonical resource, history, event, and module state plus explicitly injected external adapters for blob storage, search, and/or analytics warehouses.

One Postgres runtime instance serves one tenant. WithPostgresAllInOne requires a non-empty tenant ID. WithPostgresSchema optionally places hai_* tables and migrations in a non-public schema (for example "fhir").

Builder API

Construct a runtime with the fluent builder:

rt, err := runtime.New().
    WithSQLite("/data/haistack.db").
    WithSearch().
    WithModules("modules/core").
    WithHTTP(":8080").
    Build(ctx)

Builder methods:

  • New — returns a new Builder
  • WithSQLite(path) — select embedded SQLite storage
  • WithPostgresAllInOne(dsn, tenantID) — select single-tenant Postgres
  • WithPostgresSchema(schema) — optional Postgres schema for hai_* tables (default: public)
  • WithExternalBlobStore, WithExternalSearch, WithExternalWarehouse — cloud adapter seams
  • WithFHIRPath(engine) — optional; a default engine is created when omitted
  • WithSDC(service) — optional SDC HTTP operation adapter; the default core/FHIRPath/CQL adapter is used when omitted
  • WithSearch — enable search indexing and query execution
  • WithSync(hubURL), WithSyncHub(hub), WithSyncNode(nodeID) — device sync
  • WithSQLiteTenant, WithSQLiteTerminologyScope — local tenant namespaces
  • WithModules(paths...) — install modules from local filesystem directories
  • WithHTTP(addr) — optional managed HTTP server listen address
  • WithHTTPAuth, WithHTTPMiddleware, WithHTTPRateLimit — managed HTTP policy
  • WithModuleAuthorizer — module install/upgrade authorization
  • WithModuleVerifier — optional module signature/content verification
  • Build(ctx) — open stores, migrate, wire services, return *Runtime

Build validation rules:

  • Exactly one storage root: SQLite or Postgres, not both
  • Postgres modes require a tenant ID
  • local-sqlite rejects external blob/search/warehouse adapters
  • cloud mode is selected when Postgres is combined with any external adapter
  • Sync requires WithSync hub URL or WithSyncHub

Runtime lifecycle

  • Start(ctx) — start background job workers and the managed http.Server when WithHTTP was configured. Cancellation of ctx stops workers; call Shutdown for deterministic resource cleanup. Returns ErrAlreadyStarted on repeats.
  • Shutdown(ctx) — stop HTTP, cancel background workers, close adapters and DB connections. Repeated calls are safe.
  • Mode, Config, Services, Handler — accessors for embedding and testing
  • HTTPAddr — bound listen address after Start when HTTP is configured
  • /health and /healthz — liveness probes on the managed HTTP handler
  • SyncEngine, ReindexWorker — optional capability accessors

Shutdown order is deterministic:

  1. Stop HTTP accept loop
  2. Stop background workers (search reindex and sync job processors)
  3. Close external adapters implementing CloseableAdapter
  4. Close database connections last

Build failures roll back partially opened resources via an internal cleanup stack.

Service graph

Build wires the following through ServiceContainer:

  • registry.Manager with bundled R4 definitions seeded before module install
  • modules.Manager for filesystem module directories (pkg/modules loader)
  • fhirpath.Engine for registry-driven search indexing
  • core.ResourceService with validator, indexer, and outbox as available
  • search.Service when WithSearch is enabled
  • subscriptions.Matcher (Engine + Registry) and Processor
  • sync.Engine when sync is configured
  • FHIR HTTP handler via pkg/http adapters (always built for Handler access)

ServiceContainer fields:

  • RegistryManager, RegistrySnapshot, ModuleManager
  • ResourceService, SearchService, SyncEngine, FHIRPathEngine
  • SubscriptionManager, SubscriptionProcessor, SubscriptionMatcher
  • TenantDB (Postgres modes only)
  • BlobStore, ExternalSearch, Warehouse (cloud mode adapters)

Search behavior by mode

WithSearch on SQLite enables embedded/basic search wiring using the local SearchStore executor. Advanced registry-driven search and background reindex workers are Postgres-first per pkg/search; reindex jobs run only in Postgres modes when WithSearch is enabled.

Sync behavior by mode

SQLite with sync configured acts as a device node: local outbox, cursor, inbox, resource, and history stores plus a remote hub (HTTP via WithSync or a direct WithSyncHub adapter such as sync.PostgresHub).

Postgres edge mode does not start a device sync engine unless sync is explicitly configured. The runtime owns hub-side stores on Postgres but does not schedule device push unless WithSync or WithSyncHub is set.

Cloud adapter seams

BlobStoreAdapter, ExternalSearchAdapter, and WarehouseAdapter are minimal runtime-facing interfaces for future cloud integrations. Concrete provider implementations live outside pkg/runtime. Adapters need only the methods required for dependency registration and future wiring in this phase. Bulk $export/$import files use the blob adapter's store.BlobStore when it is non-nil; otherwise they use the chunked Postgres blob store or the SQLite blob store. Job status records persist in store.JobStore. Wiring fails if neither an adapter nor a database blob store is available.

Adapters may implement CloseableAdapter to participate in Shutdown.

Background workers

When enabled, the runtime owns one background job loop that polls:

  • search.ReindexWorker via jobs.Runner (Postgres + WithSearch)
  • sync.JobProcessor for retry push, scheduled pull, conflict, and replay jobs
  • subscriptions.Processor for event matching and delivery enqueue

Workers start on Start and stop on Shutdown context cancellation.

Ownership boundaries

haistack-runtime owns composition, mode inference, lifecycle, and the managed HTTP server. It does not own:

  • FHIR resource business rules (pkg/core)
  • Registry definition ingestion logic (pkg/registry)
  • Module manifest parsing (pkg/modules)
  • Search query planning and execution (pkg/search)
  • Sync protocol details (pkg/sync)
  • HTTP routing and OperationOutcome mapping (pkg/http)
  • SQL migrations and store implementations (pkg/sqlite, pkg/postgres)

File layout

  • doc.go — package documentation
  • mode.go — Mode constants
  • config.go — normalized Config struct
  • builder.go — Builder and mode resolution
  • runtime.go — Runtime lifecycle (Build, Start, Shutdown)
  • wire.go — store open/migrate and service wiring
  • services.go — ServiceContainer
  • adapters.go — cloud adapter seams
  • sync_hub.go — HTTP hub adapter for WithSync
  • indexer_bridge.go — search.Indexer to sync.SearchIndexer bridge
  • errors.go — validation and lifecycle errors

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNoStorage is returned when neither SQLite nor Postgres is configured.
	ErrNoStorage = errors.New("runtime: exactly one storage backend is required")

	// ErrConflictingStorage is returned when both SQLite and Postgres are configured.
	ErrConflictingStorage = errors.New("runtime: SQLite and Postgres cannot both be configured")

	// ErrMissingTenantID is returned when Postgres is selected without a tenant ID.
	ErrMissingTenantID = errors.New("runtime: tenant ID is required for Postgres modes")

	// ErrExternalAdapterInSQLite is returned when external adapters are used with SQLite.
	ErrExternalAdapterInSQLite = errors.New("runtime: external blob/search/warehouse adapters are not supported in local-sqlite mode")

	// ErrInvalidModeCombination is returned for unsupported dependency combinations.
	ErrInvalidModeCombination = errors.New("runtime: invalid mode and dependency combination")

	// ErrSyncHubRequired is returned when sync is enabled without a hub.
	ErrSyncHubRequired = errors.New("runtime: sync requires WithSync hub URL or WithSyncHub")

	// ErrAlreadyStarted is returned when Start is called on a running runtime.
	ErrAlreadyStarted = errors.New("runtime: already started")

	// ErrNotStarted is returned when operations require a started runtime.
	ErrNotStarted = errors.New("runtime: not started")

	// ErrBackgroundWorker indicates a background worker or managed server failed.
	ErrBackgroundWorker = errors.New("runtime: background worker failed")
)

Functions

This section is empty.

Types

type BlobStoreAdapter

type BlobStoreAdapter interface {
	// Name identifies the adapter for logging and capability reporting.
	Name() string
	// BlobStore returns the blob persistence contract used by binary transfer flows.
	BlobStore() store.BlobStore
}

BlobStoreAdapter is the runtime seam for external object storage in cloud mode. Concrete provider implementations live outside pkg/runtime.

func TestNoopBlobStore

func TestNoopBlobStore() BlobStoreAdapter

TestNoopBlobStore returns a minimal BlobStoreAdapter for seam tests.

type Builder

type Builder struct {
	// contains filtered or unexported fields
}

Builder composes a runtime from storage backends and optional capabilities.

func New

func New() *Builder

New returns a new runtime builder.

func (*Builder) Build

func (b *Builder) Build(ctx context.Context) (*Runtime, error)

Build constructs a wired runtime from the builder configuration.

func (*Builder) WithAnalytics

func (b *Builder) WithAnalytics() *Builder

WithAnalytics enables Postgres reporting-table refresh, CDC-triggered jobs, and view execution wired through pkg/analytics. Requires Postgres storage.

func (*Builder) WithAnalyticsConcurrency

func (b *Builder) WithAnalyticsConcurrency(max int) *Builder

WithAnalyticsConcurrency limits concurrent analytics refresh jobs to protect OLTP. Defaults to 1 when analytics is enabled and this is not set.

func (*Builder) WithBuiltinOAuth

func (b *Builder) WithBuiltinOAuth(cfg BuiltinOAuthConfig) *Builder

WithBuiltinOAuth enables the built-in SMART OAuth authorization server.

func (*Builder) WithDataDir

func (b *Builder) WithDataDir(dir string) *Builder

WithDataDir sets the absolute runtime data directory for view export artifacts and job metadata.

func (*Builder) WithExternalBlobStore

func (b *Builder) WithExternalBlobStore(store BlobStoreAdapter) *Builder

WithExternalBlobStore registers an external blob store adapter for cloud mode.

func (*Builder) WithExternalSearch

func (b *Builder) WithExternalSearch(search ExternalSearchAdapter) *Builder

WithExternalSearch registers an external search adapter for cloud mode.

func (*Builder) WithExternalWarehouse

func (b *Builder) WithExternalWarehouse(warehouse WarehouseAdapter) *Builder

WithExternalWarehouse registers an external warehouse adapter for cloud mode.

func (*Builder) WithFHIRPath

func (b *Builder) WithFHIRPath(engine fhirpath.Engine) *Builder

WithFHIRPath supplies a FHIRPath engine; when omitted, one is created at build time.

func (*Builder) WithHTTP

func (b *Builder) WithHTTP(addr string) *Builder

WithHTTP sets the listen address for a managed HTTP server started by Runtime.Start.

func (*Builder) WithHTTPAuth

func (b *Builder) WithHTTPAuth(resolver hahttp.PrincipalResolver, checker hahttp.AuthChecker) *Builder

WithHTTPAuth configures the built-in principal extraction and authorization middleware for the managed FHIR handler.

func (*Builder) WithHTTPMiddleware

func (b *Builder) WithHTTPMiddleware(middleware func(http.Handler) http.Handler) *Builder

WithHTTPMiddleware wraps the managed FHIR handler with application middleware such as authentication, tracing, or request policy.

func (*Builder) WithHTTPRateLimit

func (b *Builder) WithHTTPRateLimit(config hahttp.RateLimitConfig) *Builder

WithHTTPRateLimit enables process-local request limiting for the managed FHIR handler.

func (*Builder) WithHooks

func (b *Builder) WithHooks(h hooks.Hooks) *Builder

WithHooks registers the four-point intercept SPI on both core writes and the FHIR HTTP handler. The same registry should be used for incoming, pre-storage, post-commit, and outgoing callbacks.

func (*Builder) WithMaxExpansion

func (b *Builder) WithMaxExpansion(max int) *Builder

WithMaxExpansion sets the maximum ValueSet expansion size for terminology services and pre-expand workers. Zero uses the default of 10000.

func (*Builder) WithModuleAuthorizer

func (b *Builder) WithModuleAuthorizer(authorizer modules.InstallAuthorizer) *Builder

WithModuleAuthorizer configures authorization for module install and upgrade operations performed during Build and through the runtime module manager.

func (*Builder) WithModuleVerifier

func (b *Builder) WithModuleVerifier(verifier modules.ModuleVerifier) *Builder

WithModuleVerifier configures cryptographic or policy verification for modules before install and upgrade. Unsigned modules remain supported when no verifier is configured.

func (*Builder) WithModules

func (b *Builder) WithModules(paths ...string) *Builder

WithModules installs modules from local filesystem directories at build time.

func (*Builder) WithPackageInstalls

func (b *Builder) WithPackageInstalls(specs ...packages.InstallSpec) *Builder

WithPackageInstalls installs FHIR NPM packages or local IG directories at build time. Already-installed package versions are skipped idempotently.

func (*Builder) WithPostgresAllInOne

func (b *Builder) WithPostgresAllInOne(dsn, tenantID string) *Builder

WithPostgresAllInOne selects a single-tenant Postgres deployment.

func (*Builder) WithPostgresReadReplica

func (b *Builder) WithPostgresReadReplica(dsn string) *Builder

WithPostgresReadReplica configures a read-only Postgres DSN for analytics view scans.

func (*Builder) WithPostgresSchema

func (b *Builder) WithPostgresSchema(schema string) *Builder

WithPostgresSchema sets the Postgres schema for hai_* tables and migrations. When empty, postgres.Open uses the default public schema.

func (*Builder) WithPreExpandValueSets

func (b *Builder) WithPreExpandValueSets(enabled bool) *Builder

WithPreExpandValueSets enqueues async ValueSet pre-expansion jobs when IG packages install finite global ValueSets.

func (*Builder) WithRemoteTerminology

func (b *Builder) WithRemoteTerminology(baseURL string) *Builder

WithRemoteTerminology configures an optional remote FHIR terminology server (for example https://tx.fhir.org/r4) as the final provider in the chain.

func (*Builder) WithRemoteTerminologyBearerToken

func (b *Builder) WithRemoteTerminologyBearerToken(token string) *Builder

WithRemoteTerminologyBearerToken sets a Bearer token for remote ConceptMap/$translate.

func (*Builder) WithRemoteTerminologyTranslate

func (b *Builder) WithRemoteTerminologyTranslate(baseURL string) *Builder

WithRemoteTerminologyTranslate sets a FHIR server base URL used for ConceptMap/$translate when local ConceptMaps are unavailable. It is an alias for WithRemoteTerminology.

func (*Builder) WithRemoteTerminologyTranslateAuthorize

func (b *Builder) WithRemoteTerminologyTranslateAuthorize(fn func(*http.Request) error) *Builder

WithRemoteTerminologyTranslateAuthorize sets per-request auth for remote ConceptMap/$translate.

func (*Builder) WithRemoteTerminologyTranslateHeader

func (b *Builder) WithRemoteTerminologyTranslateHeader(key, value string) *Builder

WithRemoteTerminologyTranslateHeader adds a static request header for remote ConceptMap/$translate.

func (*Builder) WithSDC

func (b *Builder) WithSDC(service hahttp.SDCService) *Builder

WithSDC supplies the HTTP SDC operation adapter. When omitted, runtime wires the default core/FHIRPath adapter; applications can inject extractors, terminology, and adaptive session policy through this seam.

func (*Builder) WithSQLite

func (b *Builder) WithSQLite(path string) *Builder

WithSQLite selects embedded SQLite at the given database path.

func (*Builder) WithSQLiteTenant

func (b *Builder) WithSQLiteTenant(tenantID string) *Builder

WithSQLiteTenant sets the tenant namespace used by local sync and terminology persistence. It defaults to "local".

func (*Builder) WithSQLiteTerminologyScope

func (b *Builder) WithSQLiteTerminologyScope(scope string) *Builder

WithSQLiteTerminologyScope sets the terminology namespace used by SQLite. It defaults to "default".

func (*Builder) WithSearch

func (b *Builder) WithSearch() *Builder

WithSearch enables search indexing and query execution. On SQLite this wires embedded/basic search; advanced search remains Postgres-first.

func (*Builder) WithSync

func (b *Builder) WithSync(hubURL string) *Builder

WithSync enables device sync against a remote hub URL.

func (*Builder) WithSyncHub

func (b *Builder) WithSyncHub(hub hasync.Hub) *Builder

WithSyncHub enables device sync using a pre-built hub adapter.

func (*Builder) WithSyncMiddleware

func (b *Builder) WithSyncMiddleware(middleware func(http.Handler) http.Handler) *Builder

WithSyncMiddleware applies authentication and authorization to the runtime's /sync routes. It should bind the authenticated node and tenant to the request before the scoped hub is invoked.

func (*Builder) WithSyncNode

func (b *Builder) WithSyncNode(nodeID string) *Builder

WithSyncNode sets the device node ID used by the sync engine. When omitted, a default node ID is assigned at build time.

func (*Builder) WithSyncServer

func (b *Builder) WithSyncServer(hub hasync.HubServer) *Builder

WithSyncServer exposes /sync/push and /sync/pull on the HTTP server.

func (*Builder) WithViewExportDir

func (b *Builder) WithViewExportDir(dir string) *Builder

WithViewExportDir sets the filesystem directory for ViewDefinition export artifacts. When unset, SQLite runtimes use {db-dir}/view-exports and Postgres runtimes use view-exports/{tenantId}.

type BuiltinOAuthConfig

type BuiltinOAuthConfig struct {
	Production              bool
	RegistrationAccessToken string
	AutoApprove             *bool
	IssuerURL               string
	TenantID                string
	StateDir                string
}

BuiltinOAuthConfig enables the built-in pkg/oauth authorization server during runtime wire. IssuerURL defaults to http://{HTTPAddr} when empty.

type CloseableAdapter

type CloseableAdapter interface {
	Close(ctx context.Context) error
}

CloseableAdapter may be implemented by external adapters that hold connections.

type Config

type Config struct {
	Mode Mode

	// Storage
	SQLitePath             string
	SQLiteTenantID         string
	SQLiteTerminologyScope string
	PostgresDSN            string
	PostgresSchema         string // empty means the default public schema
	TenantID               string

	// Capabilities
	SearchEnabled bool
	ModulePaths   []string
	HTTPAddr      string

	// Sync
	SyncEnabled bool
	SyncHubURL  string
	SyncNodeID  string

	// OAuth (builtin authorization server)
	OAuthEnabled bool
	OAuthIssuer  string
}

Config is the normalized runtime configuration produced by Builder.Build.

type ConformanceRefresher

type ConformanceRefresher interface {
	Refresh(ctx context.Context) error
}

ConformanceRefresher rebuilds the live registry snapshot, validation catalog, and related conformance consumers after IG or terminology installs.

func NewConformanceRefresher

func NewConformanceRefresher(runtime *ConformanceRuntime, onDone func()) ConformanceRefresher

NewConformanceRefresher adapts ConformanceRuntime to ConformanceRefresher.

type ConformanceRuntime

type ConformanceRuntime struct {
	// contains filtered or unexported fields
}

ConformanceRuntime holds the live registry snapshot and validation state used by HTTP handlers and resource validation. Call Refresh after catalog changes.

func NewConformanceRuntime

func NewConformanceRuntime(cfg ConformanceRuntimeConfig) (*ConformanceRuntime, error)

NewConformanceRuntime builds a runtime view from an initial compiled snapshot.

func (*ConformanceRuntime) Engine

func (r *ConformanceRuntime) Engine() validate.Engine

Engine returns the current validation engine.

func (*ConformanceRuntime) ProfileCatalog

func (r *ConformanceRuntime) ProfileCatalog() *validate.RegistryProfileCatalog

ProfileCatalog returns the live profile catalog.

func (*ConformanceRuntime) Refresh

Refresh rebuilds the compiled snapshot and reloads validation consumers.

func (*ConformanceRuntime) Snapshot

func (r *ConformanceRuntime) Snapshot() *registry.Snapshot

Snapshot returns the current compiled registry view.

type ConformanceRuntimeConfig

type ConformanceRuntimeConfig struct {
	Manager         *registry.Manager
	FHIRPath        fhirpath.Engine
	ProfileCatalog  *validate.RegistryProfileCatalog
	Engine          *validate.ReloadableEngine
	SearchRegistry  *search.SnapshotRegistry
	PatientResolver *registry.PatientReferenceResolver
	InitialSnapshot *registry.Snapshot
}

ConformanceRuntimeConfig wires a conformance runtime from registry state.

type ExternalSearchAdapter

type ExternalSearchAdapter interface {
	// Name identifies the adapter for logging and capability reporting.
	Name() string
	// SearchExecutor returns the query executor when search is delegated externally.
	SearchExecutor() store.SearchQueryExecutor
}

ExternalSearchAdapter is the runtime seam for external search services in cloud mode.

func TestNoopExternalSearch

func TestNoopExternalSearch() ExternalSearchAdapter

TestNoopExternalSearch returns a minimal ExternalSearchAdapter for seam tests.

type Mode

type Mode string

Mode identifies the effective runtime deployment shape inferred from builder selections.

const (
	// ModeLocalSQLite uses embedded SQLite as the only durable store.
	ModeLocalSQLite Mode = "local-sqlite"

	// ModeEdgePostgresAllInOne uses one Postgres tenant for resources, history,
	// search, jobs, modules, audit, blobs, and sync/event stores.
	ModeEdgePostgresAllInOne Mode = "edge-postgres-all-in-one"

	// ModeCloudPostgresPlusExternalServices uses Postgres for canonical resource,
	// history, event, and module state with explicit external service adapters.
	ModeCloudPostgresPlusExternalServices Mode = "cloud-postgres-plus-external-services"
)

func (Mode) String

func (m Mode) String() string

type ParquetWarehouseAdapter

type ParquetWarehouseAdapter struct {
	Name_ string
	Sink  func() store.ReportingTableStore
}

ParquetWarehouseAdapter routes analytics export rows to object storage as Apache Parquet.

func (ParquetWarehouseAdapter) Name

func (ParquetWarehouseAdapter) ReportingTables

type Persistence

type Persistence struct {
	SQLite   *sqlite.DB
	Postgres *postgres.DB
	TenantDB *postgres.TenantDB
}

Persistence exposes narrow read-oriented access to underlying storage handles. It is intended for operator tooling such as the haistack CLI.

type PostgresReportingWarehouse

type PostgresReportingWarehouse struct {
	Store store.ReportingTableStore
	Name_ string
}

PostgresReportingWarehouse wraps a Postgres reporting table store for edge/cloud wiring.

func (PostgresReportingWarehouse) Name

func (PostgresReportingWarehouse) ReportingTables

type Runtime

type Runtime struct {
	// contains filtered or unexported fields
}

Runtime owns composed services, optional HTTP serving, and background workers.

func (*Runtime) BackgroundError

func (rt *Runtime) BackgroundError() error

BackgroundError returns the first background worker or managed server error observed.

func (*Runtime) Config

func (rt *Runtime) Config() Config

Config returns the normalized runtime configuration.

func (*Runtime) HTTPAddr

func (rt *Runtime) HTTPAddr() net.Addr

HTTPAddr returns the bound listen address after Start when HTTP is configured.

func (*Runtime) Handler

func (rt *Runtime) Handler() http.Handler

Handler returns the FHIR HTTP handler for embedding or testing.

func (*Runtime) IsStarted

func (rt *Runtime) IsStarted() bool

IsStarted reports whether the managed runtime has completed startup and is accepting requests. It is used by the readiness probe.

func (*Runtime) Mode

func (rt *Runtime) Mode() Mode

Mode returns the effective deployment mode.

func (*Runtime) Persistence

func (rt *Runtime) Persistence() Persistence

Persistence returns the wired persistence backends for the runtime, if any.

func (*Runtime) ReindexWorker

func (rt *Runtime) ReindexWorker() *search.ReindexWorker

ReindexWorker returns the configured search reindex worker, if any.

func (*Runtime) Services

func (rt *Runtime) Services() *ServiceContainer

Services exposes the wired service graph.

func (*Runtime) Shutdown

func (rt *Runtime) Shutdown(ctx context.Context) error

Shutdown stops HTTP serving, background workers, and closes persistence backends. Repeated calls are safe.

func (*Runtime) Start

func (rt *Runtime) Start(ctx context.Context) error

Start begins background workers and the managed HTTP server when configured.

func (*Runtime) SyncEngine

func (rt *Runtime) SyncEngine() *hasync.Engine

SyncEngine returns the configured sync engine, if any.

type ServiceContainer

type ServiceContainer struct {
	RegistryManager    *registry.Manager
	RegistrySnapshot   *registry.Snapshot
	ConformanceRuntime *ConformanceRuntime
	ModuleManager      *modules.Manager
	ResourceService    *core.ResourceService
	SearchService      *search.Service
	SyncEngine         *hasync.Engine
	FHIRPathEngine     fhirpath.Engine
	TerminologyService terminology.Service

	// TenantDB is set for Postgres modes.
	TenantDB *postgres.TenantDB

	// External adapters are populated in cloud mode when configured.
	BlobStore      BlobStoreAdapter
	ExternalSearch ExternalSearchAdapter
	Warehouse      WarehouseAdapter

	// BulkExportService handles FHIR Bulk Data export when job infrastructure is wired.
	BulkExportService *export.Service
	// BulkImportService handles FHIR Bulk Data import when job infrastructure is wired.
	BulkImportService *bulkimport.Service

	// AnalyticsRunner executes ViewDefinitions when analytics is enabled.
	AnalyticsRunner *analytics.Runner
	// ViewRegistry holds registered ViewDefinitions for analytics execution.
	ViewRegistry *view.Registry
	// ViewExecutor runs registered ViewDefinitions.
	ViewExecutor *view.Executor
	// MaterializeService handles ViewDefinition/$materialize operations.
	MaterializeService *view.MaterializeService
	// ViewRunService handles ViewDefinition/$viewdefinition-run operations.
	ViewRunService *view.RunService
	// SQLQueryService handles Library/$sqlquery-run operations.
	SQLQueryService *view.SQLQueryService
	// ViewExportService handles ViewDefinition/$viewdefinition-export operations.
	ViewExportService *view.ExportService
	// AnalyticsCDC consumes outbox events and schedules refresh jobs.
	AnalyticsCDC *analytics.CDCProcessor

	// SubscriptionManager registers and updates subscription records.
	SubscriptionManager *subscriptions.Manager
	// SubscriptionProcessor consumes resource events and enqueues deliveries.
	SubscriptionProcessor *subscriptions.Processor
	// SubscriptionMatcher evaluates triggers; Engine and Registry are always set.
	SubscriptionMatcher *subscriptions.Matcher
	// SubscriptionHandlers is the in-process local delivery handler registry.
	SubscriptionHandlers *subscriptions.HandlerRegistry
}

ServiceContainer exposes the wired service graph for embedding and testing.

type WarehouseAdapter

type WarehouseAdapter interface {
	// Name identifies the adapter for logging and capability reporting.
	Name() string
	// ReportingTables returns the reporting table contract for analytics refresh flows.
	ReportingTables() store.ReportingTableStore
}

WarehouseAdapter is the runtime seam for external analytics/reporting warehouses in cloud mode.

func TestNoopWarehouse

func TestNoopWarehouse() WarehouseAdapter

TestNoopWarehouse returns a minimal WarehouseAdapter for seam tests.

Jump to

Keyboard shortcuts

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