validate

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

README

haistack-validate (pkg/validate)

Built-in FHIR resource validation for haistack.

What it does

pkg/validate checks FHIR resources before they are saved, synced, indexed, or handed to other tools. Think of it as a gatekeeper: Is this resource well-formed enough to work with safely?

It looks at a *types.ResourceEnvelope — mainly the JSON inside it — and checks things like:

  • Is the JSON valid?
  • Does it have a resourceType (e.g. Patient, Observation)?
  • Is that type a known FHIR type?
  • Is the id valid (if present)?
  • Are basic required fields present (e.g. Observation.status)?
  • Are references syntactically valid (e.g. Patient/123, URLs, URNs)?
  • Are fields structurally sane (via Google’s FHIR JSON/proto parser — e.g. active must be a boolean, not a string)?

What it does not do by default: live terminology-server validation on API writes or FHIRPath invariants (both opt-in). Profile cardinality, slicing, and unknown-element checks against installed StructureDefinitions run on every write when the runtime profile catalog is configured.

How it fits in the ecosystem

pkg/validate is a gate before side effects. It consumes *types.ResourceEnvelope (JSON-first, optional proto companion) and returns structured issues or integrates with pkg/core as a write hook. It does not touch databases or HTTP.

flowchart TB
  subgraph inputs["Inputs"]
    ENV["ResourceEnvelope JSON + optional Proto"]
    CFG["Engine Config ProfileCatalog"]
  end

  subgraph validate_pkg["pkg/validate"]
    ENG["Engine.Validate"]
    CV["NewCoreValidator adapter"]
    OO["ToOperationOutcome"]
  end

  subgraph deps["Collaborators"]
    TYPES["pkg/types canonical JSON"]
    PROTO["pkg/proto jsonformat / proto reuse"]
    FP["pkg/fhirpath optional invariants"]
    TERM["pkg/terminology optional bindings"]
  end

  subgraph outputs["Outputs / consumers"]
    CORE["pkg/core write abort"]
    CLI["CLI / import / AI guard"]
    API["OperationOutcome responses"]
  end

  ENV --> ENG
  CFG --> ENG
  ENG --> TYPES
  ENG --> PROTO
  ENG --> FP
  ENG --> TERM
  ENG --> OO
  CV --> CORE
  OO --> API
  ENG --> CLI
Direction Package Relationship
Upstream Handlers, CLI, import jobs Call Engine.Validate directly with options per request
Upstream pkg/runtime Configures engine + NewCoreValidator on ResourceService
Input pkg/types Canonical envelope and JSON parsing rules
Input pkg/proto Structural/primitive validation via Google R4; optional proto reuse
Optional pkg/fhirpath Profile invariant evaluation when ProfileConstraints enabled
Optional pkg/terminology Full-mode terminology binding checks
Downstream pkg/core Validator hook runs before ID/version mutation on writes
Downstream API clients Receive OperationOutcome from ToOperationOutcome or core.OperationOutcomeFromError

Validation is structural and safety-oriented, not a full HL7 Java validator replacement — but base HL7 R4 profile checks integrate when the runtime catalog is wired.

Usage modes

Standalone validate (CLI, import, AI guard)

When: You need detailed issue lists or outcomes without going through ResourceService.

How: NewEngine, Validate, branch on result.Valid, emit ToOperationOutcome(result) for API-shaped errors.

Automatic validation on API writes (core hook)

When: Invalid resources must never reach SQLite/Postgres on create/update.

How: Validator: validate.NewCoreValidator(eng, opts) in ResourceServiceConfig. Failures become ErrorKindInvalid with preserved issue codes in outcomes.

Fast profile mode (runtime default)

When: Production API latency matters; you still want base profile cardinality, slicing, and unknown-element checks on snapshot profiles.

How: Enable EnforceBaseProfile / EnforceDeclaredProfiles with default ValidationModeFast. Leave ProfileConstraints false unless you explicitly want FHIRPath invariants on every write.

Full conformance mode (IG / certification)

When: Running make validate-ig or certification-style checks against examples.

