analytics

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

README

haistack-analytics (pkg/analytics)

Postgres-first analytics and reporting engine built on FHIR ViewDefinitions.

What it does

bytefhir-analytics turns registered views into durable reporting data or export files. It shares one execution pipeline across two modes:

Mode Constant Target Use case
Edge ModeRefresh ReportingTarget → Postgres reporting tables Tenant-scoped reporting, dashboards, SQL queries
Cloud ModeExport RowSink (CSV in v1) File export, downstream pipelines

The pipeline is always:

registered view → view.Executor → structured rows → target

View parsing and FHIRPath stay in pkg/view. Analytics only orchestrates execution and routes rows to the configured destination.

Quick start

Register built-in views and refresh a Postgres reporting table:

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

reg := view.NewRegistry()
if err := analytics.RegisterBuiltInViews(reg, engine); err != nil {
    // handle
}

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

runner, err := analytics.NewRunner(analytics.Config{Executor: viewExec})
if err != nil { /* handle */ }

result, err := runner.Run(ctx, analytics.RunRequest{
    ViewName: analytics.ViewPatientSummary,
    Mode:     analytics.ModeRefresh,
    Destination: analytics.Destination{
        Reporting: analytics.NewReportingTarget(tdb.ReportingTableStore()),
    },
})
if err != nil { /* handle */ }

// result.RowCount, result.Metadata.Scanned, result.Metadata.Filtered

Export the same view to CSV:

var buf bytes.Buffer

_, err := runner.Run(ctx, analytics.RunRequest{
    ViewName: analytics.ViewPatientSummary,
    Mode:     analytics.ModeExport,
    Destination: analytics.Destination{
        Sink: analytics.NewCSVSink(&buf),
    },
})

Query refreshed reporting data:

rows, err := tdb.ReportingTableStore().QueryRows(ctx, "patient_summary_view", "1.0.0")
meta, err := tdb.ReportingTableStore().GetMeta(ctx, "patient_summary_view", "1.0.0")

Supported views

First-milestone views (registered via RegisterBuiltInViews):

View name Resource Built-in helper
patient_summary_view Patient view.PatientSummaryView()
appointment_view Appointment view.AppointmentView()
observation_view Observation view.ObservationView()

Runner rejects views outside analytics.SupportedViews and rejects custom definitions or versions using a built-in name. Custom views can be registered in the view registry for direct view.Executor use, but analytics runs require the packaged v1 definitions.

Targets and sinks

ReportingTarget (edge mode)

Writes a full view result into store.ReportingTableStore. Each refresh:

  1. Deletes existing rows for (tenant, view_name, view_version).
  2. Upserts schema metadata (columns, row_count, refreshed_at).
  3. Inserts the new row set as ordered JSONB documents.

View versions are logical keys in these shared tables; they are not separate Postgres table partitions.

Postgres implementation: TenantDB.ReportingTableStore() in pkg/postgres.

This is intentionally separate from MaterializedViewStore, which stores opaque per-key payloads and is not designed for tabular reporting queries.

CSVSink (cloud mode)

Implements RowSink. Encoding rules:

  • Headers follow view.ColumnInfo declaration order.
  • null or a missing field → \N (analytics.CSVNullValue). Empty strings remain empty fields. A leading backslash in a scalar string is escaped with another backslash so the null marker remains unambiguous.
  • Scalars → string representation.
  • Arrays and maps → JSON in the cell.
  • Decimal values use fixed-point formatting; scientific notation is not emitted.

CSV rows are written directly to the supplied io.Writer, with no additional whole-export buffer. The view executor still materializes the complete result set in v1.

