http

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

README

haistack-http (pkg/http)

FHIR REST API adapter for the haistack monorepo.

What it does

haistack-http is the HTTP transport layer for HAIStack. It exposes a FHIR REST surface over existing services without absorbing lifecycle, storage, indexing, sync, or AI behavior.

Concern Owner
HTTP routing and method validation pkg/http
Request/response JSON and XML translation pkg/http
OperationOutcome error rendering pkg/http
CapabilityStatement from registry snapshot pkg/http
Pluggable auth middleware and SMART scope filters pkg/http
CRUD, history, transaction bundles pkg/core
Search planning and execution pkg/search
Enabled resource types and SearchParameters pkg/registry
Policy decisions pkg/auth

Entrypoints include NewHandler(Config), optional NewRootHandlerWithSyncMiddleware for sync routes, and health probes /health and /healthz.

It does not:

  • Open databases or manage tenants (pkg/sqlite, pkg/postgres)
  • Index resources or compile search plans (pkg/search write path)
  • Validate profiles or assign version IDs (pkg/core, pkg/types)
  • Issue or validate SMART/OAuth tokens (pkg/smart, pkg/oauth) — callers wire token resolution into PrincipalResolver

How it fits in the ecosystem

  Client (FHIR REST, Bulk Data, SDC ops)
           |
           v
  pkg/http (router, negotiation, errors, auth middleware)
           |
     +-----+-----+-----+-----+
     v     v     v     v     v
  core  search registry auth  optional: bulk, SDC, terminology, sync hub
     |     |       |
     v     v       v
  store backends (sqlite / postgres TenantDB)
Direction Package Relationship
Downstream core ResourceService — CRUD, history, transaction/batch, patch
Downstream search SearchService — type search and POST _search
Downstream registry CapabilitySource — /metadata
Downstream auth AuthChecker, patient scope via PatientReferenceResolver
Downstream sync Optional /sync/push, /sync/pull when hub middleware wired
Optional export / bulkimport Bulk Data $export / $import services
Optional hooks Four-point SPI on Config.Hooks

When to use it

  • Serving a FHIR REST API from a Go binary or sidecar
  • Integration tests that exercise end-to-end JSON translation over real stores
  • Wiring SMART, API-key, or service-account auth via PrincipalResolver without changing core/search APIs
  • Exposing terminology, SDC, measure evaluation, or bulk operations through optional service interfaces

Import alias

This package is named http and shadows the standard library. Always import with an alias:

import (
    nethttp "net/http"

    hahttp "github.com/degoke/haistack/pkg/http"
)

Usage modes

1. Minimal handler (CRUD only)
handler, err := hahttp.NewHandler(hahttp.Config{
    ResourceService: hahttp.CoreResourceService{Svc: coreSvc},
})
if err != nil {
    log.Fatal(err)
}
nethttp.ListenAndServe(":8080", handler)

Without SearchService or CapabilitySource, type-level search and /metadata return not-supported outcomes.

2. Full stack (CRUD + search + metadata + auth)
snapshot, _ := manager.RebuildSnapshot(ctx)

handler, err := hahttp.NewHandler(hahttp.Config{
    BasePath:         "/fhir",
    ResourceService:  hahttp.CoreResourceService{Svc: coreSvc},
    SearchService:    hahttp.SearchServiceAdapter{Svc: searchSvc},
    CapabilitySource: hahttp.RegistryCapabilitySource{Snapshot: snapshot},
    ServerMetadata: hahttp.ServerMetadata{
        SoftwareName:    "my-fhir-server",
        SoftwareVersion: "1.0.0",
        ServerName:      "Production FHIR Server",
    },
    PrincipalResolver: func(ctx context.Context, r *nethttp.Request) (auth.Principal, auth.TenantContext, error) {
        return principal, tenant, nil
    },
    AuthChecker: hahttp.PolicyAuthChecker{Engine: authEngine},
})

When PrincipalResolver and AuthChecker are both set, built-in middleware runs before handlers. Set AuthMiddleware instead for fully custom wrapping.

3. Bulk Data, SDC, and terminology extensions

Wire optional services on Config:

handler, err := hahttp.NewHandler(hahttp.Config{
    ResourceService:        hahttp.CoreResourceService{Svc: coreSvc},
    BulkExportService:      exportSvc,
    BulkImportService:      importSvc,
    SDCService:             sdcAdapter,
    MeasureEvaluateService: measureSvc,
    TerminologyService:     terminologySvc,
    TerminologyScope:       tenantID,
    ValidateService:        validateAdapter,
})

When a service is nil, related routes return FHIR OperationOutcome with not-supported or not-implemented semantics.

4. Sync hub routes with authentication
root, err := hahttp.NewRootHandlerWithSyncMiddleware(hahttp.RootConfig{
    FHIR:           fhirHandler,
    Hub:            scopedHub, // implements sync.ScopedHubServer
    SyncMiddleware: authMiddleware,
})

Expose POST /sync/push and GET /sync/pull. Pull defaults to 100 events; limit query accepts 1–1000.

5. Custom service implementations (mocks and alternate backends)

Implement narrow interfaces directly:

type myResources struct{}

func (m myResources) Create(ctx context.Context, resource *types.ResourceEnvelope) (*types.ResourceEnvelope, error) { ... }
func (m myResources) Read(ctx context.Context, resourceType, id string) (*types.ResourceEnvelope, error) { ... }
// Update, Delete, History, ProcessTransactionBundle, ProcessBatchBundle, Patch
6. Rate limiting and hooks
handler, err := hahttp.NewHandler(hahttp.Config{
    ResourceService: hahttp.CoreResourceService{Svc: coreSvc},
    RateLimit: hahttp.RateLimitConfig{
        Requests: 1000,
        Window:   time.Minute,
    },
    Hooks: myHooks, // implements hooks.Hooks
})

Process-local limiter emits 429 with Retry-After; use a shared edge limiter for multi-instance deployments.

Examples

Patient compartment read:

GET /fhir/Patient/{id}/$everything
Accept: application/fhir+json

