proto

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

README

haistack-proto (pkg/proto)

Optional typed protobuf adapter for FHIR resources in the haistack monorepo.

What it does

FHIR resources in this stack normally live as JSON. That is what gets stored and passed around via pkg/types.

This package adds an optional typed layer on top. It converts FHIR JSON into Google FHIR Go protobuf objects (strongly typed structs under the hood) and back again — without forcing the rest of your code to import Google's libraries.

Think of it as a translator:

FHIR JSON  ↔  typed proto (in memory)  ↔  ResourceEnvelope

Important rules:

  • JSON is still the source of truth for storage
  • pkg/types is still the shared container (ResourceEnvelope)
  • Proto is a companion — useful for validation and transformation, not a replacement for JSON

It does not store data, persist proto blobs, or replace JSON in the database. It only converts between JSON and typed proto values in memory.

How it fits in the ecosystem

pkg/proto is an optional typed companion to pkg/types. Storage, APIs, and sync continue to exchange canonical JSON in ResourceEnvelope.JSON; proto values live in envelope.Proto for in-memory validation, transformation, and tooling.

flowchart LR
  subgraph sources["Inputs"]
    JSON["FHIR JSON bytes"]
    PB["Google R4 proto messages"]
  end

  subgraph proto_pkg["pkg/proto"]
    CODEC["GoogleR4Codec / ProtoCodec"]
    HELP["ToEnvelope / ParseJSONToEnvelope"]
  end

  subgraph types_pkg["pkg/types"]
    ENV["ResourceEnvelope JSON Hash meta"]
  end

  subgraph consumers["Downstream consumers"]
    VAL["pkg/validate structural checks"]
    CORE["pkg/core optional paths"]
    APP["App transforms / codegen"]
  end

  JSON --> CODEC
  PB --> CODEC
  CODEC --> ENV
  HELP --> ENV
  ENV --> VAL
  ENV --> CORE
  ENV --> APP
Direction Package Relationship
Upstream Callers / CLI Supply JSON or typed pkg/proto/r4 builders
Foundation pkg/types All metadata (Hash, ID, VersionID) derived from canonical JSON via JSONCodec
Downstream pkg/validate Reuses attached proto when hash matches JSON to skip re-parse
Downstream pkg/core Accepts envelopes with or without Proto; persistence stores JSON only
Downstream pkg/store Persists ResourceEnvelope.JSON; proto not written in MVP
External github.com/google/fhir/go R4 jsonformat + generated messages (pinned version)
Subpackage pkg/proto/r4 Ergonomic aliases and helpers (NewPatient, etc.)

JSON→proto conversion rejects unknown JSON fields relative to the Google R4 schema. Vendor extensions that must round-trip unchanged should stay on the pkg/types JSON-only path.

Usage modes

JSON-only envelopes (default stack path)

When: Storage, sync, and APIs already normalize JSON through pkg/types and you do not need typed structs in process.

How: Skip pkg/proto entirely. envelope.Proto remains nil. Validation still works via JSON parse inside pkg/validate.

Parse JSON to typed proto for inspection

When: Tools or tests want compile-time-friendly structs and Google’s parser validation without persisting proto.

How: codec := proto.NewGoogleR4Codec() then ParseJSONToProto("Patient", data). Use ResourceTypeOfProto before branching on message type.

Build resources in Go, export canonical JSON

When: Server-side builders, codegen, or migrations construct FHIR programmatically.

How: Use pkg/proto/r4 helpers, then proto.ToEnvelope or proto.ToJSON:

patient := protor4.NewPatient("pat-1")
jsonBytes, err := proto.ToJSON(patient)
envelope, err := proto.ToEnvelope(patient)
One-step JSON envelope with proto attached

When: Ingest pipeline wants both canonical envelope fields and typed proto for downstream validators.

How: proto.ParseJSONToEnvelope("Patient", patientJSON) or codec.ParseJSONToEnvelope. Hash and meta match the JSON-only codec path; Proto holds ContainedResource.

Unwrap proto from stored envelopes

When: A resource was loaded from DB as JSON-only but you re-parse for analysis, or envelope was built on the proto path earlier in the request.

How: cr, err := proto.ContainedResourceFromEnvelope(envelope) then cr.GetPatient(). Guard with proto.IsProtoResource(envelope.Proto).

Validation fast path with proto reuse

When: pkg/validate runs on envelopes that already carry consistent proto + hash from ingest.

How: Populate envelope via proto path before calling validate.Engine.Validate — structural validation may skip jsonformat re-parse when hash matches canonical JSON.

Round-trip JSON → proto → JSON for strict R4 subsets

