core

package
v0.2.0 Latest Latest
Warning

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

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

README

haistack-core (pkg/core)

FHIR resource lifecycle kernel for the haistack monorepo.

What it does

pkg/core is the brain for FHIR resource operations. It knows the rules for creating, reading, updating, and deleting FHIR resources — but it does not talk to HTTP or a specific database directly.

Think of it as a layer between your API/server and your storage:

HTTP handler (future)  →  pkg/core  →  pkg/store  →  SQLite or Postgres

When you save a FHIR resource (like a Patient), core handles the boring but important parts:

  1. Normalizes the JSON so it is consistent
  2. Optionally validates it (if you plug in a validator)
  3. Assigns or checks IDs (uses your ID if valid, otherwise generates a UUID)
  4. Assigns a new version (meta.versionId, meta.lastUpdated)
  5. Computes a content hash
  6. Saves everything atomically:
    • current resource
    • history entry
    • search index (optional)
    • sync/outbox event (optional)

If anything fails, the whole write is rolled back — no half-written data.

It also supports:

  • Read — get the current version of a resource
  • History — get all past versions of one resource
  • Transaction bundles — create/update/delete multiple resources in one atomic operation
  • Errors → OperationOutcome — turn Go errors into FHIR error responses

It does not store data itself, parse search queries, or serve HTTP. It orchestrates lifecycle rules on top of pkg/store.

What it does not do (MVP)

  • HTTP routes or REST server
  • Search query parsing (GET /Patient?name=...)
  • CapabilityStatement generation
  • System-wide _history (per-resource history only)

When to use it

  • Building a FHIR server or API — handlers call ResourceService instead of writing DB logic themselves
  • Running on device (SQLite) or server (Postgres) — same core code, different storage backend
  • Needing consistent versioning, history, and rollback without reimplementing it in every endpoint

Usage

Wire up storage, create a ResourceService, and call methods:

import (
    "context"

    "github.com/degoke/haistack/pkg/core"
    hasync "github.com/degoke/haistack/pkg/sync"
    "github.com/degoke/haistack/pkg/types"
)

// 1. Wire up storage (example: local SQLite)
svc, err := core.NewResourceService(core.ResourceServiceConfig{
    Resources: db.ResourceStore(), // for reads
    History:   db.HistoryStore(), // for history reads
    Sessions:  db,                 // for atomic writes (sqlite.DB or postgres.TenantDB)
    Outbox:    &hasync.EventStoreOutbox{}, // optional: emit change events
    // Validator: myValidator,       // optional
    // Indexer:   myIndexer,         // optional
})
if err != nil {
    // handle config error
}

ctx := context.Background()

// 2. Create a Patient
created, err := svc.Create(ctx, &types.ResourceEnvelope{
    ResourceType: "Patient",
    JSON:         []byte(`{"resourceType":"Patient","name":[{"family":"Doe"}]}`),
})
// created.ID and created.VersionID are set by core

// 3. Read it back
patient, err := svc.Read(ctx, "Patient", created.ID)

// 4. Update it
updated, err := svc.Update(ctx, &types.ResourceEnvelope{
    ResourceType: "Patient",
    ID:           created.ID,
    JSON:         updatedJSON,
})

// 5. Delete it
err = svc.Delete(ctx, "Patient", created.ID)

// 6. Get version history
versions, err := svc.History(ctx, "Patient", created.ID)

// 7. Handle errors for an API response
if err != nil {
    outcome := core.OperationOutcomeFromError(err)
    // return outcome as JSON to the client
}

Transaction bundle (multiple writes in one atomic session):

resp, err := svc.ProcessTransactionBundle(ctx, &types.ResourceEnvelope{
    ResourceType: "Bundle",
    JSON:         transactionBundleJSON,
})

Required vs optional pieces