Conditional update:

PUT /fhir/Patient?identifier=system|value
If-Match: W/"version-id"

Async bulk export kickoff:

GET /fhir/Patient/$export
Prefer: respond-async

Returns 202 with Content-Location when BulkExportService is configured.

SMART scope filter enforcement:

handler, err := hahttp.NewHandler(hahttp.Config{
    AuthBundleResolver: smartResolver,
    ScopeFilterMatcher: smart.DefaultScopeFilterMatcher(),
    // PrincipalResolver + AuthChecker …
})

Supported endpoints (MVP)

Base path defaults to /fhir (configurable via Config.BasePath).

Method Path Action Success
GET /fhir/metadata Server capability statement 200 + CapabilityStatement
POST /fhir Transaction or batch bundle 200 + response Bundle
GET /fhir/{ResourceType} Type-level search 200 + searchset Bundle
POST /fhir/{ResourceType}/_search POST search 200 + searchset Bundle
POST /fhir/{ResourceType} Create (or conditional create) 201 or 200 + resource
PUT /fhir/{ResourceType}?... Conditional update 201/200 + resource
DELETE /fhir/{ResourceType}?... Conditional delete 204 No Content
GET /fhir/{ResourceType}/{id} Read resource 200 + resource, ETag, Last-Modified
PUT /fhir/{ResourceType}/{id} Update resource 200 + resource
PATCH /fhir/{ResourceType}/{id} JSON Patch or FHIR Patch 200 + resource
DELETE /fhir/{ResourceType}/{id} Delete resource 204 No Content
GET /fhir/{ResourceType}/{id}/_history Instance history (_since, _at) 200 + history Bundle
GET /fhir/{ResourceType}/{id}/_history/{vid} vread 200 + resource, 410 if deleted
GET /fhir/Patient/{id}/$everything Patient compartment bundle 200 + searchset Bundle
Bulk $export / $import various Async bulk data 202 / 200 / 404
Measure $evaluate-measure type and instance CQF evaluation 200 + MeasureReport
SDC on Questionnaire / QuestionnaireResponse $populate, $assemble, … SDC adapter 200 or OperationOutcome
POST / GET /sync/push, /sync/pull Sync hub (optional middleware) 200

JSON projections (_summary, _elements) and JSON/XML content negotiation are supported. Unsupported Accept or _format values return 406.

Deferred / requires wiring
  • Full CapabilityStatement conformance coverage for every optional service
  • SMART metadata and built-in token runtime (use pkg/smart + resolver)
  • Services nil → route-level not-supported responses

Configuration reference

Field Required Default Description
BasePath no /fhir FHIR REST root path
ResourceService yes — CRUD, history, transaction/batch bundles, JSON Patch
SearchService no nil Enables GET /{type} search
CapabilitySource no nil Enables GET /metadata
ServerMetadata no empty Software/server fields in CapabilityStatement
Codec no types.NewJSONCodec() FHIR JSON parse/serialize
AuthMiddleware no nil Custom outer middleware
PrincipalResolver no nil Identity extraction when auth enabled
AuthChecker no nil Read/write/search/export authorization
AuthBundleResolver no nil SMART 2.2 scope filter context
PatientReferenceResolver no nil Patient-scoped read/search enforcement
SDCService no nil SDC operations
MeasureEvaluateService no nil Measure/$evaluate-measure
BulkExportService / BulkImportService no nil Bulk Data
TerminologyService no nil $lookup, $expand, $validate-code
OperationService no nil Custom $operation
RateLimit no disabled Process-local fixed-window limiter
Hooks no nil Incoming/outgoing HTTP + core storage hooks

Error responses

Handler failures return negotiated FHIR JSON or XML OperationOutcome bodies.

Source HTTP status Issue code (typical)
core.ErrorKindInvalid 400 invalid
core.ErrorKindNotFound 404 not-found
core.ErrorKindConflict 409 conflict
core.ErrorKindNotSupported 400 not-supported
core.ErrorKindException 500 exception
search.ErrInvalidQuery and related 400 invalid
auth.ErrDenied 403 forbidden
Missing credentials (auth enabled) 401 security
Unsupported HTTP method 405 not-supported
Rate limit exceeded 429 throttled

Response headers

Header When set
Content-Type: application/fhir+json / application/fhir+xml Negotiated FHIR responses
Location 201 Created
ETag: W/"{versionId}" Read/update when version metadata present
Last-Modified Read/update when LastUpdated present

Auth integration

PolicyAuthChecker delegates to auth.PolicyEngine:

  • Read → CanReadResource
  • Write (create/update/delete) → CanWriteResource
  • Search → CanReadResource on the resource type
  • Export → CanBulkExport when bulk export is configured

For SMART-backed servers, resolve tokens in PrincipalResolver and optionally use pkg/smart.AuthAdapter to build auth.ReadRequest / auth.WriteRequest inside a custom AuthChecker.

Package layout

File Role
config.go NewHandler, Config, auth types
service.go ResourceService, SearchService, CapabilitySource
adapter.go Adapters for core, search, registry, auth
handler.go Route dispatch and endpoint handlers
router.go Path parsing and ID validation
errors.go Error → status + OperationOutcome
writer.go Response writers and FHIR headers
bundle.go History, searchset, CapabilityStatement JSON
auth.go Built-in auth middleware
sync.go Sync root handler and middleware
bulk.go / bulk_import.go Bulk Data routes

Where it fits

Package Role
http Transport adapter (this package)
core Resource lifecycle
search Search execution
registry Capability metadata
auth / smart Authorization
sync Optional hub protocol over HTTP
runtime Typical wiring of all services into Config

Limits

  • No built-in OAuth authorization server — integrate pkg/oauth / pkg/smart externally
  • Rate limit is process-local unless supplemented at the gateway
  • CapabilityStatement reflects wired services; unwired operations appear absent or not-supported at runtime
  • XML support covers negotiated read/write paths; not every auxiliary admin route may expose XML
  • Sync routes require explicit middleware and registered hub nodes for Postgres tenants

