view

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

README

haistack-view (pkg/view)

Execute FHIR ViewDefinition resources into structured JSON rows for AI context, analytics, permissioned data access, and SQL-on-FHIR operations.

Import path: github.com/degoke/haistack/pkg/view.


What it does

A FHIR ViewDefinition is a declarative tabular projection over FHIR data. This package turns those definitions into runnable views:

Stage API Behavior
Parse ParseDefinition, RegisterViewDefinition Validate FHIRPath in columns/filters at register time
Register Registry.Register Named/versioned in-memory catalog
Execute Executor.Execute Scan store, apply filters, expand nested selects
Export ExportService, RunService Async NDJSON/CSV/Parquet artifacts with watermarks
SQL SQLQueryEngine Read-only SQL over Postgres reporting tables (analytics mode)

Core execution flow:

ViewDefinition JSON → ViewSpec → ListIDs/Read → FHIRPath → []map[string]any rows

In short: given a ViewDefinition and a store.ResourceStore, produce structured JSON rows (optionally paginated, authorized, audited, or materialized).

Built-in packaged views live in builtins.go (PatientSummaryView, AppointmentView, ObservationView). Tests in view_test.go and loader_test.go exercise parsing, nested forEach, reference joins, and row encoding.


How it fits in the ecosystem

FHIR resources (store.ResourceStore)
        │
        ├── pkg/search ──► candidate IDs (metadata.searchParams)
        │
        ▼
   view.Executor ◄── pkg/fhirpath (columns, where, forEach)
        │
        ├──► pkg/analytics (refresh / export sinks)
        ├──► pkg/ai (LLM context from Result.Rows)
        ├──► pkg/parquetfhir (_parquetLayout=fhir exports)
        ├──► pkg/auth (ViewAuthorizer + permissions[])
        └──► pkg/audit (LogViewAccess)

HTTP: pkg/http wires $viewdefinition-run, $viewdefinition-export,
$materialize, $sqlquery-run when runtime analytics/view services are enabled.
Layer Role
search Index-backed prefilters (metadata.searchParams)
fhirpath Field reads, filters, resolve(), memberOf()
view Structured projections (this package)
analytics Orchestrate runs into reporting tables or file sinks
ai Interactive tools consume the same executor

Module manifests declare view names in module.json; installers register packaged ViewDefinition JSON into a shared registry at runtime startup.


When to use it

  • Reporting columns — flatten Patient/Observation/Appointment fields for dashboards
  • AI context — stable JSON rows instead of raw resource blobs
  • Permissioned reads — declare permissions on the view; wire Authorizer
  • Lakehouse export — Parquet-on-FHIR nested layouts via WriteParquetFHIRExport
  • Join-like shapes — nested forEach over references resolved through the store

Prefer pkg/search when you only need resource lists. Prefer pkg/fhirpath alone for ad hoc field reads on one envelope. Prefer pkg/analytics when the destination is a reporting table or scheduled export job.


Usage modes

1. Register and execute (library)

From doc.go and view_test.go (TestParseDefinition_ValidView):

engine, err := fhirpath.NewEngine(fhirpath.Config{})
if err != nil { /* handle */ }

reg := view.NewRegistry()
if _, err := reg.Register(view.PatientSummaryView(), engine); err != nil {
    // handle
}

exec, err := view.NewExecutor(view.Config{
    Resources: resourceStore,
    Engine:    engine,
    Registry:  reg,
})
if err != nil { /* handle */ }

res, err := exec.Execute(ctx, view.ExecuteRequest{
    ViewName: "patient_summary_view",
    Limit:    10,
})
// res.Rows, res.Total, res.NextOffset, res.Metadata

Built-in patient_summary_view declares five columns and permission read-patient-summary (see TestParseDefinition_ValidView).

2. Custom ViewDefinition JSON

Nested forEach (one row per phone):

def := []byte(`{
    "resourceType": "ViewDefinition",
    "name": "patient_phones_foreach",
    "version": "1.0.0",
    "resource": "Patient",
    "select": [{
        "column": [{"name": "id", "path": "Patient.id"}],
        "select": [{
            "forEach": "Patient.telecom.where(system = 'phone')",
            "column": [{"name": "phone", "path": "value"}]
        }]
    }]
}`)
spec, err := view.ParseDefinition(def, engine)
_, err = reg.Register(def, engine)

Reference join (Appointment → Patient) uses typed references in forEach collections; the executor loads targets via ResourceStore.Read (see README join example and gap_closure_test.go).

3. Search-driven execution

When Executor.Config.Search is wired, views can prefilter with index-backed search:

"metadata": {
  "searchParams": "status=final",
  "searchMode": "auto"
}

searchMode=index requires search wiring; FHIRPath where clauses still apply as a residual check. _since on execute adds _lastUpdated=gt... to the search query.

4. HTTP SQL-on-FHIR operations
Operation Endpoint Notes
$viewdefinition-run POST /fhir/ViewDefinition/$viewdefinition-run or POST /fhir/$viewdefinition-run Sync JSON/CSV/NDJSON/Parquet
$viewdefinition-export POST /fhir/ViewDefinition/$viewdefinition-export Async export; _since watermarks
$materialize POST /fhir/ViewDefinition/$materialize Async materialized view refresh
$sqlquery-run POST /fhir/Library/$sqlquery-run Read-only SQL over reporting tables