Piece Required? Purpose
Resources Yes Read current resources
History Yes Read version history
Sessions Yes Atomic writes (sqlite.DB or postgres.TenantDB)
IDPolicy No Defaults to FHIR id syntax + UUID generation
Codec No Defaults to types.NewJSONCodec()
Validator No Check resource before save
Indexer No Update search tables
Outbox No Emit change events for sync

Mental model

pkg/core is “how FHIR resources live and change.” You plug in storage and optional validation/search/sync; it runs the lifecycle rules for you.

Where it fits

Layer Role
types Canonical JSON and ResourceEnvelope
store Persistence contracts and write sessions
core CRUD, history, versioning, transaction bundles
validate Optional pre-write validation contract
search Optional index extraction contract
sync Optional outbox/event emission contract
sqlite / postgres Concrete storage backends

Error handling

Core returns typed errors (invalid, conflict, not-found, not-supported, exception). Map them to FHIR responses with:

outcome := core.OperationOutcomeFromError(err)

Helpers core.IsNotFound(err) and core.IsConflict(err) are available for branching in handlers.

See doc.go for the full API, write pipeline, bundle rules, and integration details.

Documentation

Overview

Package core implements haistack-core, the FHIR runtime kernel for haistack.

haistack-core owns resource lifecycle rules for CRUD, per-resource history, OperationOutcome mapping, and transaction-bundle execution while remaining storage- and transport-agnostic. It sits between HTTP/gRPC handlers (future) and pkg/store adapters (pkg/sqlite, pkg/postgres) without importing either backend.

Design principles

Storage-agnostic orchestration:

  • ResourceService depends on store.ResourceStore, store.HistoryStore, and store.WriteSessionProvider — never on concrete database packages.
  • Reads use connection-scoped stores; writes use WriteSession for atomicity.
  • Version assignment, meta mutation, and hash recomputation happen in core, not in store adapters (except postgres.ApplyWrite convenience path, which core does not use).

Canonical JSON first:

  • Incoming payloads are normalized through pkg/types before lifecycle logic.
  • Create, update, and delete recompute meta.versionId, meta.lastUpdated, and ResourceEnvelope.Hash after metadata mutation.
  • types.ResourceEnvelope.JSON remains the source of truth for content.

Optional collaborators:

  • validate.Validator — structural or profile checks before ID/version mutation.
  • search.Indexer — produces store.SearchIndexEntry values on successful writes.
  • sync.Outbox — when configured, appends store.ResourceEvent on successful writes.
  • Omitted collaborators are no-ops; writes proceed without validation, indexing, or event emission.

Typed errors, not dual returns:

  • Service methods return (*types.ResourceEnvelope, error) or error.
  • Callers map errors to FHIR OperationOutcome via OperationOutcomeFromError.
  • ErrorKind values align with FHIR issue codes: invalid, conflict, not-found, not-supported, and exception.

ResourceService

ResourceService is the primary entry point. Construct with NewResourceService and ResourceServiceConfig:

Required dependencies:

  • Resources — store.ResourceStore for Read and Exists checks outside sessions.
  • History — store.HistoryStore for per-resource History reads.
  • Sessions — store.WriteSessionProvider (for example sqlite.DB or postgres.TenantDB).
  • IDPolicy — ResourceIDPolicy; defaults to DefaultIDPolicy when nil.
  • Codec — types.ResourceCodec; defaults to types.NewJSONCodec() when nil.

Optional dependencies:

  • Validator — validate.Validator invoked before write-side ID/version mutation.
  • Indexer — search.Indexer invoked after resource/history persistence in session.
  • Outbox — sync.Outbox; when non-nil, events are appended via sync.WithWriteSession during each write (transactional through session EventStore).
  • Hooks — optional four-point intercept SPI; core runs pre-storage before persist and post-commit after a successful session commit.
  • EnforceReferentialIntegrity — HAPI-style enforceReferentialIntegrityOnWrite; nil or true (NewResourceService default) runs the write-time Exists check; false skips checkReferentialIntegrity.