Testing

go test ./pkg/http/... -count=1
  • Unit tests (http_test.go) — mock services for endpoints, auth paths, and error mapping
  • Integration tests (integration_test.go) — sqlite-backed core + search wired through adapters

Documentation

Overview

Package http implements haistack-http, the FHIR REST adapter for HAIStack.

haistack-http is a thin transport layer over pkg/core, pkg/search, pkg/registry, and optional pkg/auth. It owns HTTP routing, request/response translation, OperationOutcome rendering, CapabilityStatement metadata, and pluggable auth middleware. Resource lifecycle, persistence, indexing, sync, and AI logic remain in lower layers.

The handler also exposes unauthenticated /health and /healthz liveness probes. Readiness depends on the runtime successfully constructing the handler and its backing services.

Import this package with an alias because its name shadows net/http:

import (
    nethttp "net/http"
    hahttp "github.com/degoke/haistack/pkg/http"
)

Design principles

Transport-only adapter:

  • Handlers parse paths, query strings, and bodies into types.ResourceEnvelope or url.Values, then delegate to injected services.
  • No database, registry, or policy engine imports in handler logic beyond narrow interfaces and optional adapters.
  • Business rules (validation, versioning, indexing, transactions) stay in pkg/core and pkg/search.

Narrow dependency interfaces:

  • ResourceService — Create, Read, Update, Delete, History, transaction and batch bundle processing, and JSON Patch.
  • SearchService — SearchBundle.
  • CapabilitySource — CapabilitySnapshot for /metadata.
  • SDCService — optional SDC operation adapter for population, validation, assembly, extraction, and adaptive routes.
  • OperationService — optional generic custom-operation adapter.
  • AuthChecker — AuthorizeRead, AuthorizeWrite, AuthorizeSearch.

Concrete adapters (CoreResourceService, SearchServiceAdapter, RegistryCapabilitySource, PolicyAuthChecker) wire existing services without widening their public APIs.

FHIR-first responses:

  • Success and OperationOutcome responses negotiate application/fhir+json or application/fhir+xml from Accept or _format.
  • Failures map service, search, auth, and rate-limit errors to OperationOutcome resources with appropriate HTTP status codes.
  • Create responses include Location; read/update responses include ETag and Last-Modified when version metadata is available.

Public API

  • NewHandler(Config) (net/http.Handler, error) — constructs the FHIR REST handler tree.
  • Config — BasePath (default /fhir), ResourceService, optional SearchService, CapabilitySource, ServerMetadata, Codec, auth hooks, RateLimit, and Hooks.
  • ServerMetadata — software name/version and server description for CapabilityStatement generation.
  • PrincipalResolver — extracts auth.Principal and auth.TenantContext from a request.
  • AuthChecker — authorizes read, write, and search before handler dispatch.

Supported endpoints (MVP)

  • GET /fhir/metadata — CapabilityStatement
  • POST /fhir — transaction or batch Bundle
  • GET /fhir/{ResourceType} — type-level search (searchset Bundle)
  • POST /fhir/{ResourceType}/_search — POST search
  • POST /fhir/{ResourceType} — create (conditional create via search params / If-None-Exist)
  • PUT /fhir/{ResourceType}?... — conditional update
  • DELETE /fhir/{ResourceType}?... — conditional delete
  • GET /fhir/{ResourceType}/{id} — read
  • PUT /fhir/{ResourceType}/{id} — update
  • PATCH /fhir/{ResourceType}/{id} — JSON Patch or FHIR Patch
  • DELETE /fhir/{ResourceType}/{id} — delete (204 No Content)
  • GET /fhir/{ResourceType}/{id}/_history — history Bundle (_since, _at)
  • GET /fhir/{ResourceType}/{id}/_history/{vid} — vread (410 if deleted)
  • GET /fhir/Patient/{id}/$everything — patient compartment searchset
  • GET /fhir/$export — system bulk export kickoff (async; requires BulkExportService)
  • GET /fhir/Patient/$export and /fhir/Patient/{id}/$export — patient bulk export
  • POST /fhir/$import — system bulk import kickoff (async; requires BulkImportService)
  • GET /fhir/$import/status/{jobId} — import status polling / manifest
  • DELETE /fhir/$import/status/{jobId} — cancel import
  • GET /fhir/$import/files/{jobId}/{file} — download import error NDJSON
  • GET /fhir/Group/{id}/$export — group bulk export kickoff (async)
  • GET /fhir/$export/status/{jobId} — export status polling / manifest
  • DELETE /fhir/$export/status/{jobId} — cancel export
  • GET /fhir/$export/files/{jobId}/{file} — download NDJSON artifact
  • GET/POST /fhir/$operation and resource operation paths — custom operations
  • POST /sync/push, GET /sync/pull — optional sync hub routes via NewRootHandlerWithSyncMiddleware; pull defaults to 100 events and accepts limits from 1 through 1000
  • POST /fhir/Questionnaire/$populate, $assemble
  • GET/POST /fhir/Measure/{id}/$evaluate-measure — CQF MeasureReport
  • POST /fhir/{ResourceType}/$validate — FHIR Resource/$validate (OperationOutcome)
  • POST /fhir/QuestionnaireResponse/$validate, $extract — SDC operations
  • POST /fhir/Questionnaire/$next-question, $next, $answer (adaptive adapter)

Routing uses the Go standard library net/http ServeHTTP pattern; no third-party router is required.

Error mapping

Service errors from pkg/core are mapped via core.KindOf and core.OperationOutcomeFromError:

  • invalid → 400 Bad Request
  • not-found → 404 Not Found
  • deleted → 410 Gone
  • conflict → 409 Conflict
  • not-supported → 400 Bad Request
  • exception → 500 Internal Server Error

Search sentinel errors (ErrInvalidQuery, ErrUnknownParam, etc.) → 400. Auth denials → 403 Forbidden; missing credentials when auth is enabled → 401.

Auth