Export artifacts download at $viewdefinition-export/files/{jobId}/{filename}. Async jobs persist under {dataDir}/jobs/* when runtime.WithDataDir is set.

Query/body parameters: _subject, _actor, _format, _parquetLayout, _parquetTimestampEncoding (see Limits below). ExportService.Kickoff defaults to NDJSON when no format is specified.

5. Materialized views
exec, err := view.NewExecutor(view.Config{
    Resources:         resourceStore,
    Engine:            engine,
    Registry:          reg,
    MaterializedViews: materializedViewStore,
})
// View metadata: {"materialize": "true", "materializeKey": "id"}
res, err := exec.Execute(ctx, view.ExecuteRequest{
    ViewName: "patient_summary_materialized",
})

Requires ViewMaterializeService for HTTP $materialize (Postgres analytics wiring).

6. Authorization and audit

Optional Config.Authorizer enforces declared permissions before reads. Optional Config.AuditLogger records success, denial, and resolution errors. Both seams are optional for embedded/library use.

7. Parquet and large exports

WriteParquetFHIRExport streams through temp NDJSON spill and row groups (default 1000 rows). Prefer it over CollectMatchingResources for large datasets — the latter materializes every match in memory (export_service_test.go, parquet_fhir_export.go).

_parquetLayout=flat streams flat columns; _parquetLayout=fhir emits Parquet-on-FHIR nested layouts via pkg/parquetfhir. Timestamp annotations default to INT64 TIMESTAMP(MILLIS); _parquetTimestampEncoding=int96 selects spec INT96.


Supported ViewDefinition subset

  • One source resource type per view (resource).
  • Root select array (multiple entries cross-join).
  • Nested select, forEach, forEachOrNull, and unionAll.
  • Column paths prefixed with a resource type (for example Patient.id) evaluate against the root resource; relative paths evaluate against the current forEach item.
  • Typed relative references in forEach collections resolve through the resource store.
  • Optional root filters (where) as FHIRPath predicates.
  • Materialization via metadata.materialize / metadata.materializeKey.
  • Declared permissions as top-level permissions (v1 extension).

Row encoding

From encode.go and encode_test.go:

  • Empty FHIRPath result → null (or [] when collection: true)
  • Singleton scalar → JSON scalar (or one-element array when collection: true)
  • Multi-item result → JSON array; scalar columns without collection: true → ErrRowEncoding
  • Google FHIR Date, DateTime, Time, Instant → FHIR string literals
  • FHIR choice wrappers unwrap to their set branch
  • system.Quantity → {value, unit, system, code}
  • Unsupported complex objects → ErrRowEncoding

Configure FHIRPath with Resolve and Terminology for resolve() and memberOf().


Execution metadata

ResultMetadata fields differ by export mode:

Field Flat Execute FHIR parquet export
scanned Candidate IDs considered Same
filtered Expanded view row count Matching source resource count
maxLastUpdated Latest among returned rows Latest among exported resources

Incremental watermarks prefer maxLastUpdated (data clock). Stored watermarks are inclusive; search prefilters use _lastUpdated=gt{watermark} while envelope checks use strict LastUpdated.Before(since).


Examples from this repo

Registry helper (loader_test.go):

spec, err := view.RegisterViewDefinition(reg, view.PatientSummaryView(), engine)

Export watermark behavior (export_service_test.go):

  • TestExportServiceAdvancesWatermarkAfterAllViewsSucceed
  • TestExportServiceDoesNotAdvanceWatermarkOnFailure
  • TestExportServiceRollsBackPartialFilesOnFailure

SQL over reporting tables (gap_closure_test.go TestSQLQueryEngine_SelectReportingRows):

engine, _ := view.NewSQLQueryEngine(view.SQLQueryConfig{
    Reporting: reportingTableStore,
})
rows, err := engine.Query(ctx, "SELECT id, given FROM patient_summary_view")

Contained reference resolution (gap_closure_test.go TestResolveContainedReference).


Limits

  • Reference resolution: typed, absolute URL, URN, contained #, and FHIRPath resolve().
  • $sqlquery-run requires Postgres analytics wiring and refreshed reporting tables.
  • SQLite/edge runtimes support view run/export HTTP when executor is wired; async export/materialize needs a job runner and data directory.
  • Search-driven execution requires search wiring; searchMode=index fails without index.
  • ExecuteRequest.Parameters is passed to auth and audit only (no FHIRPath substitution yet).
  • Parameters parsing accepts valueString wrappers only (typed FHIR parameters TODO).
  • Postgres store.BlobStore BYTEA still materializes full blobs; prefer object-store adapters or lakehouse filesystem for multi-GB parquet uploads.

Documentation

Overview

Package view implements haistack-view, a standalone Go library for executing FHIR ViewDefinition resources into structured JSON rows.

Scope

The package executes SQL-on-FHIR ViewDefinition projections in-process:

  • Single root resource type per view.
  • Scan-based execution via store.ResourceStore.ListIDs and Read.
  • Flat and nested selects with forEach, forEachOrNull, unionAll, and reference joins resolved through the resource store.
  • JSON row output with row-level pagination for expanded results.
  • Optional pluggable authorization, audit hooks, and materialized view persistence.

ViewDefinition support

The canonical input is a FHIR ViewDefinition resource serialized as JSON. Supported constructs include:

  • One source resource type per view (the top-level "resource" field).
  • Root and nested select trees with column, select, forEach, forEachOrNull, and unionAll blocks.
  • Optional root filters expressed as FHIRPath predicates in "where" clauses.
  • Materialization metadata: metadata.materialize and metadata.materializeKey.
  • Declared permissions as a top-level "permissions" array; auth.ViewAuthorizer is the stack adapter.

Public API

The package centers on three public types:

  • ParseDefinition / DefinitionParser: load a ViewDefinition JSON payload and produce a normalized ViewSpec. A FHIRPath engine is required so that filter and column expressions are validated at parse time.
  • Registry: in-memory store for named/versioned ViewSpec values. Registering a view compiles its expressions immediately.
  • Executor: runs a registered view against a store.ResourceStore and returns structured rows.

Typical usage:

engine, err := fhirpath.NewEngine(fhirpath.Config{})
if err != nil { /* handle */ }

reg := view.NewRegistry()
if _, err := reg.Register(view.PatientSummaryView(), engine); err != nil {
    // handle
}

exec, err := view.NewExecutor(view.Config{
    Resources: resources,
    Engine:    engine,
    Registry:  reg,
})
if err != nil { // handle
}

res, err := exec.Execute(ctx, view.ExecuteRequest{ViewName: "patient_summary_view"})

Execution model

Execute resolves the view, applies the optional authorizer, scans the source resource type, evaluates filter FHIRPath for each resource, expands the select tree into zero or more rows per resource, and returns rows.

Result.Total is the number of output rows across the entire scan, not just the returned page. NextOffset is set when additional rows are available.

Authorization and audit

If the Executor is configured with an Authorizer and the view declares permissions, AuthorizeView is called before any resources are read. If the Executor is configured with an AuditLogger, LogViewAccess is called on success, denial, and view resolution errors. Both seams are optional; the package is fully usable without them.