When: You need normalized output that drops non-schema fields (interop with strict Google R4 tooling).

How: ParseJSONToProto → ProtoToJSON. Expect field loss for extensions not modeled in Google R4; compare hash with types normalization expectations before save.

When to use it

Use pkg/proto when you want to:

  1. Parse JSON into a typed proto — Google's parser validates structure as it parses
  2. Convert proto back to canonical JSON — same normalized format pkg/types expects
  3. Build a full envelope with both JSON and proto attached — hash and metadata from JSON, typed object in envelope.Proto

You do not need it for basic JSON handling — that is what pkg/types is for.

Usage

Construct a typed resource and create an envelope:

import (
	proto "github.com/degoke/haistack/pkg/proto"
	protor4 "github.com/degoke/haistack/pkg/proto/r4"
)

patient := protor4.NewPatient("pat-1")
envelope, err := proto.ToEnvelope(patient)
// envelope.JSON is canonical; envelope.Proto is the original patient.

For explicit resource-type control or JSON parsing, use a codec:

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

codec := proto.NewGoogleR4Codec()

Parse JSON into proto:

pb, err := codec.ParseJSONToProto("Patient", patientJSON)
// pb is an `any` — a typed Google R4 ContainedResource inside

Parse JSON into a full envelope in one step:

envelope, err := codec.ParseJSONToEnvelope("Patient", patientJSON)
// Same as ParseJSONToProto + ProtoToEnvelope
// Or use the package helper: proto.ParseJSONToEnvelope("Patient", patientJSON)

Unwrap the typed proto from an envelope:

cr, err := proto.ContainedResourceFromEnvelope(envelope)
patient := cr.GetPatient()

Convert proto back to canonical JSON:

jsonBytes, err := codec.ProtoToJSON("Patient", pb)
// Same normalized JSON rules as pkg/types

Get a full envelope (JSON + metadata + proto attached):

envelope, err := codec.ProtoToEnvelope("Patient", pb)
// envelope.JSON, envelope.Hash, envelope.ID, ...
// envelope.Proto holds the original typed value

Check what you have:

if proto.IsProtoResource(envelope.Proto) {
    rt, _ := proto.ResourceTypeOfProto(envelope.Proto) // "Patient"
}

When resourceType is non-empty, it must match the payload (for example "Patient"). Pass "" to accept whatever type is in the JSON or proto.

Wrap an individual R4 message as ContainedResource:

cr, err := proto.AsContainedResource(patientMsg)

Detect type mismatch early:

_, err := codec.ParseJSONToEnvelope("Observation", patientJSON) // error: type mismatch

Mental model

Package Role
types Works with FHIR as JSON — parse, hash, read id/meta
proto Optionally adds typed proto companions on top of that JSON
Patient JSON
    │
    ├─ pkg/types only ──► ResourceEnvelope { JSON, Hash, ... }     Proto = nil
    │
    └─ pkg/proto path ──► ResourceEnvelope { JSON, Hash, ... }     Proto = typed object

One-liner: pkg/types handles FHIR JSON; pkg/proto optionally gives you a typed proto version of the same resource, while keeping JSON as the canonical form everywhere else.

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)

Limits

  • Google FHIR Go R4 only (no R5 yet)
  • No proto blob storage in the database
  • No profile-aware validation or proto diffing
  • pkg/proto/r4 aliases the pinned Google R4 message types, while JSON remains canonical
  • envelope.Proto is set on proto paths; JSON-only paths leave it nil
  • JSON→proto→JSON may reject or omit fields outside the Google R4 schema; use pkg/types for arbitrary JSON

Documentation

Overview

Package proto implements haistack-proto, an adapter layer between provider-specific FHIR protobuf messages and the haistack runtime.

haistack-proto wraps generated FHIR protos (initially Google FHIR Go R4) behind stable interfaces so downstream packages can parse, transform, and validate resources without importing provider module paths or version-specific message types. Callers work with any for proto values and *types.ResourceEnvelope for runtime containers.

This package is an adapter, not a source of truth:

  • Canonical FHIR JSON remains the primary stored form (resource_json).
  • types.ResourceEnvelope is the shared runtime abstraction across packages.
  • Proto values are optional typed companions for validation, transformation, and (eventually) binary storage — never a replacement for JSON.

ProtoCodec