When PrincipalResolver and AuthChecker are both configured, built-in middleware resolves identity and authorizes each action before calling services. When auth is not configured, requests pass through unchanged.

Alternatively, set AuthMiddleware to wrap the handler with custom logic (for example SMART token validation). PolicyAuthChecker adapts auth.PolicyEngine; search authorization uses CanReadResource per resource type. Sync routes are mounted separately and do not inherit FHIR middleware; protect them with RootConfig.SyncMiddleware and use a scoped sync hub.

Typical usage

handler, err := hahttp.NewHandler(hahttp.Config{
    ResourceService:  hahttp.CoreResourceService{Svc: coreSvc},
    SearchService:    hahttp.SearchServiceAdapter{Svc: searchSvc},
    CapabilitySource: hahttp.RegistryCapabilitySource{Snapshot: snapshot},
    ServerMetadata: hahttp.ServerMetadata{
        SoftwareName:    "my-fhir-server",
        SoftwareVersion: "1.0.0",
    },
    PrincipalResolver: myResolver,
    AuthChecker:       hahttp.PolicyAuthChecker{Engine: authEngine},
})
if err != nil {
    log.Fatal(err)
}
nethttp.ListenAndServe(":8080", handler)

Out of scope (MVP)

  • BulkExportService — when nil, $export routes return 501
  • BulkImportService — when nil, $import routes return 501
  • Full CapabilityStatement conformance testing
  • SMART metadata, built-in OAuth2/SMART token runtime
  • gRPC or non-FHIR content types

See README.md in this directory for endpoint tables, wiring examples, and test guidance.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewHandler

func NewHandler(cfg Config) (http.Handler, error)

NewHandler constructs a FHIR REST http.Handler from Config.

func NewRateLimitMiddleware

func NewRateLimitMiddleware(cfg RateLimitConfig) func(http.Handler) http.Handler

NewRateLimitMiddleware returns middleware enforcing cfg at the HTTP edge. It deliberately runs outside authentication when installed by NewHandler, so unauthenticated traffic cannot consume expensive auth work indefinitely.

func NewRootHandler

func NewRootHandler(fhir http.Handler, sync hasync.HubServer) http.Handler

NewRootHandler combines the FHIR handler with optional sync routes.

func NewRootHandlerFromConfig

func NewRootHandlerFromConfig(cfg RootConfig) http.Handler

NewRootHandlerFromConfig builds a root handler from RootConfig.

func NewRootHandlerWithSyncMiddleware

func NewRootHandlerWithSyncMiddleware(fhir http.Handler, sync hasync.HubServer, syncMiddleware func(http.Handler) http.Handler) http.Handler

NewRootHandlerWithSyncMiddleware combines FHIR and sync routes and applies the supplied middleware to sync routes as well. This is the recommended constructor when FHIR auth is enabled; the two route trees do not otherwise share middleware automatically.

func NewSyncHandler

func NewSyncHandler(hub hasync.HubServer) http.Handler

NewSyncHandler exposes HAIStack sync push/pull endpoints expected by pkg/client.

func NotImplemented

func NotImplemented(path string) error

NotImplemented returns an error mapped to HTTP 501 by the HTTP adapter.

func SMARTBearerAuthMiddleware

func SMARTBearerAuthMiddleware(cfg smart.BearerAuthConfig) func(http.Handler) http.Handler

SMARTBearerAuthMiddleware validates Bearer JWTs and stores principal, tenant, and AuthBundle on the request context.

func ValidateSyncRequest

func ValidateSyncRequest(nodeID, tenantID string) error

ValidateSyncRequest rejects malformed node and tenant identifiers before a caller reaches a legacy hub implementation.

func WithHealthEndpoints

func WithHealthEndpoints(next nethttp.Handler, ready func() bool) nethttp.Handler

WithHealthEndpoints adds lightweight liveness and readiness probes around a runtime handler. The readiness callback should report whether the owner has completed startup and is still serving.

Types

type AuthBundleResolver

type AuthBundleResolver func(ctx context.Context, r *http.Request) (smart.AuthBundle, bool)

AuthBundleResolver optionally supplies a validated SMART AuthBundle for scope-filter enforcement.

func SMARTBackendAssertionBundleResolver

func SMARTBackendAssertionBundleResolver(cfg smart.BackendAssertionAuthConfig) AuthBundleResolver

SMARTBackendAssertionBundleResolver returns the AuthBundle from a validated backend assertion.

func SMARTBearerBundleResolver

func SMARTBearerBundleResolver(cfg smart.BearerAuthConfig) AuthBundleResolver

SMARTBearerBundleResolver returns the AuthBundle from a validated Bearer token.

type AuthChecker

type AuthChecker interface {
	AuthorizeRead(ctx context.Context, principal auth.Principal, tenant auth.TenantContext, resourceType, id string) (auth.Decision, error)
	AuthorizeWrite(ctx context.Context, principal auth.Principal, tenant auth.TenantContext, operation, resourceType, id string) (auth.Decision, error)
	AuthorizeSearch(ctx context.Context, principal auth.Principal, tenant auth.TenantContext, resourceType string) (auth.Decision, error)
	AuthorizeExport(ctx context.Context, principal auth.Principal, tenant auth.TenantContext, groupID string) (auth.Decision, error)
}

AuthChecker authorizes FHIR read, write, search, and bulk export actions.

type BulkExportService

type BulkExportService interface {
	Kickoff(ctx context.Context, req export.KickoffRequest) (*export.Job, error)
	GetJob(ctx context.Context, jobID string) (*export.Job, error)
	Cancel(ctx context.Context, jobID string) error
	Manifest(job *export.Job) *export.Manifest
	StatusURL(jobID string) string
	GetFile(ctx context.Context, jobID, filename string) ([]byte, string, error)
	OpenFile(ctx context.Context, jobID, filename string) (io.ReadCloser, string, error)
}

BulkExportService handles FHIR Bulk Data export kickoff, polling, cancellation, manifest retrieval, and artifact download.

type BulkImportService