Methods:

  • Create(ctx, resource) — requires resourceType; accepts caller id or generates one; rejects duplicate current resources as conflict.
  • Read(ctx, resourceType, id) — returns current state or not-found.
  • Update(ctx, resource) — requires resourceType and id; requires existing resource.
  • Delete(ctx, resourceType, id) — reads current resource first so tombstone history and outbox events carry the content hash; assigns a new tombstone versionId.
  • History(ctx, resourceType, id) — returns ordered immutable ResourceVersion entries.
  • ProcessTransactionBundle(ctx, bundle) — executes type=transaction bundles atomically.

Write pipeline

Every successful write inside a WriteSession:

  1. Normalize and parse incoming JSON (types + codec).
  2. Validate with optional Validator.
  3. Resolve or generate id via ResourceIDPolicy.
  4. Optional pre-storage (if configured; no-op when hooks are nil).
  5. Enforce referential integrity for local typed relative references (types.GetReferences + ResourceStore.Exists) unless EnforceReferentialIntegrity is false. Contained fragments, absolute URLs, untyped ids, unresolved URNs, and self-references are skipped. Intra-bundle POST/PUT identities satisfy Exists so transaction entry order does not matter. Matching urn:uuid fullUrl values are rewritten to the target entry Type/id before this check and persist.
  6. Generate a new versionId (UUID) and set meta.versionId / meta.lastUpdated.
  7. Recompute normalized JSON and hash.
  8. Persist current resource state (create, update, or delete).
  9. Append immutable history entry (ResourceVersion).

10. Append outbox event when Outbox is configured (via sync.WithWriteSession).

11. Rebuild search index entries when Indexer is configured.

12. Commit session; rollback on any failure before commit.

Persist preparation (prepareWrite) is always pre-storage, then referential integrity, then version meta, so a pre-storage rewrite can satisfy Exists and integrity cannot run first.

Delete path reads the current envelope before removal so history tombstones and events reference the last known content hash while receiving a new tombstone versionId.

Transaction bundles

ProcessTransactionBundle supports only:

  • Bundle.resourceType = "Bundle"
  • Bundle.type = "transaction"
  • Entry methods: POST, PUT, DELETE
  • POST url format: ResourceType
  • PUT and DELETE url format: ResourceType/id

Rejected with not-supported:

  • batch and other bundle types
  • PATCH, GET, and other HTTP methods
  • conditional URLs (query strings in request url)

Entries execute in order inside one WriteSession. Referential integrity treats POST/PUT identities from every entry as already present, so an Observation may precede the Patient it references in the same bundle. Matching urn:uuid fullUrl values are rewritten to the target entry's Type/id in stored resource JSON (Patient/{assigned-id}) before persist. The response is a transaction-response Bundle envelope with per-entry status, location, etag, and lastModified.

Resource ID policy

ResourceIDPolicy defines Validate(resourceType, id) and Generate(resourceType). DefaultIDPolicy accepts ids matching FHIR id syntax ([A-Za-z0-9\-\.]{1,64}) and generates UUIDs when the caller omits an id on create.

Errors and OperationOutcome

ServiceError carries Kind, Message, optional Expression paths, and an optional Cause. KindOf, IsNotFound, and IsConflict classify errors for handlers.

OperationOutcomeFromError maps ServiceError (including wrapped errors) to types.OperationOutcome with a single OperationIssue. Unrecognized errors map to exception severity/code.

Integration with other packages

pkg/types — ResourceEnvelope, JSONCodec, NormalizeJSON, SetMeta, HashResource. pkg/store — storage contracts and WriteSession for atomic writes. pkg/validate — optional Validator before writes. pkg/search — optional Indexer producing SearchIndexEntry values. pkg/sync — optional Outbox and WithWriteSession for transactional event append. pkg/sqlite — embedded local WriteSessionProvider (wired by application layer). pkg/postgres — tenant-scoped WriteSessionProvider (wired by application layer).

Typical flows

Single resource create:

