Documentation
¶
Overview ¶
Package analytics implements haistack-analytics, a Postgres-first analytics and reporting engine for HAIStack.
Scope ¶
bytefhir-analytics is an orchestration layer on top of pkg/view. It does not parse ViewDefinitions or evaluate FHIRPath; those responsibilities stay in haistack-view. This package owns analytics execution, reporting refresh, and export orchestration around a shared pipeline:
- Resolve a registered view by name and version.
- Execute it through view.Executor into structured rows.
- Hand rows to a mode-specific target.
v1 supports two modes with one shared core:
- Edge mode (ModeRefresh): FHIR -> ViewDefinition -> Postgres reporting tables. Full refresh only; each run replaces all rows for the view identity.
- Cloud mode (ModeExport): FHIR -> ViewDefinition -> structured rows -> sink adapters. CSV, NDJSON, flat Parquet, and Parquet-on-FHIR nested exports are supported.
Warehouse refresh, lakehouse partitioning, and manifest export sinks are implemented for Postgres analytics mode. Use ParquetLayout, TimestampEncoding, and Executor on parquet sinks for _parquetLayout=fhir nested resource exports (INT96 date annotations when TimestampEncoding is int96).
Public API ¶
The package centers on Runner and two target abstractions:
- Runner: synchronous, job-friendly entry point. Accepts a view name, optional version, run mode, and destination configuration.
- ReportingTarget: edge-mode writer backed by store.ReportingTableStore. Persists tabular reporting data keyed by tenant, view name, and version.
- RowSink: cloud-mode export interface. CSVSink is the v1 implementation.
Additional helpers:
- RegisterBuiltInViews: register the first-milestone packaged views.
- RefreshHandler / ExportHandler: pkg/jobs adapters for background runs.
- IsSupportedView / SupportedViews: first-milestone view allow-list.
Supported views ¶
The first milestone supports exactly three single-resource, flat views:
- patient_summary_view (Patient)
- appointment_view (Appointment)
- observation_view (Observation)
Built-in ViewDefinition payloads live in pkg/view (PatientSummaryView, AppointmentView, ObservationView). Register them with RegisterBuiltInViews or view.Registry.Register before running analytics.
Edge mode: Postgres reporting tables ¶
Reporting data is stored through store.ReportingTableStore, implemented by pkg/postgres (TenantDB.ReportingTableStore). This is separate from store.MaterializedViewStore, which persists opaque per-key JSON payloads and is not suitable for tabular reporting queries.
Postgres tables (migration 0009_reporting_tables.sql):
- analytics_reporting_meta: schema and refresh metadata per view version
- analytics_reporting_row: JSONB rows ordered by row_num within a refresh
Refresh is tenant-scoped and atomic: delete existing rows for the view version, upsert metadata, insert the new row set. SQLite reporting tables are not supported in v1.
Typical edge usage:
engine, _ := fhirpath.NewEngine(fhirpath.Config{})
reg := view.NewRegistry()
_ = analytics.RegisterBuiltInViews(reg, engine)
viewExec, _ := view.NewExecutor(view.Config{
Resources: tdb.ResourceStore(),
Engine: engine,
Registry: reg,
})
runner, _ := analytics.NewRunner(analytics.Config{Executor: viewExec})
_, err := runner.Run(ctx, analytics.RunRequest{
ViewName: analytics.ViewPatientSummary,
Mode: analytics.ModeRefresh,
Destination: analytics.Destination{
Reporting: analytics.NewReportingTarget(tdb.ReportingTableStore()),
},
})
Cloud mode: CSV export ¶
CSVSink writes view.Result rows directly to an io.Writer. Column order follows view.ColumnInfo declaration order. Null or missing values use the reserved analytics.CSVNullValue marker; empty strings remain empty fields. Arrays and complex values are JSON-encoded cell strings.
_, err := runner.Run(ctx, analytics.RunRequest{
ViewName: analytics.ViewPatientSummary,
Mode: analytics.ModeExport,
Destination: analytics.Destination{
Sink: analytics.NewCSVSink(&buf),
},
})
Parquet, lakehouse, warehouse, and manifest sinks:
sink := analytics.NewParquetFileSinkWithConfig(analytics.ParquetFileSinkConfig{
Writer: &buf, Layout: view.ParquetLayoutFHIR, Executor: viewExec,
})
lake := analytics.NewLakehouseSink(analytics.LakehouseConfig{
RootDir: dir, ParquetLayout: view.ParquetLayoutFHIR, Executor: viewExec,
})
Background jobs ¶
Runs are synchronous in v1 but shaped for pkg/jobs integration:
- analytics.refresh (jobs.TypeAnalyticsRefresh) with RefreshPayload
- export.csv (jobs.TypeExportCSV) with ExportPayload (format + parquetLayout)
Register handlers on a jobs.Runner:
runner.Register(analytics.TypeRefresh, analytics.RefreshHandler(analyticsRunner, target)) runner.Register(analytics.TypeExport, analytics.ExportHandler(analyticsRunner, csvSink, watermarkStore))
Execution model ¶
Runner.Run validates that the registered definition is one of the packaged v1 views, validates the destination matches the mode, then calls view.Executor.Execute with no row limit so the full matching resource set is materialized. View parse, authorization, and execution errors from pkg/view propagate unchanged.
RunResult reports view identity, mode, row count, and view.ResultMetadata (scanned/filtered counts, duration, source resource type).
Integration points ¶
- haistack-view: canonical ViewDefinition execution; analytics never duplicates view parsing or FHIRPath logic.
- haistack-store: ReportingTableStore contract; Postgres implementation only.
- haistack-postgres: tenant-scoped reporting table persistence.
- haistack-jobs: optional background refresh and export orchestration.
- haistack-ai: complementary; AI tools call view.Executor directly for interactive row access; analytics materializes the same rows for reporting.
MVP limits ¶
- Postgres-first reporting; no SQLite reporting tables.
- Full refresh only; no incremental cursors or partitioned output.
- Three built-in views only at the Runner allow-list layer.
- CSV is the only production cloud sink; other sinks are interface-only.
- No warehouse dependency required to use analytics.
Index ¶
- Constants
- Variables
- func ExportHandler(runner *Runner, sink RowSink, watermark *WatermarkStore) jobs.Handler
- func ExportHandlerWithConfig(runner *Runner, cfg ExportHandlerConfig, watermark *WatermarkStore) jobs.Handler
- func IsSupportedView(name string) bool
- func LimitedRefreshHandler(inner jobs.Handler, limiter *ConcurrencyLimiter) jobs.Handler
- func RefreshHandler(runner *Runner, target reportingWriter, watermark *WatermarkStore) jobs.Handler
- func RegisterBuiltInViews(reg *view.Registry, engine fhirpath.Engine) error
- type CDCProcessor
- type CSVSink
- type ConcurrencyLimiter
- type Config
- type Destination
- type ExportFormat
- type ExportHandlerConfig
- type ExportPayload
- type ExportRowCountSink
- type IncrementalTarget
- type LakehouseArtifact
- type LakehouseConfig
- type LakehouseSink
- type ManifestExportConfig
- type ManifestExportSink
- type Mode
- type NDJSONSink
- type ParquetFileSink
- type ParquetFileSinkConfig
- type ParquetSink
- type RefreshPayload
- type ReportingTarget
- type RowSink
- type RunRequest
- type RunResult
- type Runner
- type WarehouseSink
- type WatermarkStore
Constants ¶
const ( TypeRefresh = jobs.TypeAnalyticsRefresh TypeExport = jobs.TypeExportCSV )
Job type constants re-exported for analytics orchestration.
const ( ViewPatientSummary = "patient_summary_view" ViewAppointment = "appointment_view" ViewObservation = "observation_view" )
Supported view names for the first analytics milestone.
const CSVNullValue = `\N`
CSVNullValue is the reserved CSV cell value used to represent null or a missing field. Empty strings remain empty cells.
Variables ¶
var ( // ErrUnsupportedDestination is returned when a run request has no valid target. ErrUnsupportedDestination = errors.New("analytics: unsupported destination configuration") // ErrUnsupportedMode is returned when the run mode is not recognized. ErrUnsupportedMode = errors.New("analytics: unsupported run mode") // ErrUnsupportedView is returned when the view is not in the first-milestone set. ErrUnsupportedView = errors.New("analytics: unsupported view") // ErrSinkNotImplemented is returned by deferred sink backends. ErrSinkNotImplemented = errors.New("analytics: sink not implemented") // ErrMissingExecutor is returned when Runner is constructed without a view executor. ErrMissingExecutor = errors.New("analytics: missing view executor") )
var SupportedViews = []string{ ViewPatientSummary, ViewAppointment, ViewObservation, }
SupportedViews lists the built-in views supported in v1.
Functions ¶
func ExportHandler ¶
func ExportHandler(runner *Runner, sink RowSink, watermark *WatermarkStore) jobs.Handler
ExportHandler returns a jobs.Handler that runs export using the supplied sink. When watermark is configured, an empty Since is filled from the watermark and advanced after a successful export.
func ExportHandlerWithConfig ¶
func ExportHandlerWithConfig(runner *Runner, cfg ExportHandlerConfig, watermark *WatermarkStore) jobs.Handler
ExportHandlerWithConfig returns a jobs.Handler that builds a sink per payload format.
func IsSupportedView ¶
IsSupportedView reports whether name is in the first-milestone view set.
func LimitedRefreshHandler ¶
func LimitedRefreshHandler(inner jobs.Handler, limiter *ConcurrencyLimiter) jobs.Handler
LimitedRefreshHandler wraps a refresh handler with concurrency limiting.
func RefreshHandler ¶
func RefreshHandler(runner *Runner, target reportingWriter, watermark *WatermarkStore) jobs.Handler
RefreshHandler returns a jobs.Handler that runs reporting refreshes using the supplied reporting target. When watermark is configured, it advances only after a successful refresh completes.
Types ¶
type CDCProcessor ¶
type CDCProcessor struct {
Events store.EventStore
Cursors store.CursorStore
Jobs store.JobStore
Views []string
Scope string
BatchSize int
Now func() time.Time
}
CDCProcessor consumes resource change events and enqueues analytics refresh jobs.
type CSVSink ¶
type CSVSink struct {
// contains filtered or unexported fields
}
CSVSink writes view rows as CSV with deterministic column ordering from the view schema. Null values use CSVNullValue; arrays and complex values are JSON.
func NewCSVSink ¶
NewCSVSink returns a sink that writes CSV to w.
type ConcurrencyLimiter ¶
type ConcurrencyLimiter struct {
// contains filtered or unexported fields
}
ConcurrencyLimiter bounds concurrent analytics job execution to protect OLTP.
func NewConcurrencyLimiter ¶
func NewConcurrencyLimiter(max int) *ConcurrencyLimiter
NewConcurrencyLimiter returns a limiter that allows at most max concurrent jobs. When max <= 0, concurrency is unlimited.
func (*ConcurrencyLimiter) Acquire ¶
func (l *ConcurrencyLimiter) Acquire() func()
Acquire reserves one execution slot. Call the returned function to release it.
type Destination ¶
type Destination struct {
Reporting reportingWriter
Sink RowSink
}
Destination configures where structured rows are written.
type ExportFormat ¶
type ExportFormat string
ExportFormat selects export sink encoding.
const ( FormatJSON ExportFormat = "json" FormatNDJSON ExportFormat = "ndjson" FormatCSV ExportFormat = "csv" FormatParquet ExportFormat = "parquet" )
func ParseExportFormat ¶
func ParseExportFormat(raw string) ExportFormat
ParseExportFormat maps SQL-on-FHIR _format values to ExportFormat.
type ExportHandlerConfig ¶
ExportHandlerConfig configures dynamic export sinks for background jobs.
type ExportPayload ¶
type ExportPayload struct {
ViewName string `json:"viewName"`
Version string `json:"version"`
Actor string `json:"actor,omitempty"`
Subject string `json:"subject,omitempty"`
Since time.Time `json:"since,omitempty"`
Parameters map[string]any `json:"parameters,omitempty"`
Format ExportFormat `json:"format,omitempty"`
ParquetLayout view.ParquetLayout `json:"parquetLayout,omitempty"`
TimestampEncoding view.TimestampEncoding `json:"timestampEncoding,omitempty"`
}
ExportPayload is the job payload for analytics export runs.
type ExportRowCountSink ¶
ExportRowCountSink optionally reports the row count from the most recent export write.
type IncrementalTarget ¶
type IncrementalTarget struct {
// contains filtered or unexported fields
}
IncrementalTarget wraps a ReportingTarget with watermark-based delta refresh. Watermarks are advanced by RefreshHandler after a successful refresh completes; WriteAt persists rows only.
func NewIncrementalTarget ¶
func NewIncrementalTarget(target *ReportingTarget, watermark *WatermarkStore) *IncrementalTarget
NewIncrementalTarget returns a reporting target that reads _since from WatermarkStore.
type LakehouseArtifact ¶
type LakehouseArtifact struct {
Partition string `json:"partition"`
Location string `json:"location"`
RowCount int `json:"rowCount"`
}
LakehouseArtifact describes one parquet object written by LakehouseSink.
type LakehouseConfig ¶
type LakehouseConfig struct {
// Root writes parquet bytes to a single io.Writer when RootDir and Blob are unset.
Root io.Writer
// RootDir writes one parquet file per partition under a filesystem directory.
RootDir string
// Blob stores parquet objects when RootDir is unset.
// Uploads stream from a temp file via store.PutBlobFromPath (PutStream when available).
Blob store.BlobStore
// BlobPrefix is prepended to blob object keys.
BlobPrefix string
// PartitionBy derives the partition path for a view result.
PartitionBy func(*view.Result) string
// ParquetLayout selects flat view columns or Parquet-on-FHIR nested resources.
ParquetLayout view.ParquetLayout
// Executor is required when ParquetLayout is fhir.
Executor *view.Executor
// Actor is forwarded to FHIR resource export authorization.
Actor string
// TimestampEncoding selects INT64 (default) or INT96 date annotations for FHIR parquet.
TimestampEncoding view.TimestampEncoding
}
LakehouseConfig configures partitioned parquet export.
type LakehouseSink ¶
LakehouseSink writes view rows to a data lake / lakehouse.
func NewLakehouseSink ¶
func NewLakehouseSink(cfg LakehouseConfig) LakehouseSink
NewLakehouseSink returns a sink that writes partitioned Apache Parquet files.
type ManifestExportConfig ¶
type ManifestExportConfig struct {
Root io.Writer
Watermark *WatermarkStore
Format ExportFormat
ParquetLayout view.ParquetLayout
TimestampEncoding view.TimestampEncoding
Executor *view.Executor
Actor string
}
ManifestExportConfig configures cursor-based manifest export.
type ManifestExportSink ¶
ManifestExportSink supports cursor-based incremental export with manifests.
func NewManifestExportSink ¶
func NewManifestExportSink(cfg ManifestExportConfig) ManifestExportSink
NewManifestExportSink returns a sink that writes export payloads and advances watermarks.
type NDJSONSink ¶
type NDJSONSink struct {
// contains filtered or unexported fields
}
NDJSONSink writes one JSON object per line.
type ParquetFileSink ¶
type ParquetFileSink struct {
// contains filtered or unexported fields
}
ParquetFileSink writes view rows as Apache Parquet binary.
func NewParquetFileSink ¶
func NewParquetFileSink(w io.Writer) *ParquetFileSink
NewParquetFileSink returns a sink that writes flat-view parquet to w.
func NewParquetFileSinkWithConfig ¶
func NewParquetFileSinkWithConfig(cfg ParquetFileSinkConfig) *ParquetFileSink
NewParquetFileSinkWithConfig returns a sink with optional Parquet-on-FHIR layout.
func (*ParquetFileSink) LastExportRowCount ¶
func (s *ParquetFileSink) LastExportRowCount() int
LastExportRowCount implements ExportRowCountSink.
type ParquetFileSinkConfig ¶
type ParquetFileSinkConfig struct {
Writer io.Writer
Layout view.ParquetLayout
TimestampEncoding view.TimestampEncoding
Executor *view.Executor
Actor string
}
ParquetFileSinkConfig configures ParquetFileSink encoding.
type ParquetSink ¶
ParquetSink writes view rows as columnar JSON documents.
type RefreshPayload ¶
type RefreshPayload struct {
ViewName string `json:"viewName"`
Version string `json:"version"`
Actor string `json:"actor,omitempty"`
Subject string `json:"subject,omitempty"`
}
RefreshPayload is the job payload for analytics reporting refresh runs.
type ReportingTarget ¶
type ReportingTarget struct {
// contains filtered or unexported fields
}
ReportingTarget writes view execution results into a Postgres reporting table.
func NewReportingTarget ¶
func NewReportingTarget(s store.ReportingTableStore) *ReportingTarget
NewReportingTarget returns a target that refreshes store.ReportingTableStore.
type RowSink ¶
RowSink writes structured view rows to an export-oriented destination.
func NewNDJSONSink ¶
NewNDJSONSink returns a sink that writes NDJSON to w.
func NewParquetSink ¶
NewParquetSink returns a ParquetFileSink-compatible RowSink.
type RunRequest ¶
type RunRequest struct {
ViewName string
Version string
Mode Mode
Destination Destination
Actor string
Subject string
Parameters map[string]any
// Since limits view execution to resources updated after this timestamp.
Since time.Time
// Incremental enables cursor-based delta refresh when a cursor store is
// configured on the destination reporting target.
Incremental bool
}
RunRequest carries parameters for one synchronous analytics run.
type RunResult ¶
type RunResult struct {
ViewName string
Version string
Mode Mode
RowCount int
Metadata view.ResultMetadata
}
RunResult summarizes a completed analytics run.
type Runner ¶
type Runner struct {
// contains filtered or unexported fields
}
Runner orchestrates view execution and hands rows to analytics targets.
type WarehouseSink ¶
WarehouseSink writes view rows to a warehouse backend.
func NewWarehouseSink ¶
func NewWarehouseSink(store store.ReportingTableStore) WarehouseSink
NewWarehouseSink returns a sink that refreshes reporting tables.
type WatermarkStore ¶
type WatermarkStore struct {
// contains filtered or unexported fields
}
WatermarkStore tracks SQL-on-FHIR change-detection watermarks per view.
func NewWatermarkStore ¶
func NewWatermarkStore(cursor store.CursorStore) *WatermarkStore
NewWatermarkStore returns a watermark store backed by CursorStore.