type BulkImportService interface {
	Kickoff(ctx context.Context, req bulkimport.KickoffRequest) (*bulkimport.Job, error)
	GetJob(ctx context.Context, jobID string) (*bulkimport.Job, error)
	Cancel(ctx context.Context, jobID string) error
	Manifest(job *bulkimport.Job) *bulkimport.Manifest
	StatusURL(jobID string) string
	GetFile(ctx context.Context, jobID, filename string) ([]byte, string, error)
}

BulkImportService handles FHIR Bulk Data import kickoff, polling, cancellation, and error-artifact download.

type CapabilitySource

type CapabilitySource interface {
	CapabilitySnapshot() registry.CapabilitySnapshot
}

CapabilitySource returns the compiled registry capability snapshot for metadata.

type ConditionalResourceService

type ConditionalResourceService interface {
	UpdateIfMatch(ctx context.Context, resource *types.ResourceEnvelope, expectedVersion string) (*types.ResourceEnvelope, error)
	DeleteIfMatch(ctx context.Context, resourceType, id, expectedVersion string) error
	PatchIfMatch(ctx context.Context, resourceType, id string, patchJSON []byte, expectedVersion string) (*types.ResourceEnvelope, error)
}

ConditionalResourceService is implemented by services that can enforce If-Match atomically with the write. ResourceService remains intentionally small for adapters and test doubles that do not provide this extension.

type Config

type Config struct {
	// BasePath is the FHIR REST root path. Defaults to /fhir.
	BasePath string

	// ResourceService is required.
	ResourceService ResourceService

	// SearchService is optional; when nil, type-level GET search is unavailable.
	SearchService SearchService

	// SDCService is optional; when nil, SDC operation endpoints return
	// OperationOutcome with a not-supported error.
	SDCService SDCService

	// PackageInstallService handles ImplementationGuide/$install.
	// When nil, POST /fhir/ImplementationGuide/$install returns not-supported.
	PackageInstallService PackageInstallService

	// TerminologyService handles CodeSystem/$lookup, ValueSet/$expand, and
	// $validate-code when configured.
	TerminologyService TerminologyService

	// TerminologyScope is the tenant scope passed to terminology operations.
	TerminologyScope string

	// TerminologyInstallFactory resolves per-tenant opt-in stores for HTTP
	// terminology operations. When nil, wired default installs are used.
	TerminologyInstallFactory store.TerminologyInstallStoreFactory

	// DefaultTerminologyTenantID is the sync/default tenant when the request has
	// no authenticated tenant (single-tenant dev and startup installs).
	DefaultTerminologyTenantID string

	// TerminologyInstallService handles Basic/$terminology-install.
	TerminologyInstallService TerminologyInstallService

	// TerminologyEnableService handles Basic/$terminology-enable.
	TerminologyEnableService TerminologyEnableService

	// ModuleInstallService handles Basic/$install.
	ModuleInstallService ModuleInstallService

	// ModulePaths allowlists local directories accepted by Basic/$install.
	ModulePaths []string

	// JobStatusService handles Basic/{id}/$status job polling.
	JobStatusService JobStatusService

	// ConformanceRefresher rebuilds live conformance state via CapabilityStatement/$refresh.
	ConformanceRefresher ConformanceRefresher

	// OperationService handles non-SDC custom operations such as
	// $everything or implementation-specific operations.
	OperationService OperationService

	// MeasureEvaluateService handles Measure/$evaluate-measure.
	// When nil, GET/POST /fhir/Measure/$evaluate-measure returns not-implemented.
	MeasureEvaluateService MeasureEvaluateService

	// ValidateService handles FHIR Resource/$validate for non-SDC resource types.
	// When nil, POST /fhir/{type}/$validate returns not-supported.
	ValidateService ValidateService

	// CapabilitySource is optional; when nil, /metadata returns not-supported.
	CapabilitySource CapabilitySource

	// ServerMetadata enriches generated CapabilityStatement resources.
	ServerMetadata ServerMetadata

	// Codec parses and serializes FHIR JSON. Defaults to types.NewJSONCodec().
	Codec types.ResourceCodec

	// AuthMiddleware wraps the handler when set. When nil and PrincipalResolver
	// plus AuthChecker are configured, built-in auth middleware is used.
	AuthMiddleware func(http.Handler) http.Handler

	// PrincipalResolver extracts request identity when auth is enabled.
	PrincipalResolver PrincipalResolver

	// AuthChecker authorizes actions when auth is enabled.
	AuthChecker AuthChecker

	// AuthBundleResolver stores a SMART AuthBundle on the request context for
	// granular scope filter enforcement. Optional when hosts do not use SMART 2.2 filters.
	AuthBundleResolver AuthBundleResolver

	// ScopeFilterMatcher evaluates SMART 2.2 scope filters for this handler. When nil,
	// the package default from smart.SetScopeFilterMatcher is used.
	ScopeFilterMatcher smart.ScopeFilterMatcher

	// BulkExportService handles FHIR Bulk Data export when configured.
	BulkExportService BulkExportService

	// BulkImportService handles FHIR Bulk Data import when configured.
	BulkImportService BulkImportService

	// ViewMaterializeService handles ViewDefinition/$materialize when configured.
	ViewMaterializeService ViewMaterializeService

	// ViewRunService handles ViewDefinition/$viewdefinition-run when configured.
	ViewRunService ViewRunService

	// SQLQueryService handles Library/$sqlquery-run when configured.
	SQLQueryService SQLQueryService

	// ViewExportService handles ViewDefinition/$viewdefinition-export when configured.
	ViewExportService ViewExportService

	// PatientReferenceResolver resolves patient ownership for loaded resources when
	// TenantContext.PatientScope is set. Required for patient-scoped read/search enforcement.
	PatientReferenceResolver auth.ResourcePatientResolver

	// RateLimit enables process-local request limiting when Requests and Window
	// are configured. Use a distributed gateway limiter for multi-instance
	// deployments, or provide equivalent protection before this handler.
	RateLimit RateLimitConfig

	// Hooks is an optional four-point intercept SPI (incoming, pre-storage,
	// post-commit, outgoing). HTTP runs incoming after routing and outgoing
	// before a resource envelope is written. Core runs pre-storage and post-commit.
	Hooks hooks.Hooks
}