Parquet and lakehouse sinks
  • NewParquetSink(w) writes flat view Apache Parquet binary to w.
  • NewParquetFileSinkWithConfig(ParquetFileSinkConfig{Writer, Layout, Executor, TimestampEncoding}) supports _parquetLayout=fhir nested resources and optional INT96 date annotations.
  • NewLakehouseSink(LakehouseConfig{RootDir, ParquetLayout, Executor, TimestampEncoding}) writes {partition}/{view}-{version}.parquet files on disk (flat or FHIR layout).
  • NewLakehouseSink(LakehouseConfig{Blob, BlobPrefix, ParquetLayout, Executor, TimestampEncoding}) stores parquet objects via store.BlobStore.
  • NewManifestExportSink(ManifestExportConfig{Format: FormatParquet, ParquetLayout, Executor, TimestampEncoding}) supports flat or FHIR parquet manifest exports.
  • NewWarehouseSink() refreshes Postgres reporting tables.

Background jobs

Runs are synchronous by default but integrate with pkg/jobs:

Job type Constant Payload Handler
analytics.refresh analytics.TypeRefresh RefreshPayload RefreshHandler
export.csv analytics.TypeExport ExportPayload ExportHandler
jobRunner := jobs.NewRunner(tdb.JobStore())
jobRunner.Register(analytics.TypeRefresh, analytics.RefreshHandler(runner, target))
jobRunner.Register(analytics.TypeExport, analytics.ExportHandler(runner, csvSink, watermarkStore))

_, err := jobs.Enqueue(ctx, tdb.JobStore(), analytics.TypeRefresh, analytics.RefreshPayload{
    ViewName: analytics.ViewPatientSummary,
    Version:  "1.0.0",
}, jobs.EnqueueOptions{})

ExportHandler and ExportHandlerWithConfig take an optional *WatermarkStore third argument (nil disables watermark auto-fill/advance). When configured, watermarks advance using ResultMetadata.maxLastUpdated from exported resources when present. See CHANGELOG-parquet-analytics.md.

Where it fits

Layer Role
view Parse ViewDefinitions, execute FHIRPath, produce Result.Rows
analytics Orchestrate view runs into reporting tables or export sinks (this package)
store ReportingTableStore contract for tabular reporting persistence
postgres Tenant-scoped Postgres implementation and migrations
jobs Optional async refresh and export scheduling
ai Interactive view access via tools; analytics materializes rows for reporting

MVP limits

  • Postgres only for reporting tables and $sqlquery-run; SQLite runtimes get view run/export HTTP operations whenever storage is wired (async export/materialize when a job runner is present).
  • Incremental refresh uses a single WatermarkStore for _since cursors and export chaining; watermarks advance only after a successful refresh or export completes. Legacy analytics.view.* cursor names are migrated to analytics.watermark.* on first read.
  • View export artifacts persist on the local filesystem ({sqlite-dir}/view-exports or view-exports/{tenantId}) and roll back on multi-view failure.
  • Three views at the Runner allow-list layer.
  • CSV is the primary production cloud sink; warehouse/lake/Parquet sinks write flat view Apache Parquet binary files (application/vnd.apache.parquet).

Errors

Error When
ErrUnsupportedView View name or registered definition is not a packaged v1 view
ErrUnsupportedDestination Mode/destination mismatch (e.g. refresh without ReportingTarget)
ErrUnsupportedMode Unknown Mode value
ErrMissingExecutor NewRunner without a view executor
ErrSinkNotImplemented Deferred sink backends

View-layer errors (ErrViewNotFound, ErrUnauthorized, etc.) propagate from view.Executor unchanged.

See doc.go for the full API, persistence model, and integration points.

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:

  1. Resolve a registered view by name and version.
  2. Execute it through view.Executor into structured rows.
  3. 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

View Source
const (
	TypeRefresh = jobs.TypeAnalyticsRefresh
	TypeExport  = jobs.TypeExportCSV
)

Job type constants re-exported for analytics orchestration.

View Source
const (
	ViewPatientSummary = "patient_summary_view"
	ViewAppointment    = "appointment_view"
	ViewObservation    = "observation_view"
)

Supported view names for the first analytics milestone.

View Source
const CSVNullValue = `\N`

CSVNullValue is the reserved CSV cell value used to represent null or a missing field. Empty strings remain empty cells.

Variables

