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): 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 ¶
- Variables
- func BaseStructureDefinitionURL(resourceType string) string
- func SliceItemMatchesForTest(item map[string]interface{}, sliceEl ElementDefinition, ...) bool
- func ToOperationOutcome(result *ValidationResult) *types.OperationOutcome
- type Config
- type ElementBinding
- type ElementConstraint
- type ElementDefinition
- type ElementSlicing
- type Engine
- type FailedError
- type MapResourceTypeRegistry
- type MemoryProfileCatalog
- func LoadProfileCatalogFromDir(dir string) (MemoryProfileCatalog, error)
- func LoadProfileCatalogFromDirTree(root string) (MemoryProfileCatalog, error)
- func LoadProfileCatalogFromDirs(dirs ...string) (MemoryProfileCatalog, error)
- func LoadProfileCatalogFromJSON(resources [][]byte) (MemoryProfileCatalog, error)
- func MergeProfileCatalogs(catalogs ...MemoryProfileCatalog) MemoryProfileCatalog
- type ProfileCatalog
- type ProfileCatalogResolver
- type ReferencePolicy
- type RegistryProfileCatalog
- func (c *RegistryProfileCatalog) GetStructureDefinition(canonicalURL string) (*StructureDefinition, bool)
- func (c *RegistryProfileCatalog) Reload(snapshot *registry.Snapshot) error
- func (c *RegistryProfileCatalog) ResolveStructureDefinition(canonicalURL string) (*StructureDefinition, error)
- func (c *RegistryProfileCatalog) Warm() error
- type ReloadableEngine
- type ResourceTypeRegistry
- type SliceDiscriminator
- type StructureDefinition
- type TerminologyBinding
- type ValidateOptions
- type ValidationIssue
- type ValidationMode
- type ValidationResult
- type Validator
Constants ¶
This section is empty.
Variables ¶
var ErrProfileNotFound = errors.New("profile not found")
ErrProfileNotFound indicates a StructureDefinition URL is not in the catalog.
Functions ¶
func BaseStructureDefinitionURL ¶
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 ¶
ElementBinding is a terminology binding from a StructureDefinition element.
type ElementConstraint ¶
ElementConstraint is a FHIRPath invariant from a StructureDefinition element.
type ElementDefinition ¶
type ElementDefinition struct {
Path string
Min int
Max string
Types []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.
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 ¶
func (e *ReloadableEngine) Validate(ctx context.Context, res *types.ResourceEnvelope, opts ValidateOptions) (*ValidationResult, error)
Validate implements Engine.
type ResourceTypeRegistry ¶
ResourceTypeRegistry reports whether a FHIR resource type is installed in the runtime.
type SliceDiscriminator ¶
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 ¶
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.