How: Set Mode: validate.ValidationModeFull, supply ProfileCatalog, optional Terminology service, and enable extension policy checks.

Restricted resource-type deployments

When: A deployment only supports a subset of FHIR types (for example Patient + Observation only).

How: Configure InstalledTypes on Engine config or pass ValidateOptions.ResourceTypeRegistry per request.

Custom required fields beyond defaults

When: Organization policy mandates fields FHIR marks optional (for example Patient.gender).

How: RequiredFields map in validate.Config. Note: custom maps replace per-type defaults entirely — include Observation.status and Bundle.type if you still need them.

Proto-accelerated structural validation

When: Ingest already parsed JSON to proto and attached it to the envelope with matching hash.

How: Pass the same envelope to Validate; engine reuses proto for jsonformat work when consistent. JSON remains authoritative if hash/proto disagree.

Require server-assigned or client IDs at validation time

When: Create pipelines must reject resources missing id before reservation.

How: ValidateOptions{RequireID: true} on standalone or core adapter options.

When to use it

  • Before persisting a resource through pkg/core
  • In a CLI validate command or import pipeline
  • As a guard before exposing data to AI tools or sync

Usage

Standalone (CLI, import, AI guard, etc.)

Returns a structured result with a list of issues — good when you want detailed feedback or a FHIR OperationOutcome.