Integration points

  • haistack-modules: views are declared by name in module metadata today; installers register packaged ViewDefinition resources into a view registry.
  • haistack-ai: consumes Result.Rows directly as structured context.
  • haistack-auth: auth.ViewAuthorizer implements Authorizer.
  • haistack-analytics: reuses the same Executor for reporting-table refresh.
  • store.MaterializedViewStore: optional persistence when metadata.materialize is set and Executor.Config.MaterializedViews is wired.

Index

Constants

View Source
const (
	// TimestampEncodingInt64 writes TIMESTAMP(MILLIS) on INT64 (default).
	TimestampEncodingInt64 = parquetfhir.TimestampEncodingInt64
	// TimestampEncodingInt96 writes spec INT96 + TIMESTAMP(MILLIS).
	TimestampEncodingInt96 = parquetfhir.TimestampEncodingInt96
)
View Source
const DefaultParquetPageSize = 1000

DefaultParquetPageSize is the default executor page size for streaming parquet export.

View Source
const DefaultParquetRowGroupSize = 1000

DefaultParquetRowGroupSize controls how many rows are buffered per parquet row group.

View Source
const ParquetContentType = "application/vnd.apache.parquet"

ParquetContentType is the SQL-on-FHIR native media type for parquet output.

View Source
const TypeViewMaterialize = jobs.TypeViewMaterialize

TypeViewMaterialize is the job type for ViewDefinition materialization.

Variables

View Source
var (
	// ErrInvalidViewDefinition is returned when a ViewDefinition JSON payload is
	// malformed or fails structural validation.
	ErrInvalidViewDefinition = errors.New("view: invalid ViewDefinition")

	// ErrUnsupportedFeature is returned when a ViewDefinition uses a feature
	// outside the executable subset (for example multiple source resource types).
	ErrUnsupportedFeature = errors.New("view: unsupported ViewDefinition feature")

	// ErrViewNotFound is returned when a named/versioned view is not registered.
	ErrViewNotFound = errors.New("view: view not found")

	// ErrViewAlreadyRegistered is returned when registering a view whose name and
	// version already exist in the registry.
	ErrViewAlreadyRegistered = errors.New("view: view already registered")

	// ErrUnauthorized is returned when the configured authorizer rejects an
	// execution request.
	ErrUnauthorized = errors.New("view: unauthorized")

	// ErrRowEncoding is returned when a column result cannot be normalized into a
	// JSON-safe value.
	ErrRowEncoding = errors.New("view: row encoding failed")

	// ErrMissingEngine is returned when an Executor is configured without a
	// FHIRPath engine.
	ErrMissingEngine = errors.New("view: missing FHIRPath engine")

	// ErrMissingResourceStore is returned when an Executor is configured without
	// a resource store.
	ErrMissingResourceStore = errors.New("view: missing resource store")

	// ErrMissingMaterializedViewStore is returned when materialization is requested
	// without a configured MaterializedViewStore.
	ErrMissingMaterializedViewStore = errors.New("view: missing materialized view store")

	// ErrMissingReportingTables is returned when SQL query execution is requested
	// without a configured ReportingTableStore.
	ErrMissingReportingTables = errors.New("view: missing reporting table store")
)

Functions

func AppointmentView

func AppointmentView() []byte

AppointmentView returns an example FHIR ViewDefinition for booked appointments with a status/date filter.

func IsOperationOutputFormat

func IsOperationOutputFormat(raw string) bool

IsOperationOutputFormat reports whether raw selects a SQL-on-FHIR operation artifact encoding (csv, ndjson, parquet) rather than a FHIR response envelope.

ParseOutputFormat("json") returns FormatJSON because json is a valid FHIR envelope for Parameters/Binary responses, but IsOperationOutputFormat("json") is false so Accept-header negotiation still applies to json/xml envelopes.

func IsParquetFile

func IsParquetFile(data []byte) bool

IsParquetFile reports whether data begins with the parquet magic bytes.

func LatestTimestamp

func LatestTimestamp(a, b time.Time) time.Time

LatestTimestamp returns the later of two timestamps.

func ObservationView

func ObservationView() []byte

ObservationView returns an example FHIR ViewDefinition for final observations with scalar quantity extraction.

func ParquetFileRowCount

func ParquetFileRowCount(data []byte) (int64, error)

ParquetFileRowCount returns the number of rows in a parquet file payload.

func ParseLimitOffset

func ParseLimitOffset(limitRaw, offsetRaw string) (int, int, error)

ParseLimitOffset parses _limit and _offset query parameters.

func PatientSummaryView

func PatientSummaryView() []byte

PatientSummaryView returns an example FHIR ViewDefinition for a flat patient summary. All selected columns resolve to JSON scalars in v1.

func WatermarkAdvanceTime

func WatermarkAdvanceTime(maxUpdated, fallback time.Time) time.Time

WatermarkAdvanceTime returns the timestamp to persist for incremental export or refresh. When exported resources carry LastUpdated, that data clock is preferred over the process clock to avoid skew-related gaps or duplicates.

func WriteParquetOutput

func WriteParquetOutput(ctx context.Context, w io.Writer, result *Result, execReq ExecuteRequest, layout ParquetLayout, exec *Executor) (int, error)

WriteParquetOutput writes flat view rows or Parquet-on-FHIR resources to w.

func WriteParquetResult

func WriteParquetResult(w io.Writer, result *Result) error

WriteParquetResult writes a complete view result as one parquet file.

Types

type AuditLogger

type AuditLogger interface {
	LogViewAccess(ctx context.Context, rec AuditRecord) error
}

AuditLogger is the pluggable audit seam. It is invoked on both successful and denied executions. The package remains usable without an audit logger.

type AuditLoggerFunc

type AuditLoggerFunc func(ctx context.Context, rec AuditRecord) error

AuditLoggerFunc adapts a function to the AuditLogger interface.

func (AuditLoggerFunc) LogViewAccess

func (f AuditLoggerFunc) LogViewAccess(ctx context.Context, rec AuditRecord) error

LogViewAccess implements AuditLogger.

type AuditRecord