Config configures the FHIR HTTP handler.

type ConformanceRefresher

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

ConformanceRefresher rebuilds live conformance state after installs.

type ConformanceRuntime

type ConformanceRuntime interface {
	Snapshot() *registry.Snapshot
	Engine() validate.Engine
	Refresh(ctx context.Context) (*registry.Snapshot, error)
}

ConformanceRuntime is the hot-reloadable registry + validation view used by HTTP.

type CoreJobStatusService

type CoreJobStatusService struct {
	JobStore store.JobStore
}

CoreJobStatusService implements JobStatusService using store.JobStore.

func (CoreJobStatusService) GetJob

type CoreMeasureService

type CoreMeasureService struct {
	Engine    *cql.Engine
	Libraries cql.LibraryResolver
	Resources store.ResourceStore
	Retriever cql.Retriever
}

CoreMeasureService implements Measure/$evaluate-measure using pkg/cql.

func (CoreMeasureService) EvaluateMeasure

type CoreModuleInstallService

type CoreModuleInstallService struct {
	JobStore store.JobStore
}

CoreModuleInstallService implements module install using jobs.

func (CoreModuleInstallService) EnqueueInstall

func (s CoreModuleInstallService) EnqueueInstall(ctx context.Context, path string, upgradeOnly bool) (store.JobRecord, error)

type CorePackageInstallService

type CorePackageInstallService struct {
	JobStore store.JobStore
}

CorePackageInstallService implements package install using registry and jobs.

func (CorePackageInstallService) EnqueueArchiveInstall

func (s CorePackageInstallService) EnqueueArchiveInstall(ctx context.Context, packageID, version string, r io.Reader) (store.JobRecord, error)

func (CorePackageInstallService) EnqueueRegistryInstall

func (s CorePackageInstallService) EnqueueRegistryInstall(ctx context.Context, packageID, version string) (store.JobRecord, error)

type CoreResourceService

type CoreResourceService struct {
	Svc *core.ResourceService
}

CoreResourceService adapts *core.ResourceService to ResourceService.

func (CoreResourceService) Create

func (CoreResourceService) Delete

func (a CoreResourceService) Delete(ctx context.Context, resourceType, id string) error

func (CoreResourceService) DeleteIfMatch

func (a CoreResourceService) DeleteIfMatch(ctx context.Context, resourceType, id, expectedVersion string) error

func (CoreResourceService) Everything

func (CoreResourceService) History

func (a CoreResourceService) History(ctx context.Context, resourceType, id string) ([]store.ResourceVersion, error)

func (CoreResourceService) Patch

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

func (CoreResourceService) PatchIfMatch

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

func (CoreResourceService) ProcessBatchBundle

func (a CoreResourceService) ProcessBatchBundle(ctx context.Context, bundle *types.ResourceEnvelope) (*types.ResourceEnvelope, error)

func (CoreResourceService) ProcessTransactionBundle

func (a CoreResourceService) ProcessTransactionBundle(ctx context.Context, bundle *types.ResourceEnvelope) (*types.ResourceEnvelope, error)

func (CoreResourceService) Read

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

func (CoreResourceService) Update

func (CoreResourceService) UpdateIfMatch

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

func (CoreResourceService) VRead

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

type CoreSDCService

type CoreSDCService struct {
	Resources      *core.ResourceService
	Resolver       sdc.QuestionnaireResolver
	Provider       sdc.ExpressionProvider
	Terminology    sdc.TerminologyResolver
	Extractor      sdc.Extractor
	AdaptiveEngine sdc.AdaptiveEngine
	Elements       sdc.DefinitionElementResolver
}

CoreSDCService is the default runtime adapter. It reuses core persistence, store-backed canonical resolution, and caller-supplied SDC policies.

func (CoreSDCService) Adaptive

func (CoreSDCService) Assemble

func (CoreSDCService) Extract

func (CoreSDCService) Populate

func (CoreSDCService) Validate

type CoreTerminologyEnableService

type CoreTerminologyEnableService struct {
	InstallFactory  store.TerminologyInstallStoreFactory
	DefaultTenantID string
	Global          store.TerminologyStore
	Definitions     store.DefinitionStore
}

CoreTerminologyEnableService implements terminology catalog opt-in.

func (CoreTerminologyEnableService) Enable

type CoreTerminologyInstallService

type CoreTerminologyInstallService struct {
	JobStore     store.JobStore
	DefaultScope string
}

CoreTerminologyInstallService implements terminology rebuild using jobs.

func (CoreTerminologyInstallService) EnqueueRebuild

func (s CoreTerminologyInstallService) EnqueueRebuild(ctx context.Context, scopeID string, preExpandValueSets bool) (store.JobRecord, error)

type CoreValidateService

type CoreValidateService struct {
	Runtime   ConformanceRuntime
	Engine    validate.Engine
	Resources ResourceService
	Codec     types.ResourceCodec
	Options   validate.ValidateOptions
	Profiles  []string
}

CoreValidateService implements FHIR Resource/$validate using validate.Engine.

func (CoreValidateService) Validate

Validate runs profile validation and returns a FHIR OperationOutcome.

type DirectPackageInstallService

type DirectPackageInstallService struct {
	Installer *packages.Installer
}

DirectPackageInstallService runs package installs synchronously when no job store is wired.

func (DirectPackageInstallService) EnqueueArchiveInstall

func (s DirectPackageInstallService) EnqueueArchiveInstall(ctx context.Context, packageID, version string, r io.Reader) (store.JobRecord, error)

func (DirectPackageInstallService) EnqueueRegistryInstall

func (s DirectPackageInstallService) EnqueueRegistryInstall(ctx context.Context, packageID, version string) (store.JobRecord, error)

type JobStatusService

type JobStatusService interface {
	GetJob(ctx context.Context, id string) (*store.JobRecord, error)
}