import (
    "context"

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

eng, err := validate.NewEngine(validate.Config{})
if err != nil {
    // invalid engine config
}

result, err := eng.Validate(ctx, envelope, validate.ValidateOptions{
    RequireID: true, // optional: fail if id is missing
})
if err != nil {
    // exceptional failure (e.g. context cancelled)
}

if !result.Valid {
    for _, issue := range result.Issues {
        // issue.Code, issue.Diagnostics, issue.Expression
    }

    outcome := validate.ToOperationOutcome(result)
    // emit outcome as an API error response
}
Plugged into pkg/core (automatic validation on writes)

Core supports an optional validator hook. Wrap the engine so invalid resources are rejected on Create/Update:

import (
    "github.com/degoke/haistack/pkg/core"
    "github.com/degoke/haistack/pkg/validate"
)

eng, _ := validate.NewEngine(validate.Config{})

svc, _ := core.NewResourceService(core.ResourceServiceConfig{
    Resources: db,
    History:   db,
    Sessions:  db,
    Validator: validate.NewCoreValidator(eng, validate.ValidateOptions{}),
})

If validation fails, core aborts the write and returns ErrorKindInvalid. When the failure comes from NewCoreValidator, core.OperationOutcomeFromError preserves each validation issue code (for example invalid-id, missing-required-field) instead of collapsing them into a single generic invalid issue.

If you omit Validator, core skips validation entirely.

Filter issues by severity in tooling:

for _, issue := range result.Issues {
    if issue.Severity == "error" {
        log.Printf("%s: %s", issue.Code, issue.Diagnostics)
    }
}

Per-request type allowlist without reconfiguring the engine:

result, err := eng.Validate(ctx, envelope, validate.ValidateOptions{
    ResourceTypeRegistry: validate.MapResourceTypeRegistry{
        "Patient": {},
    },
})

Optional configuration

Restrict which resource types are allowed in a deployment, or add required-field rules:

eng, _ := validate.NewEngine(validate.Config{
    InstalledTypes: validate.MapResourceTypeRegistry{
        "Patient":     {},
        "Observation": {},
    },
    RequiredFields: map[string][]string{
        "Patient": {"gender"},
    },
})

You can also pass a per-request allowlist via ValidateOptions.ResourceTypeRegistry.

Profile enforcement

The runtime validates every write against the bundled HL7 R4 base StructureDefinition for the resource type, plus any declared meta.profile URLs. Checks include cardinality, unknown elements (base snapshot), and FHIRPath invariants (best-effort).

Fast mode (default): slicing, unknown elements, optional FHIRPath invariants (ProfileConstraints). Runtime API writes leave invariants off by default.

Full mode: adds StructureDefinition terminology bindings (skips preferred strength) and extension policy. Use for certification-style checks or haistack validate --full.

catalog := validate.NewRegistryProfileCatalog(snapshot)
fp, _ := fhirpath.NewEngine(fhirpath.Config{})
eng, _ := validate.NewEngine(validate.Config{ProfileCatalog: catalog, FHIRPath: fp})

svc, _ := core.NewResourceService(core.ResourceServiceConfig{
    Validator: validate.NewCoreValidator(eng, validate.ValidateOptions{
        EnforceBaseProfile:      true,
        EnforceDeclaredProfiles: true,
        ProfileConstraints:      true, // opt-in; runtime defaults to false
        Terminology:             termService,
        Mode:                    validate.ValidationModeFull, // optional
    }),
})

Runtime API writes use fast mode by default. make validate-ig runs the same Go validator in full mode against conformance examples.

Where it fits

FHIR JSON envelope
       ↓
  validate engine
       ↓
  Valid?  → yes → proceed (save, sync, index, etc.)
       ↓
       no → list of issues (+ optional OperationOutcome)
Layer Role
types Canonical JSON envelope
validate Structural and safety checks before use
core Optional validator hook on writes
proto Google R4 parsing used for structural/primitive checks

Limits

  • Structural and safety checks always run; base HL7 R4 profile validation is enabled by default in pkg/runtime
  • Syntactic reference checks only (no existence resolution; bare IDs without slashes are accepted; typed references are not checked against the installed resource-type registry)
  • Default required fields: Observation.status, Bundle.type only — Patient has none unless you configure RequiredFields (custom maps replace per-type defaults entirely)
  • Optional installed resource-type allowlist
  • Google FHIR R4 proto/jsonformat for primitive and structural validation; structural diagnostics use FHIR element paths (for example Patient.id: …) rather than raw jsonformat prefixes
  • Fast mode (runtime default): slice cardinality, unknown elements (snapshot profiles), optional FHIRPath invariants (ProfileConstraints).
  • Full mode: SD terminology bindings (skips preferred strength) and extension URL policy including nested extensions (set Mode: ValidationModeFull or make validate-ig)
  • Constraint profiles (hai-patient, SDC): differential cardinality overlays only; unknown-element checks come from the base HL7 profile when EnforceBaseProfile is enabled
  • Corrupt installed StructureDefinitions surface profile-parse issues instead of unknown-profile
  • FHIRPath evaluation failures emit invariant-evaluation warnings

When envelope.Proto is populated, matches the JSON resource type, and envelope.Hash still matches canonical JSON, structural validation can reuse the attached proto instead of re-parsing.

Documentation

Overview

Package validate implements haistack-validate, the built-in FHIR resource validation library for haistack.

haistack-validate checks canonical JSON resources before storage, sync, indexing, or AI exposure. It validates JSON shape, resource types, IDs, required fields, reference syntax, and structural/primitive constraints via the Google FHIR R4 proto layer. Optional profile cardinality checks run when a ProfileCatalog is configured and ValidateOptions enable base and/or declared profiles. The runtime enables base HL7 R4 StructureDefinition validation by default (fast mode). Set ValidateOptions.Mode to ValidationModeFull for SD terminology bindings and extension policy.

Two integration paths

Standalone engine API:

eng, _ := validate.NewEngine(validate.Config{})
result, err := eng.Validate(ctx, envelope, validate.ValidateOptions{})
outcome := validate.ToOperationOutcome(result)

pkg/core adapter (legacy hook shape):

svc, _ := core.NewResourceService(core.ResourceServiceConfig{
    Validator: validate.NewCoreValidator(eng, validate.ValidateOptions{}),
})

MVP scope

Built-in validation is structural and safety-oriented, not full FHIR conformance. It covers:

  • JSON validity and canonical resource object shape
  • resourceType presence and known FHIR base type checks
  • optional installed resource-type allowlists
  • FHIR id syntax and optional RequireID enforcement
  • minimal configured required-field checks
  • syntactic Reference.reference validation
  • proto/jsonformat structural and primitive validation
  • optional StructureDefinition profile checks (base, declared profiles, invariants)

Profile validation modes:

  • Fast (default): element cardinality (per backbone instance, same tree walk as unknown-element checks), slice cardinality, unknown elements on snapshot profiles, optional FHIRPath invariants (opt-in via ProfileConstraints).
  • Full: adds SD terminology bindings (except preferred strength) and extension URL policy (including nested extensions).

Constraint profiles (differential only, e.g. hai-patient) apply cardinality overlays. Unknown-element checks run on the base HL7 snapshot profile when EnforceBaseProfile is enabled; differential profiles do not repeat that walk.

Not a full HL7 validator. Still limited compared to the Java reference validator:

  • slicing discriminators follow FHIR value/type/pattern/exists/profile rules; complex nested extension definitions are not resolved against Extension URLs
  • module-specific business rules

Resource-type installation checks are allowlist-based and optional. When no ResourceTypeRegistry is configured, all known FHIR base resource types are allowed.

Reference validation is syntactic only; references are not resolved for existence.

When envelope.Proto is populated, matches the JSON resource type, and envelope.Hash still matches canonical JSON, structural validation reuses the attached proto instead of re-parsing through jsonformat. JSON remains canonical; hash mismatch or absent proto forces a fresh JSON parse.

Errors

Engine.Validate returns structured issues in ValidationResult for user-data problems. The returned error is reserved for exceptional failures such as context cancellation or internal parser faults that prevent validation from completing.

NewCoreValidator adapts invalid ValidationResult values into errors compatible with pkg/core's existing ErrorKindInvalid wrapping. ToOperationOutcome maps issues directly for CLI, import, sync, and AI guard flows without going through pkg/core.

File layout

  • doc.go — package documentation (this file)
  • validate.go — Validator interface for pkg/core
  • api.go — Engine, Config, ValidateOptions, ValidationResult types
  • engine.go — built-in validation engine
  • proto_validate.go — proto reuse and JSON/proto consistency checks
  • config.go — Config validation for NewEngine
  • core_adapter.go — NewCoreValidator
  • outcome.go — ToOperationOutcome
  • reference.go — syntactic reference checks
  • defaults.go — built-in required-field defaults
  • profile.go — optional StructureDefinition cardinality checks

Index

Constants

This section is empty.

Variables

View Source
var ErrProfileNotFound = errors.New("profile not found")

ErrProfileNotFound indicates a StructureDefinition URL is not in the catalog.

Functions

func BaseStructureDefinitionURL

func BaseStructureDefinitionURL(resourceType string) string

BaseStructureDefinitionURL is the canonical HL7 R4 base profile URL for a resource type.

func SliceItemMatchesForTest

func SliceItemMatchesForTest(item map[string]interface{}, sliceEl ElementDefinition, slicing *ElementSlicing) bool

SliceItemMatchesForTest exposes slice matching for unit tests.

func ToOperationOutcome

func ToOperationOutcome(result *ValidationResult) *types.OperationOutcome

ToOperationOutcome maps a ValidationResult into a FHIR OperationOutcome.

Types

type Config

type Config struct {
	ProtoCodec         proto.ProtoCodec
	KnownResourceTypes map[string]struct{}
	InstalledTypes     ResourceTypeRegistry
	RequiredFields     map[string][]string
	ProfileCatalog     ProfileCatalog
	FHIRPath           fhirpath.Engine
}

Config configures a built-in validation Engine.

type ElementBinding

type ElementBinding struct {
	Strength string
	ValueSet string
	Version  string
}

ElementBinding is a terminology binding from a StructureDefinition element.

type ElementConstraint

type ElementConstraint struct {
	Key        string
	Severity   string
	Expression string
	Human      string
}

ElementConstraint is a FHIRPath invariant from a StructureDefinition element.

type ElementDefinition

type ElementDefinition struct {
	Path          string
	Min           int
	Max           string
	Types         []string
	MustSupport   bool
	IsSummary     bool
	ExtensionURLs []string
	Constraints   []ElementConstraint
	Binding       *ElementBinding
	Slicing       *ElementSlicing
	SliceName     string
	Pattern       map[string]interface{}
}

ElementDefinition is one snapshot or differential element.

type ElementSlicing

type ElementSlicing struct {
	Discriminators []SliceDiscriminator
	Rules          string
}

ElementSlicing describes how a repeating element is sliced.

type Engine

type Engine interface {
	Validate(ctx context.Context, res *types.ResourceEnvelope, opts ValidateOptions) (*ValidationResult, error)
}

Engine validates ResourceEnvelope values and returns structured findings.

func NewEngine

func NewEngine(cfg Config) (Engine, error)

NewEngine returns the built-in haistack-validate engine.

type FailedError

type FailedError struct {
	Issues []ValidationIssue
}

FailedError is returned by NewCoreValidator when one or more validation issues are found.

func (FailedError) Error

func (e FailedError) Error() string

type MapResourceTypeRegistry

type MapResourceTypeRegistry map[string]struct{}

MapResourceTypeRegistry is a set-based ResourceTypeRegistry.

func (MapResourceTypeRegistry) IsInstalled

func (m MapResourceTypeRegistry) IsInstalled(resourceType string) bool

IsInstalled reports whether resourceType is present in the map.

type MemoryProfileCatalog

type MemoryProfileCatalog map[string]*StructureDefinition

MemoryProfileCatalog is an in-memory ProfileCatalog.

func LoadProfileCatalogFromDir

func LoadProfileCatalogFromDir(dir string) (MemoryProfileCatalog, error)

LoadProfileCatalogFromDir loads StructureDefinitions from a directory of FHIR JSON.

func LoadProfileCatalogFromDirTree

func LoadProfileCatalogFromDirTree(root string) (MemoryProfileCatalog, error)

LoadProfileCatalogFromDirTree walks dir and loads StructureDefinitions from every subdirectory named ig or structure-definitions, plus JSON files directly under dir.

func LoadProfileCatalogFromDirs

func LoadProfileCatalogFromDirs(dirs ...string) (MemoryProfileCatalog, error)

LoadProfileCatalogFromDirs loads StructureDefinitions from multiple directories.

func LoadProfileCatalogFromJSON

func LoadProfileCatalogFromJSON(resources [][]byte) (MemoryProfileCatalog, error)

LoadProfileCatalogFromJSON parses StructureDefinition resources.

func MergeProfileCatalogs

func MergeProfileCatalogs(catalogs ...MemoryProfileCatalog) MemoryProfileCatalog

MergeProfileCatalogs combines multiple in-memory catalogs. Later entries override earlier ones for the same canonical URL.

func (MemoryProfileCatalog) GetStructureDefinition

func (c MemoryProfileCatalog) GetStructureDefinition(canonicalURL string) (*StructureDefinition, bool)

GetStructureDefinition implements ProfileCatalog.

type ProfileCatalog

type ProfileCatalog interface {
	GetStructureDefinition(canonicalURL string) (*StructureDefinition, bool)
}

ProfileCatalog looks up compiled StructureDefinitions by canonical URL.

type ProfileCatalogResolver

type ProfileCatalogResolver interface {
	ProfileCatalog
	ResolveStructureDefinition(canonicalURL string) (*StructureDefinition, error)
}

ProfileCatalogResolver extends ProfileCatalog with explicit lookup errors. Implementations should return ErrProfileNotFound for missing profiles and a non-nil error for parse failures.

type ReferencePolicy

type ReferencePolicy int

ReferencePolicy controls how Reference.reference values are validated.

const (
	// ReferencePolicySyntactic validates reference string shape only (MVP default).
	ReferencePolicySyntactic ReferencePolicy = iota
)

type RegistryProfileCatalog

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

RegistryProfileCatalog resolves StructureDefinitions from a compiled registry snapshot.

func NewRegistryProfileCatalog

func NewRegistryProfileCatalog(snapshot *registry.Snapshot) *RegistryProfileCatalog

NewRegistryProfileCatalog builds a ProfileCatalog backed by registry.Snapshot.

func (*RegistryProfileCatalog) GetStructureDefinition

func (c *RegistryProfileCatalog) GetStructureDefinition(canonicalURL string) (*StructureDefinition, bool)

GetStructureDefinition implements ProfileCatalog.

func (*RegistryProfileCatalog) Reload

func (c *RegistryProfileCatalog) Reload(snapshot *registry.Snapshot) error

Reload swaps the backing snapshot and clears the parse cache.

func (*RegistryProfileCatalog) ResolveStructureDefinition

func (c *RegistryProfileCatalog) ResolveStructureDefinition(canonicalURL string) (*StructureDefinition, error)

ResolveStructureDefinition returns a parsed StructureDefinition or a lookup/parse error.

func (*RegistryProfileCatalog) Warm

func (c *RegistryProfileCatalog) Warm() error

Warm pre-parses base StructureDefinitions for all enabled resource types.

type ReloadableEngine

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

ReloadableEngine is a thread-safe validate.Engine whose snapshot-backed state can be refreshed after registry catalog changes.

func NewReloadableEngine

func NewReloadableEngine(cfg Config) (*ReloadableEngine, error)

NewReloadableEngine constructs an engine and retains the config for reload.

func (*ReloadableEngine) Config

func (e *ReloadableEngine) Config() Config

Config returns the last reload configuration.

func (*ReloadableEngine) Reload

func (e *ReloadableEngine) Reload(cfg Config) error

Reload rebuilds the inner engine from an updated config.

func (*ReloadableEngine) Validate

Validate implements Engine.

type ResourceTypeRegistry

type ResourceTypeRegistry interface {
	IsInstalled(resourceType string) bool
}

ResourceTypeRegistry reports whether a FHIR resource type is installed in the runtime.

type SliceDiscriminator

type SliceDiscriminator struct {
	Type string
	Path string
}

SliceDiscriminator matches array items to named slices.

type StructureDefinition

type StructureDefinition struct {
	URL         string
	Type        string
	Kind        string
	Derivation  string
	UseSnapshot bool
	Elements    []ElementDefinition
	// contains filtered or unexported fields
}

StructureDefinition is the subset of a FHIR StructureDefinition used for profile validation on write.

type TerminologyBinding

type TerminologyBinding struct{ URL, Version, Strength string }

type ValidateOptions

type ValidateOptions struct {
	RequireID               bool
	ResourceTypeRegistry    ResourceTypeRegistry
	ReferencePolicy         ReferencePolicy
	Terminology             terminology.Service
	TerminologyEnabled      bool
	TerminologyBindings     map[string]TerminologyBinding
	Profiles                []string
	ProfileCatalog          ProfileCatalog
	EnforceBaseProfile      bool
	EnforceDeclaredProfiles bool
	ProfileConstraints      bool
	// Mode selects fast vs full profile validation. Zero defaults to Fast.
	Mode ValidationMode
}

ValidateOptions configures a single Validate invocation.

type ValidationIssue

type ValidationIssue struct {
	Severity    string
	Code        string
	Diagnostics string
	Expression  []string
}

ValidationIssue is one structured validation finding.

func IssuesFromError

func IssuesFromError(err error) ([]ValidationIssue, bool)

IssuesFromError returns structured validation issues when err is or wraps a FailedError.

type ValidationMode

type ValidationMode int

ValidationMode selects how deeply profile validation runs.

const (
	// ValidationModeFast checks slice cardinality, unknown elements on snapshot
	// profiles, and optional FHIRPath invariants (ProfileConstraints). This is
	// the default for runtime API writes.
	ValidationModeFast ValidationMode = iota
	// ValidationModeFull adds StructureDefinition terminology bindings (except
	// preferred strength) and extension URL policy checks.
	ValidationModeFull
)

type ValidationResult

type ValidationResult struct {
	Valid  bool
	Issues []ValidationIssue
}

ValidationResult is the structured output of Engine.Validate.

type Validator

type Validator interface {
	// ValidateResource returns nil when resource is acceptable for persistence.
	ValidateResource(ctx context.Context, resource *types.ResourceEnvelope) error
}

Validator checks a resource envelope before lifecycle mutations in pkg/core.

func NewCoreValidator

func NewCoreValidator(engine Engine, opts ValidateOptions) Validator

NewCoreValidator adapts Engine into the pkg/core Validator interface.

Jump to

Keyboard shortcuts

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