type AuditRecord struct {
	ViewName   string            `json:"viewName"`
	Version    string            `json:"version,omitempty"`
	Actor      string            `json:"actor"`
	Subject    string            `json:"subject,omitempty"`
	Outcome    string            `json:"outcome"`
	Details    map[string]string `json:"details,omitempty"`
	Parameters map[string]any    `json:"parameters,omitempty"`
	Timestamp  time.Time         `json:"timestamp"`
}

AuditRecord captures one view access event for the audit seam. It is intentionally smaller than store.AuditRecord and scoped to view execution.

type AuditStoreAdapter

type AuditStoreAdapter struct {
	Store store.AuditStore
	Now   func() time.Time
	NewID func() string
}

AuditStoreAdapter writes view audit records through pkg/audit into a store.AuditStore. Action naming is owned by pkg/audit (execute-view). Set NewID for deterministic event IDs (research provenance bundles); the default is a UUID.

func (*AuditStoreAdapter) LogViewAccess

func (a *AuditStoreAdapter) LogViewAccess(ctx context.Context, rec AuditRecord) error

LogViewAccess converts a view.AuditRecord to a canonical audit event and appends it.

type AuthRequest

type AuthRequest struct {
	ViewName     string         `json:"viewName"`
	Version      string         `json:"version,omitempty"`
	ResourceType string         `json:"resourceType"`
	Actor        string         `json:"actor"`
	Subject      string         `json:"subject,omitempty"`
	Permissions  []string       `json:"permissions,omitempty"`
	Parameters   map[string]any `json:"parameters,omitempty"`
}

AuthRequest carries the authorization context for one view execution.

type Authorizer

type Authorizer interface {
	AuthorizeView(ctx context.Context, req AuthRequest) error
}

Authorizer is the pluggable authorization seam. If an Executor is configured without an Authorizer, executions proceed without permission checks. If an Authorizer is configured and the view declares permissions, the Authorizer is invoked before any resources are read.

type AuthorizerFunc

type AuthorizerFunc func(ctx context.Context, req AuthRequest) error

AuthorizerFunc adapts a function to the Authorizer interface.

func (AuthorizerFunc) AuthorizeView

func (f AuthorizerFunc) AuthorizeView(ctx context.Context, req AuthRequest) error

AuthorizeView implements Authorizer.

type ColumnInfo

type ColumnInfo struct {
	Name string `json:"name"`
	Type string `json:"type,omitempty"`
}

ColumnInfo describes one output column for result metadata.

type ColumnSpec

type ColumnSpec struct {
	Name        string
	Path        string
	Type        string
	Description string
	Collection  bool
	// contains filtered or unexported fields
}

ColumnSpec describes one output column.

type Config

type Config struct {
	Resources         store.ResourceStore
	Engine            fhirpath.Engine
	Authorizer        Authorizer
	Audit             AuditLogger
	Registry          *Registry
	MaterializedViews store.MaterializedViewStore
	Search            search.Executor
	SearchRegistry    search.Registry
	SearchPlanner     search.Planner
	BaseURL           string
	ResolveLogicalID  func(ctx context.Context, logicalID string) (resourceType, id string, ok bool)
	ProfileCatalog    validate.ProfileCatalog
	Now               func() time.Time
}

Config configures an Executor. The resource store and FHIRPath engine are required; authorizer, audit logger, and registry are optional but required for their respective features. If Now is nil, time.Now is used.

type DefinitionParser

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

DefinitionParser loads and validates a FHIR ViewDefinition resource from JSON bytes. A FHIRPath engine is required so that all filter and column expressions are validated at parse time. Use NewDefinitionParser to create one.

func NewDefinitionParser

func NewDefinitionParser(engine fhirpath.Engine) (*DefinitionParser, error)

NewDefinitionParser returns a parser that validates FHIRPath expressions with the supplied engine when parsing. Engine must be non-nil.

func (*DefinitionParser) Parse

func (p *DefinitionParser) Parse(def []byte) (*ViewSpec, error)

Parse loads and validates a ViewDefinition payload into a normalized ViewSpec.

type ExecuteRequest

type ExecuteRequest struct {
	ViewName          string
	Version           string
	Actor             string
	Subject           string
	Limit             int
	Offset            int
	Parameters        map[string]any
	Since             time.Time
	Materialize       bool
	TimestampEncoding TimestampEncoding
}

ExecuteRequest carries runtime parameters for one view execution.

func ExecRequestForExport

func ExecRequestForExport(result *Result, actor string) ExecuteRequest

ExecRequestForExport returns the execute request used for Parquet-on-FHIR export.

type Executor

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

Executor runs a parsed ViewDefinition against a store.ResourceStore.

func NewExecutor

func NewExecutor(cfg Config) (*Executor, error)

NewExecutor validates the configuration and returns an Executor.

func (*Executor) CollectMatchingResources deprecated

func (e *Executor) CollectMatchingResources(ctx context.Context, req ExecuteRequest) ([]map[string]any, string, error)

CollectMatchingResources returns full FHIR resources matching a view's filters.

Deprecated: prefer WriteParquetFHIRExport for large exports. This helper materializes every matching resource in memory and is not suitable for lakehouse-scale datasets.

func (*Executor) Execute

func (e *Executor) Execute(ctx context.Context, req ExecuteRequest) (*Result, error)

Execute resolves the registered view, applies optional authorization, scans the source resource type, filters resources, extracts columns, and returns rows. Audit records are written for both success and denial when an Audit logger is configured.

func (*Executor) ExecuteInline

func (e *Executor) ExecuteInline(ctx context.Context, req ExecuteRequest, def []byte) (*Result, error)

ExecuteInline runs an inline ViewDefinition payload with the same authorization, audit, and scan behavior as Execute.

func (*Executor) ResolveView

func (e *Executor) ResolveView(name, version string) (*ViewSpec, error)

ResolveView resolves a registered view without executing it. It is useful to validate an execution policy before touching the resource store.

type ExportFile

type ExportFile struct {
	ViewName          string            `json:"viewName"`
	Version           string            `json:"version"`
	OutputName        string            `json:"outputName"`
	Filename          string            `json:"filename"`
	RowCount          int               `json:"rowCount"`
	Format            string            `json:"format"`
	ParquetLayout     ParquetLayout     `json:"parquetLayout,omitempty"`
	TimestampEncoding TimestampEncoding `json:"timestampEncoding,omitempty"`
}