JobStatusService reads durable background job state.

type LiveCapabilitySource

type LiveCapabilitySource struct {
	Runtime ConformanceRuntime
}

LiveCapabilitySource serves CapabilityStatement metadata from a hot-reloadable conformance runtime.

func (LiveCapabilitySource) CapabilitySnapshot

func (s LiveCapabilitySource) CapabilitySnapshot() registry.CapabilitySnapshot

CapabilitySnapshot implements CapabilitySource.

type LivePatientSearchParamResolver

type LivePatientSearchParamResolver struct {
	Runtime ConformanceRuntime
}

LivePatientSearchParamResolver resolves patient search scope from the current conformance snapshot on each request.

func (LivePatientSearchParamResolver) PatientSearchParameterCode

func (r LivePatientSearchParamResolver) PatientSearchParameterCode(resourceType string) (string, bool)

PatientSearchParameterCode implements auth.PatientSearchParamResolver.

type MeasureEvaluateRequest

type MeasureEvaluateRequest struct {
	ID    string
	Query url.Values
	Body  []byte
}

MeasureEvaluateRequest is the HTTP boundary for Measure/$evaluate-measure.

type MeasureEvaluateService

type MeasureEvaluateService interface {
	EvaluateMeasure(context.Context, MeasureEvaluateRequest) (*types.ResourceEnvelope, error)
}

MeasureEvaluateService runs CQF Measure/$evaluate-measure and returns a MeasureReport.

type ModuleInstallService

type ModuleInstallService interface {
	EnqueueInstall(ctx context.Context, path string, upgradeOnly bool) (store.JobRecord, error)
}

ModuleInstallService enqueues local module install jobs.

type OperationAuthChecker

type OperationAuthChecker interface {
	AuthorizeOperation(ctx context.Context, principal auth.Principal, tenant auth.TenantContext, resourceType, operation, id string) (auth.Decision, error)
}

OperationAuthChecker optionally authorizes named FHIR operations such as Basic/$status independently from resource read or write.

type OperationRequest

type OperationRequest struct {
	ResourceType string
	ID           string
	Operation    string
	Query        url.Values
	Body         []byte
}

OperationRequest is the generic FHIR operation boundary. Custom operation implementations own their Parameters validation and response type.

type OperationService

type OperationService interface {
	Execute(context.Context, OperationRequest) (*types.ResourceEnvelope, error)
}

type PackageInstallService

type PackageInstallService interface {
	EnqueueRegistryInstall(ctx context.Context, packageID, version string) (store.JobRecord, error)
	EnqueueArchiveInstall(ctx context.Context, packageID, version string, r io.Reader) (store.JobRecord, error)
}

PackageInstallService enqueues FHIR NPM package install jobs. Install jobs refresh conformance state automatically on completion.

type PatientScopedSearchService

type PatientScopedSearchService interface {
	SearchBundleForPatient(ctx context.Context, resourceType, patientID string, params url.Values) (*search.SearchBundle, error)
}

PatientScopedSearchService is required when the authenticated tenant is restricted to one patient. A regular SearchService cannot safely infer a patient filter from an auth decision, so the implementation must apply the restriction while planning/executing the search.

type PolicyAuthChecker

type PolicyAuthChecker struct {
	Engine auth.PolicyEngine
}

PolicyAuthChecker adapts auth.PolicyEngine to AuthChecker.

func (PolicyAuthChecker) AuthorizeExport

func (c PolicyAuthChecker) AuthorizeExport(ctx context.Context, principal auth.Principal, tenant auth.TenantContext, groupID string) (auth.Decision, error)

func (PolicyAuthChecker) AuthorizeRead

func (c PolicyAuthChecker) AuthorizeRead(ctx context.Context, principal auth.Principal, tenant auth.TenantContext, resourceType, id string) (auth.Decision, error)

func (PolicyAuthChecker) AuthorizeSearch

func (c PolicyAuthChecker) AuthorizeSearch(ctx context.Context, principal auth.Principal, tenant auth.TenantContext, resourceType string) (auth.Decision, error)

func (PolicyAuthChecker) AuthorizeWrite

func (c PolicyAuthChecker) AuthorizeWrite(ctx context.Context, principal auth.Principal, tenant auth.TenantContext, operation, resourceType, id string) (auth.Decision, error)

type PrincipalResolver

type PrincipalResolver func(ctx context.Context, r *http.Request) (auth.Principal, auth.TenantContext, error)

PrincipalResolver extracts the authenticated principal and tenant from a request.

func SMARTBackendAssertionPrincipalResolver

func SMARTBackendAssertionPrincipalResolver(cfg smart.BackendAssertionAuthConfig) PrincipalResolver

SMARTBackendAssertionPrincipalResolver validates a backend client assertion Bearer token.

func SMARTBearerPrincipalResolver

func SMARTBearerPrincipalResolver(cfg smart.BearerAuthConfig) PrincipalResolver

SMARTBearerPrincipalResolver returns principal and tenant from a validated Bearer token.

type RateLimitConfig

type RateLimitConfig struct {
	Requests   int
	Window     time.Duration
	Key        func(*http.Request) string
	MaxEntries int
}

RateLimitConfig enables a process-local fixed-window request limiter. Requests <= 0 leaves rate limiting disabled. Key should identify the caller; when omitted, the remote IP address is used.

type RegistryCapabilitySource

type RegistryCapabilitySource struct {
	Snapshot *registry.Snapshot
}

RegistryCapabilitySource adapts *registry.Snapshot to CapabilitySource.

func (RegistryCapabilitySource) CapabilitySnapshot

func (s RegistryCapabilitySource) CapabilitySnapshot() registry.CapabilitySnapshot

type ResourceService

