subscriptions

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

README

haistack-subscriptions (pkg/subscriptions)

Tenant-neutral event automation on top of store.EventStore change events and pkg/jobs background delivery.

What it does

haistack-subscriptions is a downstream consumer of the existing resource event log. It registers triggers on resource type and event kind, matches incoming store.ResourceEvent entries, and enqueues durable delivery jobs. It does not hook into pkg/core write paths directly.

Capabilities:

  • Internal trigger model — resource type + event (create, update, delete, or change for create+update), optional changed-field filters, optional FHIRPath predicates, optional search criteria
  • FHIR adapter — RegisterFromFHIRSubscription maps a supported subset of FHIR Subscription (rest-hook only) into the internal model
  • Event processor — reads EventStore since a CursorStore checkpoint, matches active subscriptions, enqueues delivery jobs
  • Durable delivery — webhook (HTTP POST/PUT) and local (in-process handler) channels
  • Retry + logging — retries via pkg/jobs; operational delivery logs in subscription_delivery_log

Core types:

Type Purpose
Manager Register, update, disable, list, delete subscription records
Processor Consume ResourceEvent entries and schedule delivery work
DeliveryWorker Execute queued deliveries
DeliveryJobRunner Claim and run delivery jobs via pkg/jobs
Matcher Evaluate triggers against current/previous resource state
WebhookDispatcher HTTP POST/PUT transport
LocalDispatcher / HandlerRegistry In-process handler transport

Job type: jobs.TypeSubscriptionsDeliver (subscriptions.deliver).

It does not (v1):

  • WebSocket, email, SMS, or message channel types
  • Dead-letter queues or full delivery audit expansion
  • Kafka/NATS or a separate queue service
  • Tenant semantics in the core API (Postgres scoping is via TenantDB wiring)
  • Chained, _include, _revinclude, full-text, modifiers (:not, :exact), or comparator prefixes in FHIR Subscription.criteria
  • Delete notifications from FHIR Subscription.criteria (use internal TriggerEventDelete if needed)

How it fits in the ecosystem

pkg/core (write)  →  EventStore (outbox / event_log)
                           |
                           v
              subscriptions.Processor (Matcher + cursor)
                           |
                           v
                     JobStore (subscriptions.deliver)
                           |
                           v
              subscriptions.DeliveryWorker
                    /              \
         WebhookDispatcher    LocalDispatcher
Direction Package Relationship
Upstream core Produces ResourceEvent on writes (unchanged)
Upstream store Event, cursor, job, subscription, resource, history stores
Upstream fhirpath FilterFHIRPath evaluation in Matcher
Upstream search ParseQuery, MatchResourceParameter, criteria params
Downstream jobs Durable queue and retry runtime
Sidecar runtime Wires default matcher with engine + registry

When to use it

  • Webhook notifications when FHIR resources change (REST-hook style)
  • In-process reactions — register a named local handler for create/update/delete
  • Filtered triggers — e.g. Observation.created where code = X via FHIRPath
  • Field-scoped updates — e.g. only when Appointment.status changed
  • Edge (SQLite) or hub (Postgres) — same package, different store wiring
  • FHIR Subscription compatibility for simple equality criteria (Patient?active=true)

Usage modes

1. Register and manage subscriptions (Manager)
mgr := &subscriptions.Manager{Store: db.SubscriptionStore()}

rec, err := mgr.Register(ctx, "patient-created",
    subscriptions.Trigger{
        ResourceType: "Patient",
        Event:        subscriptions.TriggerEventCreate,
    },
    subscriptions.Channel{
        Type: subscriptions.ChannelTypeWebhook,
        Webhook: &subscriptions.WebhookConfig{
            URL:    "https://example.test/hooks/patient",
            Method: "POST",
        },
    },
    subscriptions.RetryPolicy{MaxAttempts: 5},
)

Also: Update, Disable, Enable, List, Get, Delete on the manager.

2. Field-scoped and FHIRPath triggers
// Appointment.status changed
subscriptions.Trigger{
    ResourceType:  "Appointment",
    Event:         subscriptions.TriggerEventUpdate,
    ChangedFields: []string{"status"},
}

// Observation.created where code = 8867-4
subscriptions.Trigger{
    ResourceType:   "Observation",
    Event:          subscriptions.TriggerEventCreate,
    FilterFHIRPath: "code.coding.code = '8867-4'",
}

Changed-field matching compares top-level JSON fields between previous history snapshot and current resource.

3. Run the event processor (batch or loop)
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},
    Scope:         "default",
}

n, err := processor.RunOnce(ctx)
go processor.RunLoop(ctx, time.Second)

Checkpoint: subscriptions.CursorName(scope) → subscriptions.processor.{scope}.

Matcher.Registry is required when triggers use FilterParams or FHIR criteria; nil registry returns ErrNilRegistry.

4. Delivery workers and local handlers
registry := subscriptions.NewHandlerRegistry()
registry.Register("on-patient-created", func(ctx context.Context, payload subscriptions.DeliverPayload, resourceJSON []byte, metadata map[string]any) error {
    return nil
})

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,
    MaxAttempts: 5,
}
_, err := runner.RunOnce(ctx)

Delivery job IDs: subscriptions:deliver:{subscriptionId}:{eventSequence} (idempotent re-processing).

5. FHIR Subscription adapter
rec, err := mgr.RegisterFromFHIRSubscription(ctx, subscriptions.FHIRSubscriptionInput{
    Status:   "active",
    Criteria: "Patient?active=true",
    Channel: subscriptions.FHIRSubscriptionChannel{
        Type:     "rest-hook",
        Endpoint: "https://example.test/hook",
        Payload:  "application/fhir+json",
    },
}, extensions)