svc, _ := core.NewResourceService(core.ResourceServiceConfig{
    Resources: db.ResourceStore(),
    History:   db.HistoryStore(),
    Sessions:  db,
    Outbox:    &sync.EventStoreOutbox{Events: db.OutboxStore()},
})
created, err := svc.Create(ctx, &types.ResourceEnvelope{
    ResourceType: "Patient",
    JSON:         patientJSON,
})

Error to OperationOutcome:

if err != nil {
    outcome := core.OperationOutcomeFromError(err)
    // marshal outcome as FHIR JSON response
}

Transaction bundle:

resp, err := svc.ProcessTransactionBundle(ctx, bundleEnvelope)

File layout

  • doc.go — package documentation (this file)
  • service.go — ResourceService, write pipeline, CRUD, History
  • bundle.go — ProcessTransactionBundle and entry execution
  • errors.go — ServiceError, ErrorKind, classification helpers
  • operation_outcome.go — OperationOutcomeFromError
  • id_policy.go — ResourceIDPolicy, DefaultIDPolicy

Testing

core_test.go contains unit tests with in-memory store doubles covering CRUD, history, conflict rollback, optional collaborator failures, bundle execution, and OperationOutcome mapping.

integration_sqlite_test.go and integration_postgres_test.go exercise ResourceService against real sqlite and postgres backends (postgres skips when Docker/DSN unavailable).

service_internal_test.go contains package-internal tests for outbox wiring.

Out of scope (MVP)

CapabilityStatement generation, conditional create/update, FHIR Patch, batch bundles, custom operations, system-wide _history, search/query execution, authentication, authorization, subscription delivery, and HTTP routing. Per-resource history only; no _history endpoint semantics in this increment.

Index

Constants

This section is empty.

Variables

View Source
var DefaultEverythingTypes = []string{
	"Patient",
	"Observation",
	"Encounter",
	"Condition",
	"Procedure",
	"MedicationRequest",
	"MedicationStatement",
	"AllergyIntolerance",
	"Immunization",
	"DiagnosticReport",
	"DocumentReference",
	"Appointment",
	"CarePlan",
	"Goal",
	"ServiceRequest",
	"QuestionnaireResponse",
	"RelatedPerson",
	"Coverage",
	"Claim",
	"ExplanationOfBenefit",
	"Task",
	"Provenance",
}

DefaultEverythingTypes is the Patient compartment type list used when _type is omitted.

Functions

func FilterHistory

func FilterHistory(versions []store.ResourceVersion, q HistoryQuery) []store.ResourceVersion

FilterHistory applies FHIR instance-history _since and _at filters. Versions are assumed oldest-first. _since keeps versions created at or after that instant. _at keeps the version that was current at that instant.

func IsConflict

func IsConflict(err error) bool

IsConflict reports whether err is a conflict service error.

func IsNotFound

func IsNotFound(err error) bool

IsNotFound reports whether err is a not-found service error.

func OperationOutcomeFromError

func OperationOutcomeFromError(err error) *types.OperationOutcome

OperationOutcomeFromError maps a haistack-core error to a FHIR OperationOutcome.

func PatientCompartmentSearchParam

func PatientCompartmentSearchParam(resourceType string) string

PatientCompartmentSearchParam returns the primary search parameter that scopes resourceType to one Patient, or empty if the type is not in the compartment.

func PatientCompartmentSearchParams

func PatientCompartmentSearchParams(resourceType string) []string

PatientCompartmentSearchParams returns every Patient-compartment search parameter for resourceType (for example Observation subject and performer).

Types

type DefaultIDPolicy

type DefaultIDPolicy struct{}

DefaultIDPolicy accepts FHIR-constrained IDs and generates UUIDs when omitted.

func (DefaultIDPolicy) Generate

func (DefaultIDPolicy) Generate(_ string) (string, error)

Generate returns a new UUID suitable for use as a FHIR resource id.

func (DefaultIDPolicy) Validate

func (DefaultIDPolicy) Validate(_ string, id string) error

