types

package
v0.2.0 Latest Latest
Warning

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

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

README

haistack-types (pkg/types)

Generic FHIR JSON layer for the haistack monorepo.

What it does

FHIR resources usually arrive as JSON (Patient, Observation, and so on). This package lets you work with any FHIR resource as JSON without importing R4 or R5 generated structs.

It:

  1. Wraps JSON in a standard container (ResourceEnvelope) with resource type, id, version, last-updated time, normalized JSON, and a content hash.
  2. Normalizes JSON so the same resource always produces the same bytes and hash, even when formatting or key order differs.
  3. Provides small helpers to read and write common fields (id, meta) and find references inside nested JSON.
  4. Defines lightweight types such as OperationOutcome for errors, without full FHIR codegen.

It does not store data, run searches, validate profiles, or talk to a database. It only handles FHIR JSON shape and metadata.

When to use it

  • Before saving a resource — normalize and hash it for storage or change detection
  • When you need type, id, or version without unmarshaling into a large struct
  • When walking references in a resource (for example Patient/123 links)
  • As the shared container passed between packages (core, store, proto)

Usage

Parse JSON into an envelope:

import "github.com/degoke/haistack/pkg/types"

codec := types.NewJSONCodec()
envelope, err := codec.ParseJSON("Patient", patientJSON)
// envelope.ResourceType, envelope.ID, envelope.JSON, envelope.Hash

Get a stable hash for deduping or change detection:

hash, err := types.HashResource(patientJSON)

Read or update id / meta without a typed struct:

id, _ := types.GetID(patientJSON)

updated, _ := types.SetID(patientJSON, "new-id")
updated, _ := types.SetMeta(updated, types.Meta{
    VersionID:   "2",
    LastUpdated: time.Now(),
})

Find all references in a resource:

refs, _ := types.GetReferences(observationJSON)
for _, ref := range refs {
    // ref.Raw is always set; ref.ResourceType/ID for "Patient/123" style refs
}

Serialize back to JSON:

out, err := codec.ToJSON(envelope) // returns normalized JSON bytes

Mental model

Think of it as FHIR JSON utilities plus a standard envelope — not a full FHIR server or validator, but the common foundation so every other package can handle resources the same way.

Where it fits

Layer Role
types Canonical JSON, envelopes, field helpers
proto Optional typed proto companions on envelopes
store Persistence contracts using ResourceEnvelope
core Resource lifecycle (CRUD, history, bundles)

MVP limits

  • Version-agnostic FHIR JSON only (no generated R4/R5 bindings here)
  • No bundle helpers, extension helpers, profile validation, or identifier extraction
  • ResourceEnvelope.Proto is set by pkg/proto on proto paths; JSON-only paths leave it nil

See doc.go for the full API, canonical JSON rules, and reference parsing behavior.

Documentation

Overview

Package types implements haistack-types, a version-agnostic FHIR JSON type layer.

haistack-types is the foundational library in the haistack monorepo. It lets every downstream package (pkg/core, pkg/store, pkg/proto, pkg/search, and others) handle FHIR resources generically without importing generated R4 or R5 structs. Resources are represented as normalized JSON envelopes with derived metadata, lightweight support types, and helpers for common field access.

This package is the JSON source of truth for runtime abstractions:

  • Canonical FHIR JSON is the primary interchange and storage form.
  • ResourceEnvelope is the shared container passed across packages.
  • Proto values (via pkg/proto) are optional typed companions — never a replacement for JSON.
  • Hash, VersionID, and LastUpdated are always derived from canonical JSON, not from proto fields.

MVP scope targets version-agnostic FHIR JSON. Generated R4/R5 bindings, bundle helpers, extension helpers, profile metadata, primitive validators, DB/REST/search/sync/auth, and AI tooling are explicitly out of scope here.

ResourceEnvelope

ResourceEnvelope is the generic runtime container for any FHIR resource:

  • ResourceType — top-level resourceType string.
  • ID — top-level id when present (empty string when absent).
  • VersionID — copied from meta.versionId when present.
  • LastUpdated — parsed from meta.lastUpdated when present (zero time.Time when absent).
  • JSON — normalized canonical JSON bytes (see Canonical JSON below).
  • Hash — SHA-256 hex digest of JSON.
  • Proto — optional typed companion; nil in JSON-only MVP paths (pkg/proto sets this).