ProtoCodec is the provider-agnostic boundary. Implementations convert between FHIR JSON, provider protobuf messages, and types.ResourceEnvelope:

  • ParseJSONToProto validates the payload resourceType, parses JSON into a proto message, and returns it as any.
  • ParseJSONToEnvelope parses JSON into proto and returns a fully populated ResourceEnvelope in one step (ParseJSONToProto followed by ProtoToEnvelope).
  • ProtoToJSON accepts a supported proto value, serializes to FHIR JSON, and re-normalizes through types.NormalizeJSON so output matches the runtime's canonical JSON rules.
  • ProtoToEnvelope converts proto to JSON, parses via types.NewJSONCodec().ParseJSON, attaches the original proto to envelope.Proto, and returns a fully populated envelope with Hash, VersionID, and LastUpdated derived the same way as JSON-only resources.

When resourceType is non-empty on any method, it must match the actual resource type carried by the payload or proto value; mismatches return an error.

GoogleR4Codec

GoogleR4Codec is the default ProtoCodec implementation. It uses github.com/google/fhir/go (pinned to v0.7.4) jsonformat support and R4 generated protos.

ParseJSONToProto uses UnmarshalR4 and returns a Google R4 ContainedResource as any. ContainedResource is preferred internally so arbitrary resource types share one parse path.

ProtoToJSON accepts either a ContainedResource or an individual R4 resource message (for example *patient_go_proto.Patient). Individual messages are marshaled via MarshalResource; ContainedResource values use Marshal.

NewGoogleR4Codec constructs a codec with a UTC timezone unmarshaller and a compact (non-indented) marshaller. Initialization panics only on programmer error (invalid jsonformat configuration).

Integration with types.ResourceEnvelope

ProtoToEnvelope always routes metadata through types.JSONCodec rather than reading proto fields directly. That guarantees envelope.Hash, envelope.VersionID, and envelope.LastUpdated match what pkg/types would produce from the same canonical JSON. envelope.Proto holds the caller's original proto value (ContainedResource or individual resource) for later typed access within pkg/proto or provider-aware code paths.

Downstream storage and APIs should continue to persist and exchange envelope.JSON; Proto is an in-memory companion only in MVP (no resource_proto_blob APIs).

Resource registry

google_r4_registry.go builds an internal r4ResourceRegistry from the R4 ContainedResource protobuf oneof at init time. The registry maps FHIR resource type names (for example Patient) to oneof field descriptors and message full names. It powers ResourceTypeOfProto, IsProtoResource, wrapR4Resource, and future provider-specific lookups without exposing Google types in the public API.

Convenience helpers

IsProtoResource reports whether a value is a supported Google FHIR R4 protobuf resource (ContainedResource with a set branch, or a known individual R4 resource message).

ResourceTypeOfProto returns the FHIR resource type string for a supported R4 proto value.

Both helpers currently target R4 only. When additional providers or FHIR versions are added, they will dispatch by message descriptor (see google_r5.go).

ToEnvelope, ToJSON, ResourceType, and ParseJSONToEnvelope are concise R4 helpers using the default GoogleR4Codec. Applications can construct resources with aliases from github.com/degoke/haistack/pkg/proto/r4, for example:

patient := r4.NewPatient("pat-1")
envelope, err := proto.ToEnvelope(patient)

AsContainedResource and ContainedResourceFromEnvelope unwrap envelope.Proto values for typed access to the inner ContainedResource without manual type assertions.

JSON round-trip limitations

JSON→proto→JSON conversion uses Google's jsonformat layer. Fields not modeled in the Google R4 protobuf schema are not preserved on the proto path: ParseJSONToProto and ParseJSONToEnvelope return an error when the JSON contains unknown fields. Successful round-trips emit only schema-modeled fields in envelope.JSON. Use pkg/types JSON-only helpers when arbitrary or vendor-specific payload fields must be retained without proto.

Public API rules

Exported codec signatures use any and *types.ResourceEnvelope. The r4 subpackage exposes aliases for the pinned Google-generated R4 messages; callers need not import the long github.com/google/fhir/go paths directly.

Storage APIs for proto blobs, profile-aware validation, and proto diffing are out of MVP scope.

Conversion flows

JSON ingest:

FHIR JSON → ParseJSONToProto → ContainedResource (any)
FHIR JSON → ParseJSONToEnvelope → ResourceEnvelope { JSON, Hash, Proto, ... }

JSON egress:

ContainedResource (any) → ProtoToJSON → canonical JSON bytes
individual R4 resource (any) → ProtoToJSON → canonical JSON bytes

Envelope construction:

proto (any) → ProtoToJSON → types.JSONCodec.ParseJSON → envelope + envelope.Proto = proto

Future extension points