View Source
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")
)

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

func IsSupportedView(name string) bool

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.

func RegisterBuiltInViews

func RegisterBuiltInViews(reg *view.Registry, engine fhirpath.Engine) error

RegisterBuiltInViews registers the first-milestone view definitions into reg.

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.

func (*CDCProcessor) RunOnce

func (p *CDCProcessor) RunOnce(ctx context.Context) (processed int, err error)

RunOnce reads one batch of events since the stored cursor and schedules refreshes.

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

func NewCSVSink(w io.Writer) *CSVSink

NewCSVSink returns a sink that writes CSV to w.

func (*CSVSink) WriteRows

func (s *CSVSink) WriteRows(ctx context.Context, result *view.Result) error

WriteRows encodes result as CSV.

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 Config

type Config struct {
	Executor *view.Executor
	Now      func() time.Time
}

Config configures a Runner.

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

type ExportHandlerConfig struct {
	Writer   io.Writer
	Executor *view.Executor
	Actor    string
}

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

type ExportRowCountSink interface {
	RowSink
	LastExportRowCount() int
}

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.

func (*IncrementalTarget) Since

func (t *IncrementalTarget) Since(ctx context.Context, viewName, version string) (time.Time, error)

Since returns the last successful refresh watermark for a view, if any.

func (*IncrementalTarget) WriteAt

func (t *IncrementalTarget) WriteAt(ctx context.Context, result *view.Result, refreshedAt time.Time) error

WriteAt persists rows without advancing the watermark.

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

type LakehouseSink interface {
	WriteRows(ctx context.Context, result *view.Result) error
}

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

type ManifestExportSink interface {
	WriteRows(ctx context.Context, result *view.Result) error
}

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 Mode

type Mode string

Mode selects the analytics execution target.

const (
	// ModeRefresh executes a view and writes to a reporting table (edge mode).
	ModeRefresh Mode = "refresh"
	// ModeExport executes a view and writes to a row sink (cloud mode).
	ModeExport Mode = "export"
)

type NDJSONSink

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

NDJSONSink writes one JSON object per line.

func (*NDJSONSink) WriteRows

func (s *NDJSONSink) WriteRows(ctx context.Context, result *view.Result) error

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.

func (*ParquetFileSink) WriteRows

func (s *ParquetFileSink) WriteRows(ctx context.Context, result *view.Result) error

WriteRows encodes view rows as Apache Parquet.

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

type ParquetSink interface {
	WriteRows(ctx context.Context, result *view.Result) error
}

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.

func (*ReportingTarget) Write

func (t *ReportingTarget) Write(ctx context.Context, result *view.Result) error

Write persists the full view result via a reporting table refresh.

type RowSink

type RowSink interface {
	WriteRows(ctx context.Context, result *view.Result) error
}

RowSink writes structured view rows to an export-oriented destination.

func NewNDJSONSink

func NewNDJSONSink(w io.Writer) RowSink

NewNDJSONSink returns a sink that writes NDJSON to w.

func NewParquetSink

func NewParquetSink(w io.Writer) RowSink

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.

func NewRunner

func NewRunner(cfg Config) (*Runner, error)

NewRunner validates configuration and returns a Runner.

func (*Runner) Run

func (r *Runner) Run(ctx context.Context, req RunRequest) (*RunResult, error)

Run resolves and executes the named view, then writes rows to the configured target.

type WarehouseSink

type WarehouseSink interface {
	WriteRows(ctx context.Context, result *view.Result) error
}

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.

func (*WatermarkStore) Advance

func (w *WatermarkStore) Advance(ctx context.Context, viewName, version string, refreshedAt time.Time) error

Advance stores a new watermark after a successful incremental run.

func (*WatermarkStore) Since

func (w *WatermarkStore) Since(ctx context.Context, viewName, version string) (time.Time, error)

Since returns the last successful watermark timestamp for a view, if any. When no watermark exists, a legacy analytics.view.* cursor is migrated forward once.

Jump to

Keyboard shortcuts

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