ExportFile describes one exported artifact.

type ExportFileStore

type ExportFileStore interface {
	Put(ctx context.Context, jobID, filename string, data []byte, contentType string) error
	Get(ctx context.Context, jobID, filename string) ([]byte, string, error)
	DeleteJob(ctx context.Context, jobID string) error
}

ExportFileStore persists view export artifacts keyed by job id and filename.

type ExportFileStoreWithStream

type ExportFileStoreWithStream interface {
	ExportFileStore
	PutStream(ctx context.Context, jobID, filename string, r io.Reader, size int64, contentType string) error
	Open(ctx context.Context, jobID, filename string) (io.ReadCloser, string, error)
}

ExportFileStoreWithStream optionally writes artifacts from an io.Reader and opens them without requiring the caller to materialize the full payload as []byte.

func NewInMemoryExportFileStore

func NewInMemoryExportFileStore() ExportFileStoreWithStream

NewInMemoryExportFileStore returns an in-memory ExportFileStoreWithStream.

type ExportService

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

ExportService orchestrates ViewDefinition/$viewdefinition-export operations.

func NewExportService

func NewExportService(cfg ExportServiceConfig) (*ExportService, error)

NewExportService validates configuration and returns an ExportService.

func (*ExportService) Cancel

func (s *ExportService) Cancel(ctx context.Context, jobID string) error

Cancel requests cancellation of an in-progress export job.

func (*ExportService) FileURL

func (s *ExportService) FileURL(jobID, filename string) string

FileURL returns the download URL for one exported artifact.

func (*ExportService) GetFile

func (s *ExportService) GetFile(ctx context.Context, jobID, filename string) ([]byte, string, error)

GetFile returns one exported artifact.

func (*ExportService) GetJob

func (s *ExportService) GetJob(ctx context.Context, jobID string) (*ViewExportJob, error)

GetJob returns the current export job state.

func (*ExportService) JobHandler

func (s *ExportService) JobHandler() jobs.Handler

JobHandler returns a jobs.Handler for async execution.

func (*ExportService) Kickoff

Kickoff creates an async export job.

func (*ExportService) OpenFile

func (s *ExportService) OpenFile(ctx context.Context, jobID, filename string) (io.ReadCloser, string, error)

OpenFile streams one exported artifact without assembling a full []byte.

func (*ExportService) RunJob

func (s *ExportService) RunJob(ctx context.Context, jobID string) error

RunJob executes one export job synchronously.

func (*ExportService) StatusURL

func (s *ExportService) StatusURL(jobID string) string

StatusURL returns the polling URL for a job.

type ExportServiceConfig

type ExportServiceConfig struct {
	Jobs      ViewExportJobStore
	Files     ExportFileStore
	Executor  *Executor
	Watermark WatermarkAdvancer
	JobQueue  store.JobStore
	BasePath  string
	Now       func() time.Time
	NewID     func() string
}

ExportServiceConfig configures ExportService.

type ExportStatus

type ExportStatus string

ExportStatus tracks view export job lifecycle.

const (
	ExportInProgress ExportStatus = "in-progress"
	ExportComplete   ExportStatus = "complete"
	ExportError      ExportStatus = "error"
	ExportCancelled  ExportStatus = "cancelled"
)

type ExportWriter

type ExportWriter interface {
	WriteExport(ctx context.Context, filename string, result *Result, format OutputFormat) error
}

ExportWriter receives one exported view artifact.

func NewFileExportWriter

func NewFileExportWriter(store ExportFileStore, jobID string) ExportWriter

NewFileExportWriter returns a writer that persists artifacts for one export job.

type FileExportWriter

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

FileExportWriter stores export artifacts in an ExportFileStore scoped to one job.

func (*FileExportWriter) WriteExport

func (w *FileExportWriter) WriteExport(ctx context.Context, filename string, result *Result, format OutputFormat) error

type FilterSpec

type FilterSpec struct {
	Path        string
	Description string
	// contains filtered or unexported fields
}

FilterSpec describes one root filter predicate.

type LocalExportFileStore

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

LocalExportFileStore persists view export artifacts on the local filesystem.

func NewLocalExportFileStore

func NewLocalExportFileStore(root string) (*LocalExportFileStore, error)

NewLocalExportFileStore creates a filesystem-backed ExportFileStore.

func (*LocalExportFileStore) DeleteJob

func (s *LocalExportFileStore) DeleteJob(_ context.Context, jobID string) error

func (*LocalExportFileStore) Get

func (s *LocalExportFileStore) Get(ctx context.Context, jobID, filename string) ([]byte, string, error)

func (*LocalExportFileStore) Open

func (s *LocalExportFileStore) Open(_ context.Context, jobID, filename string) (io.ReadCloser, string, error)

func (*LocalExportFileStore) Put

func (s *LocalExportFileStore) Put(ctx context.Context, jobID, filename string, data []byte, contentType string) error

func (*LocalExportFileStore) PutStream

func (s *LocalExportFileStore) PutStream(_ context.Context, jobID, filename string, r io.Reader, size int64, contentType string) error

type LocalMaterializeJobStore

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

LocalMaterializeJobStore persists MaterializeJob records as JSON files.

func NewLocalMaterializeJobStore

func NewLocalMaterializeJobStore(dir string) (*LocalMaterializeJobStore, error)

NewLocalMaterializeJobStore creates a filesystem-backed MaterializeJobStore.

func (*LocalMaterializeJobStore) Create

func (*LocalMaterializeJobStore) Get

func (*LocalMaterializeJobStore) Update

type LocalViewExportJobStore

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

LocalViewExportJobStore persists ViewExportJob records as JSON files.

func NewLocalViewExportJobStore

func NewLocalViewExportJobStore(dir string) (*LocalViewExportJobStore, error)

NewLocalViewExportJobStore creates a filesystem-backed ViewExportJobStore.

func (*LocalViewExportJobStore) Create

func (*LocalViewExportJobStore) Get

func (*LocalViewExportJobStore) Update

type MatchingResourceStats