The following seams are documented in stub files and are not implemented in MVP:

  • google_r5.go — GoogleR5Codec implementing ProtoCodec for R5 ContainedResource
  • binary.go — wire-format marshal/unmarshal for optional proto blob storage
  • validation.go — typed structural validation beyond jsonformat ingest checks
  • codegen.go — generated registry and adapter boilerplate for new providers/versions

Adding a new provider should implement ProtoCodec, keep provider imports internal, reuse types.JSONCodec for envelope normalization, and extend the contract tests in proto_test.go.

Out of scope (MVP)

R5 support, binary proto storage helpers, typed profile validation, code generation scripts, proto diffing, and persistence of proto blobs alongside resource_json.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AsContainedResource

func AsContainedResource(v any) (*r4.ContainedResource, error)

AsContainedResource returns v as a Google R4 ContainedResource. Values already stored as ContainedResource are returned as-is. Individual R4 resource messages (for example *r4.Patient) are wrapped automatically.

func ContainedResourceFromEnvelope

func ContainedResourceFromEnvelope(envelope *types.ResourceEnvelope) (*r4.ContainedResource, error)

ContainedResourceFromEnvelope returns envelope.Proto as a ContainedResource. It errors when envelope is nil, Proto is unset, or Proto is not a supported R4 value.

func IsProtoResource

func IsProtoResource(v any) bool

IsProtoResource reports whether v is a supported Google FHIR R4 protobuf resource.

func KnownR4ResourceTypes

func KnownR4ResourceTypes() map[string]struct{}

KnownR4ResourceTypes returns the FHIR resource types supported by GoogleR4Codec.

func ParseJSONToEnvelope

func ParseJSONToEnvelope(resourceType string, data []byte) (*types.ResourceEnvelope, error)

ParseJSONToEnvelope parses FHIR JSON and returns a fully populated envelope with Proto attached.

func ResourceType

func ResourceType(resource any) (string, error)

ResourceType returns the FHIR resource type carried by a typed R4 resource.

func ResourceTypeOfProto

func ResourceTypeOfProto(v any) (string, error)

ResourceTypeOfProto returns the FHIR resource type for a supported Google FHIR R4 proto value.

func ToEnvelope

func ToEnvelope(resource any) (*types.ResourceEnvelope, error)

ToEnvelope converts a typed Google FHIR R4 resource to a canonical envelope. The original protobuf value is retained in the returned envelope's Proto field.

func ToJSON

func ToJSON(resource any) ([]byte, error)

ToJSON converts a typed Google FHIR R4 resource to canonical FHIR JSON.

Types

type GoogleR4Codec

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

GoogleR4Codec implements ProtoCodec using Google FHIR Go R4 protobufs.

func NewGoogleR4Codec

func NewGoogleR4Codec() *GoogleR4Codec

NewGoogleR4Codec returns a GoogleR4Codec ready for use.

func (*GoogleR4Codec) ParseJSONToEnvelope

func (c *GoogleR4Codec) ParseJSONToEnvelope(resourceType string, data []byte) (*types.ResourceEnvelope, error)

ParseJSONToEnvelope parses FHIR JSON into proto and returns a fully populated envelope.

func (*GoogleR4Codec) ParseJSONToProto

func (c *GoogleR4Codec) ParseJSONToProto(resourceType string, data []byte) (any, error)

ParseJSONToProto validates resourceType and parses FHIR JSON into a Google R4 ContainedResource.

func (*GoogleR4Codec) ProtoToEnvelope

func (c *GoogleR4Codec) ProtoToEnvelope(resourceType string, protoVal any) (*types.ResourceEnvelope, error)

ProtoToEnvelope converts proto to JSON, parses through types.JSONCodec, and attaches the proto value.

func (*GoogleR4Codec) ProtoToJSON

func (c *GoogleR4Codec) ProtoToJSON(resourceType string, protoVal any) ([]byte, error)

ProtoToJSON converts a supported Google R4 proto resource to canonical FHIR JSON.

type ProtoCodec

type ProtoCodec interface {
	ParseJSONToProto(resourceType string, data []byte) (any, error)
	ParseJSONToEnvelope(resourceType string, data []byte) (*types.ResourceEnvelope, error)
	ProtoToJSON(resourceType string, proto any) ([]byte, error)
	ProtoToEnvelope(resourceType string, proto any) (*types.ResourceEnvelope, error)
}

ProtoCodec converts between FHIR JSON, provider-specific protobuf messages, and types.ResourceEnvelope values.

Directories

Path Synopsis
Package r4 exposes ergonomic aliases for the pinned Google FHIR R4 protobuf messages used by package proto.
Package r4 exposes ergonomic aliases for the pinned Google FHIR R4 protobuf messages used by package proto.

Jump to

Keyboard shortcuts

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