Envelope fields duplicate commonly accessed metadata so callers avoid re-parsing JSON for type, id, version, and timestamp on hot paths. JSON and Hash are always populated together from the same normalization pass.

ResourceCodec and JSONCodec

ResourceCodec is the parsing boundary for FHIR JSON envelopes:

  • ParseJSON(resourceType, data) decodes data, requires a top-level JSON object with resourceType, normalizes the payload, derives envelope metadata, and returns ResourceEnvelope. When resourceType is non-empty it must match the payload; when empty the type is taken from the JSON.
  • ToJSON(resource) returns resource.JSON when present; errors on nil resource or empty JSON. There is no serialization path from Proto in MVP — callers must use pkg/proto for proto-to-JSON conversion.

JSONCodec is the default ResourceCodec implementation. Construct with NewJSONCodec. pkg/proto routes envelope construction through JSONCodec.ParseJSON so Hash and meta fields match JSON-only ingestion.

Canonical JSON

NormalizeJSON defines the runtime's canonical JSON form:

  • Input must be a valid JSON object (top-level array or scalar returns an error).
  • Insignificant whitespace is removed.
  • Object keys are sorted deterministically (encoding/json.Marshal on generic maps).
  • Array element order is preserved.
  • Nested objects and arrays are normalized recursively through the same rules.

SetID, SetMeta, JSONCodec.ParseJSON, and envelope construction all return bytes in this canonical form. Semantically equivalent payloads that differ only in formatting or key order normalize to identical bytes.

Hashing

HashResource returns the SHA-256 digest of normalized canonical JSON, hex-encoded. ResourceEnvelope.Hash is computed the same way during envelope construction. Equivalent payloads produce identical hashes; any semantic change produces a different hash. Hashing is content-only — it does not include resourceType as a separate input because resourceType is part of the JSON object.

JSON helpers

Package-level helpers operate on raw []byte without requiring a ResourceEnvelope or typed struct. All mutating helpers (SetID, SetMeta) return normalized canonical bytes and preserve unrelated fields.

GetResourceType returns the top-level resourceType or an error when missing/invalid.

GetID returns the top-level id string, or "" when id is absent (not an error).

SetID sets or removes the top-level id and returns normalized JSON.

GetMeta extracts meta.versionId and meta.lastUpdated. Returns zero Meta when meta is absent. lastUpdated is parsed from FHIR ISO 8601 timestamps (RFC3339 and common FHIR variants).

SetMeta updates meta.versionId and meta.lastUpdated. Empty VersionID removes versionId; zero LastUpdated removes lastUpdated. Removes the entire meta object when no fields remain.

GetReferences recursively walks nested JSON objects and arrays and collects every field named reference (FHIR Reference.reference). Each value is parsed into Reference (see below). Discovery order follows JSON structure traversal (object keys in map iteration order during walk; not sorted).

Reference parsing