type MatchingResourceStats struct {
	Scanned            int
	Filtered           int
	Written            int
	SourceResourceType string
	MaxLastUpdated     time.Time
}

MatchingResourceStats summarizes FHIR resource matching for Parquet-on-FHIR export.

func WriteParquetFHIRExport

func WriteParquetFHIRExport(ctx context.Context, w io.Writer, exec *Executor, req ExecuteRequest) (int, MatchingResourceStats, error)

WriteParquetFHIRExport writes Parquet-on-FHIR nested resources for one view.

type MaterializeJob

type MaterializeJob struct {
	ID          string             `json:"id"`
	Status      MaterializeStatus  `json:"status"`
	Request     MaterializeRequest `json:"request"`
	RowCount    int                `json:"rowCount,omitempty"`
	Progress    string             `json:"progress,omitempty"`
	LastError   string             `json:"lastError,omitempty"`
	CreatedAt   time.Time          `json:"createdAt"`
	CompletedAt time.Time          `json:"completedAt,omitempty"`
	Cancelled   bool               `json:"cancelled,omitempty"`
}

MaterializeJob is a durable materialize job record.

type MaterializeJobPayload

type MaterializeJobPayload struct {
	JobID string `json:"jobId"`
}

MaterializeJobPayload is the background job payload for materialize execution.

type MaterializeJobStore

type MaterializeJobStore interface {
	Create(ctx context.Context, job MaterializeJob) error
	Get(ctx context.Context, id string) (*MaterializeJob, error)
	Update(ctx context.Context, job MaterializeJob) error
}

MaterializeJobStore persists materialize jobs.

func NewInMemoryMaterializeJobStore

func NewInMemoryMaterializeJobStore() MaterializeJobStore

NewInMemoryMaterializeJobStore returns an ephemeral job store for tests and edge mode.

type MaterializeRequest

type MaterializeRequest struct {
	ViewName   string    `json:"viewName"`
	Version    string    `json:"version"`
	TargetName string    `json:"targetName,omitempty"`
	Since      time.Time `json:"since,omitempty"`
	Actor      string    `json:"actor,omitempty"`
}

MaterializeRequest captures parameters for one materialize operation.

type MaterializeResult

type MaterializeResult struct {
	ViewName   string         `json:"viewName"`
	Version    string         `json:"version"`
	TargetName string         `json:"targetName"`
	RowCount   int            `json:"rowCount"`
	Metadata   ResultMetadata `json:"metadata"`
	UpdatedAt  time.Time      `json:"updatedAt"`
}

MaterializeResult is returned when a materialize job completes.

type MaterializeService

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

MaterializeService orchestrates ViewDefinition $materialize operations.

func NewMaterializeService

func NewMaterializeService(cfg MaterializeServiceConfig) (*MaterializeService, error)

NewMaterializeService validates configuration and returns a MaterializeService.

func (*MaterializeService) Cancel

func (s *MaterializeService) Cancel(ctx context.Context, jobID string) error

Cancel requests cancellation of an in-progress job.

func (*MaterializeService) GetJob

func (s *MaterializeService) GetJob(ctx context.Context, jobID string) (*MaterializeJob, error)

GetJob returns the current job state.

func (*MaterializeService) JobHandler

func (s *MaterializeService) JobHandler() jobs.Handler

JobHandler returns a jobs.Handler for async execution.

func (*MaterializeService) Kickoff

Kickoff creates an async materialize job.

func (*MaterializeService) Result

Result builds the completed operation result payload.

func (*MaterializeService) RunJob

func (s *MaterializeService) RunJob(ctx context.Context, jobID string) error

RunJob executes one materialize job synchronously.

func (*MaterializeService) StatusURL

func (s *MaterializeService) StatusURL(jobID string) string

StatusURL returns the polling URL for a job.

type MaterializeServiceConfig

type MaterializeServiceConfig struct {
	Jobs     MaterializeJobStore
	Executor *Executor
	JobQueue store.JobStore
	BasePath string
	Now      func() time.Time
	NewID    func() string
}

MaterializeServiceConfig configures MaterializeService.

type MaterializeStatus

type MaterializeStatus string

MaterializeStatus tracks materialize job lifecycle.

const (
	MaterializeInProgress MaterializeStatus = "in-progress"
	MaterializeComplete   MaterializeStatus = "complete"
	MaterializeError      MaterializeStatus = "error"
	MaterializeCancelled  MaterializeStatus = "cancelled"
)

type MemoryExportWriter

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

MemoryExportWriter stores exported artifacts in memory for tests and edge mode.

func NewMemoryExportWriter

func NewMemoryExportWriter() *MemoryExportWriter

NewMemoryExportWriter returns an in-memory ExportWriter.

func (*MemoryExportWriter) Get

func (w *MemoryExportWriter) Get(filename string) ([]byte, bool)

Get returns one exported artifact by filename.

func (*MemoryExportWriter) WriteExport

func (w *MemoryExportWriter) WriteExport(ctx context.Context, filename string, result *Result, format OutputFormat) error

WriteExport encodes one view result using the requested export format.

type OutputFormat

type OutputFormat string

OutputFormat selects SQL-on-FHIR operation output encoding.

const (
	FormatJSON    OutputFormat = "json"
	FormatNDJSON  OutputFormat = "ndjson"
	FormatCSV     OutputFormat = "csv"
	FormatParquet OutputFormat = "parquet"
)

func ParseOutputFormat

func ParseOutputFormat(raw string) OutputFormat

ParseOutputFormat maps SQL-on-FHIR _format values to OutputFormat.

type ParquetExportResult

type ParquetExportResult struct {
	RowCount       int
	MaxLastUpdated time.Time
}

ParquetExportResult summarizes a streamed flat view parquet export.

func WriteParquetExport

func WriteParquetExport(ctx context.Context, w io.Writer, exec *Executor, req ExecuteRequest, pageSize int) (ParquetExportResult, error)

WriteParquetExport streams a view export through paginated executor calls.

type ParquetLayout

type ParquetLayout string

ParquetLayout selects how Parquet output is encoded.

const (
	// ParquetLayoutFlat exports ViewDefinition flat columns (default).
	ParquetLayoutFlat ParquetLayout = "flat"
	// ParquetLayoutFHIR exports full nested FHIR resources using Parquet-on-FHIR.
	ParquetLayoutFHIR ParquetLayout = "fhir"
)