Validate checks that id satisfies FHIR id syntax.

type DefinitionIngestor

type DefinitionIngestor interface {
	InstallDefinition(ctx context.Context, jsonData []byte, provenance registry.InstallProvenance) error
	CompletePackageInstall(ctx context.Context, provenance registry.InstallProvenance) error
	DeleteDefinition(ctx context.Context, canonicalURL, version string) error
}

DefinitionIngestor installs FHIR definition resources into the registry catalog.

type ErrorKind

type ErrorKind string

ErrorKind classifies haistack-core service errors for OperationOutcome mapping.

const (
	// ErrorKindInvalid indicates the request or resource failed validation or syntax checks.
	ErrorKindInvalid ErrorKind = "invalid"
	// ErrorKindConflict indicates a duplicate create or version conflict.
	ErrorKindConflict ErrorKind = "conflict"
	// ErrorKindNotFound indicates the target resource does not exist.
	ErrorKindNotFound ErrorKind = "not-found"
	// ErrorKindNotSupported indicates the requested operation or bundle shape is not implemented.
	ErrorKindNotSupported ErrorKind = "not-supported"
	// ErrorKindPrecondition indicates an If-Match or other request precondition failed.
	ErrorKindPrecondition ErrorKind = "precondition-failed"
	// ErrorKindGone indicates the requested version exists in history but was deleted.
	ErrorKindGone ErrorKind = "deleted"
	// ErrorKindException indicates an unexpected or storage-layer failure.
	ErrorKindException ErrorKind = "exception"
)

func KindOf

func KindOf(err error) ErrorKind

KindOf returns the ErrorKind for err when it is or wraps a ServiceError. Unrecognized errors return ErrorKindException.

type EverythingQuery

type EverythingQuery struct {
	Types  []string
	Since  time.Time // resource meta.lastUpdated (_since)
	Start  time.Time // care-date lower bound (start)
	End    time.Time // care-date upper bound (end)
	Count  int
	Offset int
}

EverythingQuery configures Patient/$everything collection.

type HistoryQuery

type HistoryQuery struct {
	Since *time.Time
	At    *time.Time
}

HistoryQuery filters instance history by FHIR _since / _at.

type ResourceIDPolicy

type ResourceIDPolicy interface {
	// Validate checks that id is acceptable for resourceType.
	Validate(resourceType, id string) error
	// Generate returns a new id when the caller omits one on create.
	Generate(resourceType string) (string, error)
}

ResourceIDPolicy validates and generates FHIR resource IDs.

type ResourceService

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

ResourceService implements haistack-core FHIR resource lifecycle operations.

Use NewResourceService to construct a service. All write paths run inside store.WriteSession for atomic persistence of resource, history, index, and events.

func NewResourceService

func NewResourceService(cfg ResourceServiceConfig) (*ResourceService, error)

NewResourceService constructs a ResourceService with required dependencies.

func (*ResourceService) Create

Create persists a new resource, assigning an ID and version when needed.

func (*ResourceService) Delete

func (s *ResourceService) Delete(ctx context.Context, resourceType, id string) error

Delete removes the current resource and records a tombstone history entry.

func (*ResourceService) DeleteIfMatch

func (s *ResourceService) DeleteIfMatch(ctx context.Context, resourceType, id, expectedVersion string) error

DeleteIfMatch removes a resource only when expectedVersion still matches the persisted version. The comparison and delete occur in one write session.

func (*ResourceService) Everything

func (s *ResourceService) Everything(ctx context.Context, patientID string, q EverythingQuery) ([]*types.ResourceEnvelope, error)

Everything returns the Patient and resources in that patient's compartment.

func (*ResourceService) History

func (s *ResourceService) History(ctx context.Context, resourceType, id string) ([]store.ResourceVersion, error)

History returns immutable version history for one resource.

func (*ResourceService) Patch

func (s *ResourceService) Patch(ctx context.Context, resourceType, id string, patchJSON []byte) (*types.ResourceEnvelope, error)