type ResourceService interface {
	Create(ctx context.Context, resource *types.ResourceEnvelope) (*types.ResourceEnvelope, error)
	Read(ctx context.Context, resourceType, id string) (*types.ResourceEnvelope, error)
	Update(ctx context.Context, resource *types.ResourceEnvelope) (*types.ResourceEnvelope, error)
	Delete(ctx context.Context, resourceType, id string) error
	History(ctx context.Context, resourceType, id string) ([]store.ResourceVersion, error)
	ProcessTransactionBundle(ctx context.Context, bundle *types.ResourceEnvelope) (*types.ResourceEnvelope, error)
	ProcessBatchBundle(ctx context.Context, bundle *types.ResourceEnvelope) (*types.ResourceEnvelope, error)
	Patch(ctx context.Context, resourceType, id string, patchJSON []byte) (*types.ResourceEnvelope, error)
}

ResourceService is the narrow resource lifecycle surface the HTTP adapter needs.

type RootConfig

type RootConfig struct {
	FHIR http.Handler
	Sync SyncHubServer
	// SyncMiddleware must enforce the caller's node/tenant authentication and
	// authorization when sync routes are exposed.
	SyncMiddleware func(http.Handler) http.Handler
	// OAuth serves /.well-known/smart-configuration and /oauth/* when set.
	// When FHIR is also mounted, the same well-known routes are mirrored under /fhir/.well-known/.
	OAuth http.Handler
}

RootConfig configures a combined FHIR + sync HTTP handler tree.

type SDCRequest

type SDCRequest struct {
	Questionnaire         *types.ResourceEnvelope
	QuestionnaireResponse *types.ResourceEnvelope
	Parameters            *types.ResourceEnvelope
	Body                  *types.ResourceEnvelope
	Query                 url.Values
}

SDCRequest carries canonical FHIR operation inputs to the SDC adapter. The adapter owns population, validation, assembly, extraction, and adaptive policy; HTTP only performs envelope parsing and response translation.

type SQLQueryService

type SQLQueryService interface {
	Execute(ctx context.Context, req view.SQLQueryRequest) ([]byte, string, error)
}

SQLQueryService handles Library/$sqlquery-run operations.

type SearchService

type SearchService interface {
	SearchBundle(ctx context.Context, resourceType string, params url.Values) (*search.SearchBundle, error)
}

SearchService is the narrow search surface the HTTP adapter needs.

type SearchServiceAdapter

type SearchServiceAdapter struct {
	Svc                        searchBundleExecutor
	PatientSearchParamResolver auth.PatientSearchParamResolver
}

SearchServiceAdapter adapts *search.Service to SearchService and PatientScopedSearchService. PatientSearchParamResolver derives scope parameters from installed registry SearchParameters when configured.

func (SearchServiceAdapter) SearchBundle

func (a SearchServiceAdapter) SearchBundle(ctx context.Context, resourceType string, params url.Values) (*search.SearchBundle, error)

func (SearchServiceAdapter) SearchBundleForPatient

func (a SearchServiceAdapter) SearchBundleForPatient(ctx context.Context, resourceType, patientID string, params url.Values) (*search.SearchBundle, error)

SearchBundleForPatient injects a patient relationship filter into search params before executing the query so unauthorized rows are excluded at query time rather than fetched and hidden after the fact.

type ServerMetadata

type ServerMetadata struct {
	SoftwareName    string
	SoftwareVersion string
	ServerName      string
	Description     string
}

ServerMetadata supplies static server fields for CapabilityStatement generation.

type SyncHubServer

type SyncHubServer = hasync.HubServer

SyncHubServer is an alias for the sync hub server interface used by HTTP wiring.

type TerminologyEnableService

type TerminologyEnableService interface {
	Enable(ctx context.Context, record store.TerminologyInstallRecord) (terminology.EnableResult, error)
}

TerminologyEnableService enables or disables tenant opt-in to global catalog entries.

type TerminologyInstallService

type TerminologyInstallService interface {
	EnqueueRebuild(ctx context.Context, scopeID string, preExpandValueSets bool) (store.JobRecord, error)
}

TerminologyInstallService enqueues async terminology projection rebuild jobs.

type TerminologyService

type TerminologyService = terminology.Service

TerminologyService is the terminology provider surface exposed over HTTP.

type ValidateRequest

type ValidateRequest struct {
	ResourceType string
	ID           string
	ContentType  string
	Body         []byte
	Query        url.Values
}

ValidateRequest carries FHIR Resource/$validate inputs.

Query parameters:

  • mode — create, update, delete, or profile (delete requires an instance URL)
  • profile — additional StructureDefinition canonical URL
  • _fast=true — lightweight validation (runtime write profile; invariants off)
  • _invariants=true — force FHIRPath invariant checks even when _fast=true

type ValidateService

type ValidateService interface {
	Validate(context.Context, ValidateRequest) (*types.OperationOutcome, error)
}

ValidateService runs FHIR Resource/$validate and returns an OperationOutcome.

type ViewExportService

type ViewExportService interface {
	Kickoff(ctx context.Context, req view.ViewExportRequest) (*view.ViewExportJob, error)
	GetJob(ctx context.Context, jobID string) (*view.ViewExportJob, error)
	Cancel(ctx context.Context, jobID string) error
	StatusURL(jobID string) string
	FileURL(jobID, filename string) string
	GetFile(ctx context.Context, jobID, filename string) ([]byte, string, error)
	OpenFile(ctx context.Context, jobID, filename string) (io.ReadCloser, string, error)
}

ViewExportService handles ViewDefinition/$viewdefinition-export operations.

type ViewMaterializeService

type ViewMaterializeService interface {
	Kickoff(ctx context.Context, req view.MaterializeRequest) (*view.MaterializeJob, error)
	GetJob(ctx context.Context, jobID string) (*view.MaterializeJob, error)
	Cancel(ctx context.Context, jobID string) error
	StatusURL(jobID string) string
	Result(job *view.MaterializeJob) *view.MaterializeResult
}

ViewMaterializeService handles ViewDefinition/$materialize operations.

type ViewRunService

type ViewRunService interface {
	Execute(ctx context.Context, req view.ViewRunRequest) ([]byte, string, error)
}

ViewRunService handles ViewDefinition/$viewdefinition-run operations.

Jump to

Keyboard shortcuts

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