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:
- Normalize and parse incoming JSON (types + codec).
- Validate with optional Validator.
- Resolve or generate id via ResourceIDPolicy.
- Optional pre-storage (if configured; no-op when hooks are nil).
- 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.
- Generate a new versionId (UUID) and set meta.versionId / meta.lastUpdated.
- Recompute normalized JSON and hash.
- Persist current resource state (create, update, or delete).
- 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 ¶
- Variables
- func FilterHistory(versions []store.ResourceVersion, q HistoryQuery) []store.ResourceVersion
- func IsConflict(err error) bool
- func IsNotFound(err error) bool
- func OperationOutcomeFromError(err error) *types.OperationOutcome
- func PatientCompartmentSearchParam(resourceType string) string
- func PatientCompartmentSearchParams(resourceType string) []string
- type DefaultIDPolicy
- type DefinitionIngestor
- type ErrorKind
- type EverythingQuery
- type HistoryQuery
- type ResourceIDPolicy
- type ResourceService
- func (s *ResourceService) Create(ctx context.Context, resource *types.ResourceEnvelope) (*types.ResourceEnvelope, error)
- func (s *ResourceService) Delete(ctx context.Context, resourceType, id string) error
- func (s *ResourceService) DeleteIfMatch(ctx context.Context, resourceType, id, expectedVersion string) error
- func (s *ResourceService) Everything(ctx context.Context, patientID string, q EverythingQuery) ([]*types.ResourceEnvelope, error)
- func (s *ResourceService) History(ctx context.Context, resourceType, id string) ([]store.ResourceVersion, error)
- func (s *ResourceService) Patch(ctx context.Context, resourceType, id string, patchJSON []byte) (*types.ResourceEnvelope, error)
- func (s *ResourceService) PatchIfMatch(ctx context.Context, resourceType, id string, patchJSON []byte, ...) (*types.ResourceEnvelope, error)
- func (s *ResourceService) ProcessBatchBundle(ctx context.Context, bundle *types.ResourceEnvelope) (*types.ResourceEnvelope, error)
- func (s *ResourceService) ProcessTransactionBundle(ctx context.Context, bundle *types.ResourceEnvelope) (*types.ResourceEnvelope, error)
- func (s *ResourceService) Read(ctx context.Context, resourceType, id string) (*types.ResourceEnvelope, error)
- func (s *ResourceService) ResourceStore() store.ResourceStore
- func (s *ResourceService) Update(ctx context.Context, resource *types.ResourceEnvelope) (*types.ResourceEnvelope, error)
- func (s *ResourceService) UpdateIfMatch(ctx context.Context, resource *types.ResourceEnvelope, expectedVersion string) (*types.ResourceEnvelope, error)
- func (s *ResourceService) VRead(ctx context.Context, resourceType, id, versionID string) (*types.ResourceEnvelope, error)
- type ResourceServiceConfig
- type ServiceError
Constants ¶
This section is empty.
Variables ¶
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 ¶
IsConflict reports whether err is a conflict service error.
func IsNotFound ¶
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 ¶
PatientCompartmentSearchParam returns the primary search parameter that scopes resourceType to one Patient, or empty if the type is not in the compartment.
func PatientCompartmentSearchParams ¶
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.
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" )
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 ¶
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 ¶
func (s *ResourceService) Create(ctx context.Context, resource *types.ResourceEnvelope) (*types.ResourceEnvelope, error)
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 ¶
func (s *ResourceService) Update(ctx context.Context, resource *types.ResourceEnvelope) (*types.ResourceEnvelope, error)
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 ¶
ServiceError is a typed haistack-core error.
func (*ServiceError) Error ¶
func (e *ServiceError) Error() string
func (*ServiceError) Unwrap ¶
func (e *ServiceError) Unwrap() error