Documentation
¶
Overview ¶
Package subscriptions implements haistack-subscriptions, the tenant-neutral event automation library for HAIStack.
haistack-subscriptions consumes store.ResourceEvent entries produced by pkg/core writes and schedules durable notification delivery through pkg/jobs. It is a downstream consumer of the existing event log — subscriptions do not hook into pkg/core write paths and remain optional at deploy time.
Scope (v1) ¶
v1 supports:
- Internal trigger registration (resource type + create/update/delete/change event, optional changed-field filters, optional FHIRPath predicates)
- A narrow adapter from a supported subset of FHIR Subscription resources (rest-hook channel only; Subscription.criteria is parsed with pkg/search and notifies on create and update, not delete)
- Webhook (HTTP) and local (in-process handler) delivery channels
- Durable delivery logging and retries backed by pkg/jobs
- Postgres-first and SQLite edge persistence without Kafka/NATS
v1 does not support:
- WebSocket, email, SMS, or message channel types (FHIR adapter is rest-hook only)
- Dead-letter queues or full delivery audit expansion
- Tenant semantics in the core API (Postgres scoping is via TenantDB wiring)
- Chained, _include, _revinclude, full-text, modifiers, or prefixes in Subscription.criteria
Public API ¶
- Manager — register, update, disable, list, delete subscription records
- Processor — consume ResourceEvent entries and enqueue delivery jobs
- DeliveryWorker — execute queued deliveries
- DeliveryJobRunner — claim and run delivery jobs via pkg/jobs.Runner
- Matcher — evaluate triggers against current and previous resource state
- WebhookDispatcher — HTTP POST/PUT transport
- LocalDispatcher / HandlerRegistry — in-process handler transport
- RegisterFromFHIRSubscription — FHIR Subscription adapter (supported subset)
- CursorName — processor checkpoint naming helper
Core types: SubscriptionRecord, Trigger, Channel, RetryPolicy, DeliveryRecord, DeliverPayload.
Job type: jobs.TypeSubscriptionsDeliver ("subscriptions.deliver").
Trigger examples ¶
Patient.created:
Trigger{ResourceType: "Patient", Event: TriggerEventCreate}
Appointment.status changed:
Trigger{ResourceType: "Appointment", Event: TriggerEventUpdate,
ChangedFields: []string{"status"}}
Observation.created where code = X:
Trigger{ResourceType: "Observation", Event: TriggerEventCreate,
FilterFHIRPath: "code.coding.code = '8867-4'"}
Observation matching search criteria (create and update):
Trigger{ResourceType: "Observation", Event: TriggerEventChange,
Criteria: "Observation?code=8867-4", FilterParams: parsed.Params}
FilterFHIRPath is evaluated with pkg/fhirpath against the current resource on create/update. FilterParams are parsed from Subscription.criteria with search.ParseQuery and matched with search.MatchResourceParameter. Matcher.Registry must be set when FilterParams is used; a nil registry returns ErrNilRegistry. pkg/runtime wires Matcher.Engine and Matcher.Registry on the default runtime. Changed-field matching compares top-level JSON fields between the previous history snapshot and the current resource. FHIR adapter criteria use TriggerEventChange so matching resources notify on create and update, not delete.
Store contracts ¶
Subscription-specific persistence lives in pkg/store:
- store.SubscriptionStore — registry CRUD (subscription_registry)
- store.SubscriptionDeliveryStore — delivery attempt log (subscription_delivery_log)
Reused contracts:
- store.EventStore — change event source (sync_outbox on SQLite, event_log on Postgres)
- store.CursorStore — processor checkpoint position
- store.JobStore — durable delivery work and retries (no dedicated retry table)
- store.ResourceStore / store.HistoryStore — resource context for matching
Postgres: pkg/postgres.TenantDB.SubscriptionStore(), SubscriptionDeliveryStore(). SQLite: pkg/sqlite.DB.SubscriptionStore(), SubscriptionDeliveryStore().
Local handler names are registered in-memory via HandlerRegistry; they are not persisted.
Typical wiring ¶
mgr := &subscriptions.Manager{Store: db.SubscriptionStore()}
_, _ = mgr.Register(ctx, "patient-created", trigger, channel, retryPolicy)
engine, _ := fhirpath.NewEngine(fhirpath.Config{})
processor := &subscriptions.Processor{
Events: db.OutboxStore(),
Cursors: db.CursorStore(),
Subscriptions: db.SubscriptionStore(),
Jobs: db.JobStore(),
Resources: db.ResourceStore(),
History: db.HistoryStore(),
Matcher: &subscriptions.Matcher{Engine: engine, Registry: searchRegistry},
}
_, _ = processor.RunOnce(ctx)
registry := subscriptions.NewHandlerRegistry()
registry.Register("on-patient-created", handler)
worker := &subscriptions.DeliveryWorker{
Subscriptions: db.SubscriptionStore(),
Deliveries: db.SubscriptionDeliveryStore(),
Resources: db.ResourceStore(),
Webhook: &subscriptions.WebhookDispatcher{},
Local: &subscriptions.LocalDispatcher{Registry: registry},
}
runner := &subscriptions.DeliveryJobRunner{Jobs: db.JobStore(), Worker: worker}
_, _ = runner.RunOnce(ctx)
Runtime flow ¶
- Processor.RunOnce/RunLoop reads EventStore.ReadSince using CursorStore.
- For each event, active subscriptions are loaded by resource type and event kind (create/update also load TriggerEventChange FHIR criteria).
- Matcher evaluates changed fields (via history) and FHIRPath filters.
- On match, one delivery job is enqueued per subscription-event pair.
- DeliveryWorker resolves subscription context, dispatches via webhook or local handler, and appends/updates delivery-log records.
- Retry policy uses pkg/jobs backoff; terminal failure remains in job state plus delivery log (no DLQ table in v1).
Delivery job IDs are deterministic (subscriptions:deliver:{id}:{sequence}) so the same event/subscription pair is idempotent across processor restarts.
Ownership boundaries ¶
haistack-subscriptions owns trigger matching, delivery scheduling, transport adapters, FHIR Subscription adaptation, and operational delivery logging. It does not own resource writes, event emission, job persistence, or compliance-grade audit (pkg/audit may mirror lifecycle events later without changing delivery semantics).
File layout ¶
- doc.go — package documentation
- types.go — SubscriptionRecord, Trigger, Channel, DeliveryRecord, payloads
- errors.go — package sentinels
- codec.go — store record conversion and validation helpers
- manager.go — subscription registry CRUD
- matcher.go — event predicate evaluation
- processor.go — event intake and job enqueue
- delivery_worker.go — delivery execution and DeliveryJobRunner
- webhook_dispatcher.go — HTTP webhook transport
- local_dispatcher.go — in-process handler transport
- handler_registry.go — in-memory local handler registry
- fhir_adapter.go — FHIR Subscription subset adapter
See README.md for extended usage and integration notes.
Index ¶
- Variables
- func CursorName(scope string) string
- func DeliveryJobID(subscriptionID string, eventSequence int64) string
- type Channel
- type ChannelType
- type DeliverPayload
- type DeliveryJobRunner
- type DeliveryRecord
- type DeliveryWorker
- type FHIRSubscriptionChannel
- type FHIRSubscriptionInput
- type HandlerRegistry
- type LocalConfig
- type LocalDispatcher
- type LocalHandler
- type Manager
- func (m *Manager) Delete(ctx context.Context, id string) error
- func (m *Manager) Disable(ctx context.Context, id string) error
- func (m *Manager) Get(ctx context.Context, id string) (SubscriptionRecord, error)
- func (m *Manager) List(ctx context.Context, status store.SubscriptionStatus, resourceType string, ...) ([]SubscriptionRecord, error)
- func (m *Manager) Register(ctx context.Context, name string, trigger Trigger, channel Channel, ...) (SubscriptionRecord, error)
- func (m *Manager) RegisterFromFHIRSubscription(ctx context.Context, input FHIRSubscriptionInput, extensions []map[string]any) (SubscriptionRecord, error)
- func (m *Manager) Update(ctx context.Context, rec SubscriptionRecord) (SubscriptionRecord, error)
- type MatchContext
- type Matcher
- type PayloadMode
- type Processor
- type RetryPolicy
- type SubscriptionRecord
- type Trigger
- type TriggerEvent
- type WebhookConfig
- type WebhookDispatcher
- type WebhookResult
Constants ¶
This section is empty.
Variables ¶
var ( ErrNilStore = errors.New("subscriptions: store is nil") ErrNilEngine = errors.New("subscriptions: fhirpath engine is nil") ErrNilRegistry = errors.New("subscriptions: search registry is nil") ErrNotFound = errors.New("subscriptions: not found") ErrInvalidTrigger = errors.New("subscriptions: invalid trigger") ErrInvalidChannel = errors.New("subscriptions: invalid channel") ErrUnsupportedFHIR = errors.New("subscriptions: unsupported FHIR subscription shape") ErrUnknownHandler = errors.New("subscriptions: unknown local handler") ErrDuplicateDelivery = errors.New("subscriptions: delivery already completed") )
Functions ¶
func CursorName ¶
CursorName returns a stable processor checkpoint name for a scope.
func DeliveryJobID ¶
DeliveryJobID returns the deterministic delivery job id for tests and tooling.
Types ¶
type Channel ¶
type Channel struct {
Type ChannelType `json:"type"`
Webhook *WebhookConfig `json:"webhook,omitempty"`
Local *LocalConfig `json:"local,omitempty"`
}
Channel defines how matched events are delivered.
type ChannelType ¶
type ChannelType string
ChannelType names a delivery transport.
const ( ChannelTypeWebhook ChannelType = "webhook" ChannelTypeLocal ChannelType = "local" )
type DeliverPayload ¶
type DeliverPayload struct {
SubscriptionID string `json:"subscriptionId"`
EventSequence int64 `json:"eventSequence"`
ResourceType string `json:"resourceType"`
ResourceID string `json:"resourceId"`
VersionID string `json:"versionId"`
Action store.EventAction `json:"action"`
Attempt int `json:"attempt,omitempty"`
}
DeliverPayload is the background job payload for subscription delivery.
type DeliveryJobRunner ¶
type DeliveryJobRunner struct {
Jobs store.JobStore
Worker *DeliveryWorker
MaxAttempts int
Backoff jobs.Backoff
Now func() time.Time
}
DeliveryJobRunner claims and executes subscription delivery jobs.
type DeliveryRecord ¶
type DeliveryRecord struct {
ID string `json:"id"`
SubscriptionID string `json:"subscriptionId"`
EventSequence int64 `json:"eventSequence"`
Attempt int `json:"attempt"`
Status store.DeliveryStatus `json:"status"`
ResponseStatus int `json:"responseStatus,omitempty"`
ResponseBody string `json:"responseBody,omitempty"`
ErrorMessage string `json:"errorMessage,omitempty"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
DeliveryRecord is the public delivery log shape.
type DeliveryWorker ¶
type DeliveryWorker struct {
Subscriptions store.SubscriptionStore
Deliveries store.SubscriptionDeliveryStore
Resources store.ResourceStore
History store.HistoryStore
Webhook *WebhookDispatcher
Local *LocalDispatcher
Now func() time.Time
}
DeliveryWorker executes subscription delivery jobs.
type FHIRSubscriptionChannel ¶
FHIRSubscriptionChannel maps FHIR Subscription.channel.
type FHIRSubscriptionInput ¶
type FHIRSubscriptionInput struct {
ID string
Status string
Criteria string
Channel FHIRSubscriptionChannel
Name string
}
FHIRSubscriptionInput carries a supported subset of FHIR Subscription fields.
func ParseFHIRSubscriptionJSON ¶
func ParseFHIRSubscriptionJSON(data []byte) (FHIRSubscriptionInput, []map[string]any, error)
ParseFHIRSubscriptionJSON decodes a FHIR Subscription resource JSON blob.
type HandlerRegistry ¶
type HandlerRegistry struct {
// contains filtered or unexported fields
}
HandlerRegistry maps handler names to in-process delivery callbacks.
func NewHandlerRegistry ¶
func NewHandlerRegistry() *HandlerRegistry
NewHandlerRegistry returns an empty handler registry.
func (*HandlerRegistry) Lookup ¶
func (r *HandlerRegistry) Lookup(name string) (LocalHandler, bool)
Lookup returns a registered handler by name.
func (*HandlerRegistry) Register ¶
func (r *HandlerRegistry) Register(name string, handler LocalHandler)
Register adds or replaces a named local handler.
type LocalConfig ¶
type LocalConfig struct {
HandlerName string `json:"handlerName"`
Metadata map[string]any `json:"metadata,omitempty"`
}
LocalConfig configures in-process handler delivery.
type LocalDispatcher ¶
type LocalDispatcher struct {
Registry *HandlerRegistry
}
LocalDispatcher invokes registered in-process handlers.
func (*LocalDispatcher) Dispatch ¶
func (d *LocalDispatcher) Dispatch(ctx context.Context, cfg LocalConfig, payload DeliverPayload, resourceJSON []byte) error
Dispatch calls the configured local handler.
type LocalHandler ¶
type LocalHandler func(ctx context.Context, payload DeliverPayload, resourceJSON []byte, metadata map[string]any) error
LocalHandler processes one matched subscription event in-process.
type Manager ¶
type Manager struct {
Store store.SubscriptionStore
Now func() time.Time
}
Manager registers and manages subscription definitions.
func (*Manager) List ¶
func (m *Manager) List(ctx context.Context, status store.SubscriptionStatus, resourceType string, event TriggerEvent) ([]SubscriptionRecord, error)
List returns subscriptions matching optional filters.
func (*Manager) Register ¶
func (m *Manager) Register(ctx context.Context, name string, trigger Trigger, channel Channel, retry RetryPolicy) (SubscriptionRecord, error)
Register creates a new active subscription.
func (*Manager) RegisterFromFHIRSubscription ¶
func (m *Manager) RegisterFromFHIRSubscription(ctx context.Context, input FHIRSubscriptionInput, extensions []map[string]any) (SubscriptionRecord, error)
RegisterFromFHIRSubscription adapts a supported FHIR Subscription shape into the internal trigger model and registers it.
func (*Manager) Update ¶
func (m *Manager) Update(ctx context.Context, rec SubscriptionRecord) (SubscriptionRecord, error)
Update replaces an existing subscription definition.
type MatchContext ¶
type MatchContext struct {
Event store.ResourceEvent
Current *types.ResourceEnvelope
Previous *types.ResourceEnvelope
}
MatchContext carries runtime state for one event evaluation.
type Matcher ¶
Matcher evaluates subscription triggers against resource events.
Registry is required when a trigger has FilterParams (FHIR Subscription.criteria). Hosts must set Matcher.Registry to a search parameter registry; a nil Registry returns ErrNilRegistry instead of silently failing to match.
type PayloadMode ¶
type PayloadMode string
PayloadMode controls webhook body encoding.
const ( PayloadModeResourceJSON PayloadMode = "resource-json" PayloadModeEventOnly PayloadMode = "event-only" )
type Processor ¶
type Processor struct {
Events store.EventStore
Cursors store.CursorStore
Subscriptions store.SubscriptionStore
Jobs store.JobStore
Resources store.ResourceStore
History store.HistoryStore
Matcher *Matcher
Scope string
BatchSize int
Now func() time.Time
}
Processor consumes store.ResourceEvent entries and enqueues delivery jobs.
type RetryPolicy ¶
type RetryPolicy struct {
MaxAttempts int `json:"maxAttempts"`
}
RetryPolicy configures delivery retries via pkg/jobs.
type SubscriptionRecord ¶
type SubscriptionRecord struct {
ID string `json:"id"`
Name string `json:"name"`
Status store.SubscriptionStatus `json:"status"`
Trigger Trigger `json:"trigger"`
Channel Channel `json:"channel"`
RetryPolicy RetryPolicy `json:"retryPolicy"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
SubscriptionRecord is the public subscription definition shape.
type Trigger ¶
type Trigger struct {
ResourceType string `json:"resourceType"`
Event TriggerEvent `json:"event"`
ChangedFields []string `json:"changedFields,omitempty"`
FilterFHIRPath string `json:"filterFhirPath,omitempty"`
Criteria string `json:"criteria,omitempty"`
FilterParams []search.ParamClause `json:"filterParams,omitempty"`
}
Trigger defines when a subscription should fire.
type TriggerEvent ¶
type TriggerEvent string
TriggerEvent describes which resource lifecycle action fires a subscription.
const ( TriggerEventCreate TriggerEvent = "create" TriggerEventUpdate TriggerEvent = "update" TriggerEventDelete TriggerEvent = "delete" // TriggerEventChange matches create and update (FHIR R4 Subscription.criteria), // but not delete. TriggerEventChange TriggerEvent = "change" )
type WebhookConfig ¶
type WebhookConfig struct {
URL string `json:"url"`
Method string `json:"method,omitempty"`
Headers map[string]string `json:"headers,omitempty"`
Timeout time.Duration `json:"timeout,omitempty"`
PayloadMode PayloadMode `json:"payloadMode,omitempty"`
}
WebhookConfig configures HTTP delivery.
type WebhookDispatcher ¶
WebhookDispatcher performs HTTP webhook delivery.
func (*WebhookDispatcher) Dispatch ¶
func (d *WebhookDispatcher) Dispatch(ctx context.Context, cfg WebhookConfig, event DeliverPayload, resource *types.ResourceEnvelope) (WebhookResult, error)
Dispatch sends the configured webhook request.
type WebhookResult ¶
WebhookResult captures one HTTP delivery attempt.