Parse from FHIR JSON:

input, extensions, err := subscriptions.ParseFHIRSubscriptionJSON(subscriptionJSON)

Unsupported shapes return ErrUnsupportedFHIR (modifiers, chains, websocket channel, etc.).

6. Search-criteria triggers (create + update)
parsed, _ := search.ParseQuery("Observation", url.Values{"code": []string{"8867-4"}})
trigger := subscriptions.Trigger{
    ResourceType: "Observation",
    Event:        subscriptions.TriggerEventChange,
    Criteria:     "Observation?code=8867-4",
    FilterParams: parsed.Params,
}

Internal TriggerEventChange matches create and update; FHIR adapter uses the same semantics for criteria subscriptions.

Examples

Disable a subscription without deleting:

err := mgr.Disable(ctx, rec.ID)

Webhook with custom headers:

subscriptions.WebhookConfig{
    URL:     "https://hooks.example/clinical",
    Method:  "POST",
    Headers: map[string]string{"X-Tenant": "a"},
}

Inspect delivery log after failure:

deliveries, err := db.SubscriptionDeliveryStore().ListBySubscription(ctx, rec.ID, limit)

Storage

Contracts in pkg/store:

Interface Role
SubscriptionStore Registry CRUD
SubscriptionDeliveryStore Delivery attempt log
CursorStore Processor checkpoint (reused)
JobStore Delivery work + retries (reused)
Backend Tables Accessors
SQLite subscription_registry, subscription_delivery_log sqlite.DB.SubscriptionStore(), SubscriptionDeliveryStore()
Postgres same + tenant_id postgres.TenantDB.SubscriptionStore(), SubscriptionDeliveryStore()

Configuration / key types

Type Notes
TriggerEvent create, update, delete, change
ChannelType webhook, local
SubscriptionRecord ID, name, status, trigger, channel, retry policy, timestamps
DeliverPayload Subscription id, event sequence, resource type/id, operation
RetryPolicy MaxAttempts (defaults applied when <= 0)

Errors: ErrNilStore, ErrNilEngine, ErrNilRegistry, ErrNotFound, ErrInvalidTrigger, ErrInvalidChannel, ErrUnsupportedFHIR, ErrUnknownHandler, ErrDuplicateDelivery.

Where it fits

Package Role
store Event, cursor, job, subscription stores
jobs Durable delivery queue and retry runtime
fhirpath In-resource filter evaluation
search Criteria parsing and parameter matching
core Produces events; subscriptions optional at deploy time
sqlite / postgres Persistence backends

Limits

  • FHIR adapter: rest-hook only; criteria equality parameters without modifiers
  • No delete notifications for FHIR criteria subscriptions
  • Local handler names are in-memory only (HandlerRegistry)
  • Processor scope is a string partition for cursors — not a security boundary
  • Webhook dispatcher uses standard library HTTP client; mTLS and signing are caller responsibilities
  • Dead-letter and expanded audit trails deferred

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

  1. Processor.RunOnce/RunLoop reads EventStore.ReadSince using CursorStore.
  2. For each event, active subscriptions are loaded by resource type and event kind (create/update also load TriggerEventChange FHIR criteria).
  3. Matcher evaluates changed fields (via history) and FHIRPath filters.
  4. On match, one delivery job is enqueued per subscription-event pair.
  5. DeliveryWorker resolves subscription context, dispatches via webhook or local handler, and appends/updates delivery-log records.
  6. 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

Constants

This section is empty.

Variables

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

func CursorName(scope string) string

CursorName returns a stable processor checkpoint name for a scope.

func DeliveryJobID

func DeliveryJobID(subscriptionID string, eventSequence int64) string

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.

func (*DeliveryJobRunner) RunOnce

func (r *DeliveryJobRunner) RunOnce(ctx context.Context) (processed bool, err error)

RunOnce claims at most one pending delivery job and executes it.

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.

func (*DeliveryWorker) HandleJob

func (w *DeliveryWorker) HandleJob(ctx context.Context, job store.JobRecord) error

HandleJob implements jobs.Handler for subscription delivery.

type FHIRSubscriptionChannel

type FHIRSubscriptionChannel struct {
	Type     string
	Endpoint string
	Payload  string
	Headers  []string
}

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) Delete

func (m *Manager) Delete(ctx context.Context, id string) error

Delete removes a subscription definition.

func (*Manager) Disable

func (m *Manager) Disable(ctx context.Context, id string) error

Disable marks a subscription inactive without deleting it.

func (*Manager) Get

Get returns one subscription by id.

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

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

type Matcher struct {
	Engine   fhirpath.Engine
	Registry search.Registry
}

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.

func (*Matcher) Matches

func (m *Matcher) Matches(ctx context.Context, trigger Trigger, mc MatchContext) (bool, error)

Matches reports whether trigger conditions are satisfied for one event.

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.

func (*Processor) RunLoop

func (p *Processor) RunLoop(ctx context.Context, idle time.Duration) error

RunLoop repeatedly calls RunOnce until ctx is cancelled.

func (*Processor) RunOnce

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

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

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

type WebhookDispatcher struct {
	Client *http.Client
}

WebhookDispatcher performs HTTP webhook delivery.

func (*WebhookDispatcher) Dispatch

Dispatch sends the configured webhook request.

type WebhookResult

type WebhookResult struct {
	StatusCode int
	Body       string
}

WebhookResult captures one HTTP delivery attempt.

Jump to

Keyboard shortcuts

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