func ParseParquetLayout

func ParseParquetLayout(raw string) ParquetLayout

ParseParquetLayout maps _parquetLayout query values.

type ParquetRowWriter

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

ParquetRowWriter streams view rows into an Apache Parquet file.

func NewParquetRowWriter

func NewParquetRowWriter(w io.Writer, result *Result) (*ParquetRowWriter, error)

NewParquetRowWriter opens a parquet writer using the schema from result metadata.

func (*ParquetRowWriter) Close

func (pw *ParquetRowWriter) Close() error

Close flushes the parquet footer.

func (*ParquetRowWriter) RowCount

func (pw *ParquetRowWriter) RowCount() int

RowCount returns the number of rows written so far.

func (*ParquetRowWriter) WriteRows

func (pw *ParquetRowWriter) WriteRows(rows []map[string]any) error

WriteRows appends one batch of rows to the parquet file.

type Registry

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

Registry stores named/versioned views in memory for runtime lookup. It is safe for concurrent use. Registering a view compiles its FHIRPath expressions immediately with the supplied engine so that invalid expressions are caught at registration time.

func NewRegistry

func NewRegistry() *Registry

NewRegistry returns an empty in-memory view registry.

func (*Registry) Get

func (r *Registry) Get(name, version string) (*ViewSpec, error)

Get returns a registered view by name and version. Returns ErrViewNotFound when no matching view exists.

func (*Registry) List

func (r *Registry) List() []*ViewSpec

List returns all registered views. The returned slice is a copy; the underlying ViewSpec values are shared.

func (*Registry) Register

func (r *Registry) Register(def []byte, engine fhirpath.Engine) (*ViewSpec, error)

Register parses, validates, and stores a ViewDefinition. The name and version are taken from the ViewDefinition itself. All FHIRPath expressions are compiled with engine to fail fast on invalid expressions. If a view with the same name and version is already registered, ErrViewAlreadyRegistered is returned.

func (*Registry) Resolve

func (r *Registry) Resolve(name, version string) (*ViewSpec, error)

Resolve returns a registered view by name and version. If version is empty, the only registered version with that name is returned. If multiple versions are registered for the name and version is empty, ErrViewNotFound is returned.

func (*Registry) Unregister

func (r *Registry) Unregister(name, version string) error

Unregister removes a view from the registry. Returns ErrViewNotFound if the view was not registered.

type ReportingTableRef

type ReportingTableRef struct {
	ViewName    string
	ViewVersion string
	TableName   string
}

ReportingTableRef identifies one reporting table to load into the SQL engine.

type Result

type Result struct {
	ViewName    string
	Version     string
	Columns     []ColumnInfo
	Rows        []map[string]any
	Total       int
	Metadata    ResultMetadata
	NextOffset  *int
	ExecRequest *ExecuteRequest
}

Result is the structured output of a view execution.

type ResultMetadata

type ResultMetadata struct {
	ExecutedAt         time.Time     `json:"executedAt"`
	Duration           time.Duration `json:"duration"`
	SourceResourceType string        `json:"sourceResourceType"`
	Scanned            int           `json:"scanned"`
	Filtered           int           `json:"filtered"`
	// MaxLastUpdated is the latest resource LastUpdated among rows/resources included
	// in the result. Flat Execute counts expanded view rows; FHIR export counts
	// matching source resources written to parquet.
	MaxLastUpdated time.Time `json:"maxLastUpdated,omitempty"`
}

ResultMetadata captures execution-side metadata.

type RowEncoder

type RowEncoder struct{}

RowEncoder normalizes fhirpath.Value collections into JSON-safe values. Empty results become null; singletons become scalars; multi-item results become arrays. Complex objects are converted only when they are already representable from pkg/fhirpath.Value (currently system.Quantity); otherwise ErrRowEncoding is returned.

func (*RowEncoder) Encode

func (e *RowEncoder) Encode(values []fhirpath.Value) (any, error)

Encode converts a fhirpath collection to a JSON-safe value.

func (*RowEncoder) EncodeColumn

func (e *RowEncoder) EncodeColumn(values []fhirpath.Value, collection bool) (any, error)

EncodeColumn converts a FHIRPath collection to a JSON-safe value. When collection is true, singleton results are wrapped in a one-element array. When collection is false, multi-item results return ErrRowEncoding.

type RunService

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

RunService executes synchronous ViewDefinition runs.

func NewRunService

func NewRunService(executor *Executor) *RunService

NewRunService returns a RunService.

func (*RunService) Execute

func (s *RunService) Execute(ctx context.Context, req ViewRunRequest) ([]byte, string, error)

Execute runs a registered or inline ViewDefinition and encodes the result.

type SQLQueryEngine

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

SQLQueryEngine executes read-only SQL against reporting table snapshots.

func NewSQLQueryEngine

func NewSQLQueryEngine(tables store.ReportingTableStore) *SQLQueryEngine

NewSQLQueryEngine returns an engine backed by ReportingTableStore.

func (*SQLQueryEngine) Query

func (e *SQLQueryEngine) Query(ctx context.Context, sqlText string, tables []ReportingTableRef) (*SQLQueryResult, error)

Query executes one read-only SQL statement against loaded reporting tables. Table names correspond to sanitized view names from reporting metadata.

type SQLQueryRequest

type SQLQueryRequest struct {
	SQL    string
	Tables []ReportingTableRef
	Format OutputFormat
}

SQLQueryRequest carries one SQL-on-FHIR sqlquery-run request.

type SQLQueryResult

type SQLQueryResult struct {
	Columns []ColumnInfo     `json:"columns"`
	Rows    []map[string]any `json:"rows"`
}

SQLQueryResult is the tabular output of one SQL query.

type SQLQueryService

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

SQLQueryService executes SQL queries against reporting tables.

func NewSQLQueryService

func NewSQLQueryService(engine *SQLQueryEngine) *SQLQueryService

NewSQLQueryService returns a SQLQueryService.

func (*SQLQueryService) Execute

func (s *SQLQueryService) Execute(ctx context.Context, req SQLQueryRequest) ([]byte, string, error)