Patch applies a JSON Patch (RFC 6902) or FHIR Patch Parameters document to an existing resource. JSON Patch bodies are arrays; FHIR Patch bodies are Parameters resources.

func (*ResourceService) PatchIfMatch

func (s *ResourceService) PatchIfMatch(ctx context.Context, resourceType, id string, patchJSON []byte, expectedVersion string) (*types.ResourceEnvelope, error)

PatchIfMatch applies JSON Patch or FHIR Patch and commits it only when expectedVersion still matches the current resource version.

func (*ResourceService) ProcessBatchBundle

func (s *ResourceService) ProcessBatchBundle(ctx context.Context, bundle *types.ResourceEnvelope) (*types.ResourceEnvelope, error)

ProcessBatchBundle executes a FHIR batch bundle. Each entry is processed independently; failures do not roll back successful entries.

func (*ResourceService) ProcessTransactionBundle

func (s *ResourceService) ProcessTransactionBundle(ctx context.Context, bundle *types.ResourceEnvelope) (*types.ResourceEnvelope, error)

ProcessTransactionBundle executes a FHIR transaction bundle atomically.

Only Bundle.type=transaction with POST, PUT, and DELETE entries is supported. Returns a transaction-response Bundle envelope or an error that fails the whole bundle.

func (*ResourceService) Read

func (s *ResourceService) Read(ctx context.Context, resourceType, id string) (*types.ResourceEnvelope, error)

Read returns the current state of a resource.

func (*ResourceService) ResourceStore

func (s *ResourceService) ResourceStore() store.ResourceStore

ResourceStore returns the underlying resource store for adapters that need store access.

func (*ResourceService) Update

Update replaces an existing resource with a new version.

func (*ResourceService) UpdateIfMatch

func (s *ResourceService) UpdateIfMatch(ctx context.Context, resource *types.ResourceEnvelope, expectedVersion string) (*types.ResourceEnvelope, error)

UpdateIfMatch replaces a resource only when expectedVersion still matches the persisted version. The comparison and update occur in one write session.

func (*ResourceService) VRead

func (s *ResourceService) VRead(ctx context.Context, resourceType, id, versionID string) (*types.ResourceEnvelope, error)

VRead returns a specific historical version of a resource. Deleted versions return ErrorKindGone (HTTP 410).

type ResourceServiceConfig

type ResourceServiceConfig struct {
	Resources store.ResourceStore
	History   store.HistoryStore
	Sessions  store.WriteSessionProvider
	IDPolicy  ResourceIDPolicy
	Codec     types.ResourceCodec

	Validator               validate.Validator
	Indexer                 search.Indexer
	Outbox                  hasync.Outbox
	Terminology             store.TerminologyStore
	TerminologyScope        string
	GlobalTerminologyScope  string
	TerminologySourceModule string
	TerminologyCache        terminology.Invalidator
	DefinitionIngestor      DefinitionIngestor
	ConformanceRefresh      func(ctx context.Context) error
	Hooks                   hooks.Hooks

	// EnforceReferentialIntegrity is the HAPI-style
	// enforceReferentialIntegrityOnWrite toggle. Nil (the zero value) enables
	// the check, matching NewResourceService's default. Set to a pointer to
	// false to skip checkReferentialIntegrity on write.
	EnforceReferentialIntegrity *bool
}

ResourceServiceConfig configures a ResourceService.

Resources, History, and Sessions are required. IDPolicy and Codec default when nil. Validator, Indexer, Outbox, and Hooks are optional no-ops when nil.

type ServiceError

type ServiceError struct {
	Kind       ErrorKind
	Message    string
	Expression []string
	Cause      error
}

ServiceError is a typed haistack-core error.

func (*ServiceError) Error

func (e *ServiceError) Error() string

func (*ServiceError) Unwrap

func (e *ServiceError) Unwrap() error

Jump to

Keyboard shortcuts

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