GetReferences applies these rules when populating Reference fields:

  • Typed relative references (ResourceType/ID) — e.g. Patient/123 — set ResourceType, ID, and Raw. IDs after the first slash are retained in ID (e.g. Patient/123/_history/1).
  • Untyped relative references (no slash, not a URL/URN/fragment) — e.g. only-an-id — populate Raw only; ResourceType and ID remain empty.
  • Absolute URLs (http://, https://), URNs (urn:), and fragments (#) — populate Raw only.

Reference.Raw always holds the original reference string.

Support types

Reference — parsed reference with optional ResourceType, ID, and always Raw.

Meta — lightweight meta.versionId and meta.lastUpdated (not the full FHIR Meta complex type).

Identifier — lightweight identifier fields (System, Value, Use, Type) for future helpers; no extraction helpers in MVP.

OperationOutcome and OperationIssue — hand-written FHIR OperationOutcome types with JSON tags for direct marshaling (for example error responses from pkg/core). Code is a plain string in MVP, not a CodeableConcept.

Integration with other packages

pkg/proto — ProtoToEnvelope converts proto → JSON → JSONCodec.ParseJSON, then sets envelope.Proto. Canonical JSON and Hash always come from pkg/types normalization.

pkg/store — storage contracts use ResourceEnvelope and depend only on pkg/types for FHIR resource shape (no business rules in the type layer).

pkg/core — resource lifecycle reads and writes envelopes; OperationOutcome types may be composed for API errors.

Typical flows

JSON ingest:

FHIR JSON bytes → NewJSONCodec().ParseJSON("", data) → ResourceEnvelope { JSON, Hash, ... }

JSON egress:

ResourceEnvelope → JSONCodec.ToJSON(envelope) → canonical JSON bytes

Field mutation without envelope:

data → SetID(data, newID) → normalized JSON → HashResource(...) for updated digest

Reference extraction:

data → GetReferences(data) → []Reference for indexing, graph walks, or validation

Proto path (via pkg/proto):

proto → pkg/proto.ProtoToJSON → types.NormalizeJSON / JSONCodec.ParseJSON → envelope + Proto

File layout

  • doc.go — package documentation (this file).
  • types.go — Reference, Meta, Identifier.
  • envelope.go — ResourceEnvelope.
  • operation_outcome.go — OperationOutcome, OperationIssue.
  • codec.go — ResourceCodec, JSONCodec.
  • helpers.go — package-level JSON helpers.
  • jsonutil.go — internal canonicalization, hashing, and reference parsing (unexported).

Out of scope (MVP)

Bundle helpers, extension helpers, profile metadata, primitive validators, generated R4/R5 adapters, identifier extraction helpers, DB/REST/search/sync/auth, AI tooling, and proto blob storage. Bundle ownership is acknowledged for a later phase; generic single-resource movement is the first-cut focus.

Index

Constants

This section is empty.

Variables

View Source
var ErrQuestionnaireNotFound = errors.New("questionnaire not found")

ErrQuestionnaireNotFound indicates a QuestionnaireResponse.questionnaire reference could not be resolved.

Functions

func GetID

func GetID(data []byte) (string, error)

GetID returns the top-level id from FHIR JSON, or "" when id is absent.

func GetResourceType

func GetResourceType(data []byte) (string, error)

GetResourceType returns the top-level resourceType from FHIR JSON. Returns an error when data is not a JSON object or resourceType is missing or invalid.

func HashResource

func HashResource(data []byte) (string, error)

HashResource returns the SHA-256 hex digest of the normalized canonical JSON for data.

func NormalizeJSON

func NormalizeJSON(data []byte) ([]byte, error)

NormalizeJSON canonicalizes FHIR JSON: valid object, sorted keys, no insignificant whitespace. Semantically equivalent payloads with different formatting normalize to identical bytes.

func SetID

func SetID(data []byte, id string) ([]byte, error)

SetID updates the top-level id (or removes it when id is empty) and returns normalized JSON. Unrelated fields are preserved.

func SetMeta

func SetMeta(data []byte, meta Meta) ([]byte, error)

SetMeta updates meta.versionId and meta.lastUpdated and returns normalized JSON. Empty VersionID removes versionId; zero LastUpdated removes lastUpdated. Removes meta entirely when no fields remain. Unrelated fields are preserved.

Types

type ClientValidationOutcomeError

type ClientValidationOutcomeError interface {
	error
	OperationOutcome() OperationOutcome
}

ClientValidationOutcomeError marks errors that represent client-side validation failures with a structured OperationOutcome. Infrastructure and not-found errors should not implement this interface.

type Identifier

type Identifier struct {
	System string
	Value  string
	Use    string
	Type   string
}

Identifier is a lightweight FHIR Identifier for use in future helpers and callers. MVP exposes the type only; no JSON extraction helpers are provided yet.

type JSONCodec

type JSONCodec struct{}

JSONCodec is the default ResourceCodec. It normalizes JSON and derives envelope metadata without typed FHIR structs or proto values.

func NewJSONCodec

func NewJSONCodec() *JSONCodec

NewJSONCodec returns a JSONCodec ready for use.

func (*JSONCodec) ParseJSON

func (c *JSONCodec) ParseJSON(resourceType string, data []byte) (*ResourceEnvelope, error)

ParseJSON decodes FHIR JSON, validates resourceType when the argument is non-empty, normalizes the payload, and returns a populated ResourceEnvelope with Proto nil.

func (*JSONCodec) ToJSON

func (c *JSONCodec) ToJSON(resource *ResourceEnvelope) ([]byte, error)

ToJSON returns the envelope's normalized JSON bytes. Errors if resource is nil or JSON is empty.

type Meta

type Meta struct {
	VersionID   string
	LastUpdated time.Time
}

Meta holds lightweight FHIR meta fields extracted from or applied to resource JSON. It is not a full FHIR Meta complex type — only versionId and lastUpdated are supported.

func GetMeta

func GetMeta(data []byte) (*Meta, error)

GetMeta extracts meta.versionId and meta.lastUpdated from FHIR JSON. Returns zero Meta when meta is absent; errors when meta is not a JSON object.

type OperationIssue

type OperationIssue struct {
	Severity    string   `json:"severity,omitempty"`
	Code        string   `json:"code,omitempty"`
	Diagnostics string   `json:"diagnostics,omitempty"`
	Expression  []string `json:"expression,omitempty"`
}

OperationIssue is one issue entry within an OperationOutcome.

type OperationOutcome

type OperationOutcome struct {
	ResourceType string           `json:"resourceType"`
	Issue        []OperationIssue `json:"issue,omitempty"`
}

OperationOutcome is a hand-written FHIR OperationOutcome resource for error responses. Marshal and unmarshal directly with encoding/json; Code is a plain string in MVP.

type QuestionnaireReferenceError

type QuestionnaireReferenceError struct {
	Canonical  string
	Kind       string // "not-found", "resolver-required", or "resolution-failed"
	Expression []string
	Cause      error
}

QuestionnaireReferenceError classifies questionnaire resolution failures for HTTP and core mapping.

func NewQuestionnaireNotFoundError

func NewQuestionnaireNotFoundError(canonical string, cause error) QuestionnaireReferenceError

NewQuestionnaireNotFoundError returns a not-found questionnaire reference error.

func NewQuestionnaireResolutionFailedError

func NewQuestionnaireResolutionFailedError(cause error) QuestionnaireReferenceError

NewQuestionnaireResolutionFailedError returns an infrastructure resolution failure.

func NewQuestionnaireResolverRequiredError

func NewQuestionnaireResolverRequiredError() QuestionnaireReferenceError

NewQuestionnaireResolverRequiredError returns a client error when validation cannot resolve a questionnaire.

func (QuestionnaireReferenceError) Error

func (QuestionnaireReferenceError) Is

func (e QuestionnaireReferenceError) Is(target error) bool

func (QuestionnaireReferenceError) Unwrap

type Reference

type Reference struct {
	ResourceType string
	ID           string
	Raw          string
}

Reference is a parsed FHIR Reference.reference value. Raw always holds the original string; ResourceType and ID are set only for typed relative references (see package documentation for parsing rules).

func GetReferences

func GetReferences(data []byte) ([]Reference, error)

GetReferences recursively collects every reference field in the JSON payload. See package documentation for Reference parsing rules.

type ResourceCodec

type ResourceCodec interface {
	ParseJSON(resourceType string, data []byte) (*ResourceEnvelope, error)
	ToJSON(resource *ResourceEnvelope) ([]byte, error)
}

ResourceCodec parses FHIR JSON into ResourceEnvelope and serializes envelopes back to JSON.

type ResourceEnvelope

type ResourceEnvelope struct {
	ResourceType string
	ID           string
	VersionID    string
	LastUpdated  time.Time
	JSON         []byte
	Proto        any
	Hash         string
}

ResourceEnvelope is the generic runtime container for a FHIR resource. JSON and Hash are always canonical; Proto is optional (set by pkg/proto on proto paths).

func (*ResourceEnvelope) BoolField

func (e *ResourceEnvelope) BoolField(path ...string) (bool, bool)

BoolField returns a boolean-valued field from the envelope.

func (*ResourceEnvelope) DecodeInto

func (e *ResourceEnvelope) DecodeInto(target any) error

DecodeInto unmarshals the canonical resource JSON into a caller-owned typed FHIR struct. It keeps the generic envelope API while avoiding repeated manual json.Unmarshal calls in client applications.

func (*ResourceEnvelope) Field

func (e *ResourceEnvelope) Field(path ...string) (any, bool)

Field returns a JSON field reached by the supplied object path. It is a lightweight alternative to decoding the entire envelope for callers that only need one or two values.

func (*ResourceEnvelope) Int64Field

func (e *ResourceEnvelope) Int64Field(path ...string) (int64, bool)

Int64Field returns an integer-valued field from the envelope.

func (*ResourceEnvelope) StringField

func (e *ResourceEnvelope) StringField(path ...string) (string, bool)

StringField returns a string-valued field from the envelope.

Jump to

Keyboard shortcuts

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