Execute runs one SQL query and encodes the result.

type SearchMode

type SearchMode string

SearchMode controls whether view execution uses the search index.

const (
	// SearchModeAuto uses search when configured and search params are available.
	SearchModeAuto SearchMode = "auto"
	// SearchModeIndex requires search-backed candidate resolution.
	SearchModeIndex SearchMode = "index"
	// SearchModeScan forces ListIDs scanning.
	SearchModeScan SearchMode = "scan"
)

type SelectSpec

type SelectSpec struct {
	Columns       []ColumnSpec
	Children      []SelectSpec
	ForEach       string
	ForEachOrNull string
	UnionAll      []SelectSpec
	// contains filtered or unexported fields
}

SelectSpec is one node in a ViewDefinition select tree. Columns are evaluated in the current iteration context; nested Children are cross-joined with parent rows; ForEach / ForEachOrNull iterate over a FHIRPath collection; UnionAll concatenates sibling branches.

func (*SelectSpec) FlattenColumns

func (s *SelectSpec) FlattenColumns() []ColumnSpec

FlattenColumns returns output columns in tree order for metadata.

type TimestampEncoding

type TimestampEncoding = parquetfhir.TimestampEncoding

TimestampEncoding selects Parquet-on-FHIR date annotation physical types.

func NormalizeTimestampEncoding

func NormalizeTimestampEncoding(enc TimestampEncoding) TimestampEncoding

NormalizeTimestampEncoding returns int64 unless enc is explicitly int96.

func ParseTimestampEncoding

func ParseTimestampEncoding(raw string) (TimestampEncoding, error)

ParseTimestampEncoding maps _parquetTimestampEncoding query or Parameters body values.

type ViewExportJob

type ViewExportJob struct {
	ID          string            `json:"id"`
	Status      ExportStatus      `json:"status"`
	Request     ViewExportRequest `json:"request"`
	Files       []ExportFile      `json:"files,omitempty"`
	Progress    string            `json:"progress,omitempty"`
	LastError   string            `json:"lastError,omitempty"`
	CreatedAt   time.Time         `json:"createdAt"`
	CompletedAt time.Time         `json:"completedAt,omitempty"`
	Cancelled   bool              `json:"cancelled,omitempty"`
}

ViewExportJob tracks async export progress.

type ViewExportJobPayload

type ViewExportJobPayload struct {
	JobID string `json:"jobId"`
}

ViewExportJobPayload is the background job payload for export execution.

type ViewExportJobStore

type ViewExportJobStore interface {
	Create(ctx context.Context, job ViewExportJob) error
	Get(ctx context.Context, id string) (*ViewExportJob, error)
	Update(ctx context.Context, job ViewExportJob) error
}

ViewExportJobStore persists export jobs.

func NewInMemoryViewExportJobStore

func NewInMemoryViewExportJobStore() ViewExportJobStore

NewInMemoryViewExportJobStore returns an ephemeral export job store.

type ViewExportRequest

type ViewExportRequest struct {
	Views             []ViewExportTarget `json:"views"`
	Since             time.Time          `json:"since"`
	Format            OutputFormat       `json:"format"`
	ParquetLayout     ParquetLayout      `json:"parquetLayout,omitempty"`
	TimestampEncoding TimestampEncoding  `json:"timestampEncoding,omitempty"`
	Actor             string             `json:"actor,omitempty"`
	Subject           string             `json:"subject,omitempty"`
	Parameters        map[string]any     `json:"parameters,omitempty"`
}

ViewExportRequest captures one ViewDefinition export operation.

type ViewExportTarget

type ViewExportTarget struct {
	ViewName   string `json:"viewName"`
	Version    string `json:"version"`
	OutputName string `json:"outputName,omitempty"`
}

ViewExportTarget identifies one view to export.

type ViewRunRequest

type ViewRunRequest struct {
	ViewName          string
	Version           string
	InlineDef         []byte
	Since             time.Time
	Limit             int
	Offset            int
	Actor             string
	Subject           string
	Parameters        map[string]any
	Format            OutputFormat
	ParquetLayout     ParquetLayout
	TimestampEncoding TimestampEncoding
	Header            bool
}

ViewRunRequest captures parameters for ViewDefinition/$viewdefinition-run.

type ViewSpec

type ViewSpec struct {
	Name         string
	Version      string
	URL          string
	ResourceType string
	Description  string
	Status       string
	RootSelect   SelectSpec
	Columns      []ColumnSpec
	Filters      []FilterSpec
	Permissions  []string
	Metadata     map[string]string
	// Materialize enables writing rows to MaterializedViewStore when configured
	// on the Executor. MaterializeKey names the output column used as the row key.
	Materialize    bool
	MaterializeKey string
	SearchParams   url.Values
	SearchMode     SearchMode
	Raw            []byte
	// contains filtered or unexported fields
}

ViewSpec is a normalized internal representation of one parsed FHIR ViewDefinition, including source resource type, compiled filter expressions, compiled column expressions, declared permissions, and optional metadata tags.

func ParseDefinition

func ParseDefinition(def []byte, engine fhirpath.Engine) (*ViewSpec, error)

ParseDefinition loads and validates a ViewDefinition payload into a normalized ViewSpec. All filter and column FHIRPath expressions are compiled with engine to fail fast on invalid expressions. Engine must be non-nil.

func RegisterViewDefinition

func RegisterViewDefinition(reg *Registry, raw []byte, engine fhirpath.Engine) (*ViewSpec, error)

RegisterViewDefinition parses raw JSON and registers it when resourceType is ViewDefinition.

func (*ViewSpec) ColumnInfos

func (s *ViewSpec) ColumnInfos() []ColumnInfo

ColumnInfos returns column metadata for the view.

func (*ViewSpec) ColumnNames

func (s *ViewSpec) ColumnNames() []string

ColumnNames returns the declared output column names in order.

type WatermarkAdvancer

type WatermarkAdvancer interface {
	Since(ctx context.Context, viewName, version string) (time.Time, error)
	Advance(ctx context.Context, viewName, version string, refreshedAt time.Time) error
}

WatermarkAdvancer tracks SQL-on-FHIR export watermarks.

Jump to

Keyboard shortcuts

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