sync

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

README

haistack-sync (pkg/sync)

Offline-first replication library for haistack — device-to-hub push/pull with canonical Postgres acceptance.

What it does

haistack-sync is the replication layer between local SQLite nodes and a canonical Postgres hub. It follows a Git-inspired model:

Branch Role
Local SQLite node Provisional branch — offline writes append to the outbox
Postgres hub Accepted branch — hub validates, accepts, and assigns canonical sequence/version
Push Device proposes local events to the hub
Pull Device replays accepted canonical events back locally

Think of it as: core writes a change locally → sync pushes it to the server → sync pulls canonical truth back → devices converge.

The package has two layers:

  1. Outbox (write path) — Outbox, EventStoreOutbox, SessionOutbox, WithWriteSession integrate with pkg/core so successful writes emit store.ResourceEvent inside the same transaction.
  2. Sync engine (replication) — Engine, Hub, PostgresHub orchestrate push/pull, cursors, inbox idempotency, conflicts, jobs, audit, and optional search reindex on pull apply.

Public protocol types include LocalEvent, CanonicalEvent, PushResult, acknowledgement states (AckState), and job payloads (ConflictJobPayload, ReplayJobPayload).

It does not:

  • Parse FHIR on the device-side orchestration path or assign version IDs (pkg/core + backends)
  • Implement mandatory HTTP/MQTT transport (Hub is an in-process protocol boundary; pkg/http exposes optional /sync/push and /sync/pull)
  • Own merge policy (pkg/conflict evaluates conflicts; sync detects, persists, and enqueues)
  • Replace pkg/store persistence (it reuses existing contracts)

PostgresHub validates pushed FHIR payloads before canonical acceptance.

How it fits in the ecosystem

 pkg/core (ResourceService + optional Outbox)
        |
        v
 store.EventStore (sqlite outbox / postgres event_log)
        |
        v
 sync.Engine.Push  ----Hub---->  sync.PostgresHub  -->  postgres.ApplyWrite
        ^                              |
        |                              v
 sync.Engine.Pull  <----Hub----  canonical event_log + hub inbox dedupe
        |
        v
 local ResourceStore / HistoryStore / InboxStore / SearchStore (optional)
        |
        +--> store.ConflictStore + jobs (sync.conflict_processing)
        +--> pkg/conflict.Engine (via ConflictEngine config default)
        +--> store.AuditStore (sync audit actions)
Direction Package Relationship
Upstream core Emits minimal ResourceEvent rows when Outbox is wired
Upstream store Event, cursor, inbox, conflict, job, audit, resource, history contracts
Upstream conflict Default ConflictEngine; merge/review artifacts for job handler
Sidecar postgres PostgresHub, canonical event_log, hub inbox
Sidecar sqlite Device outbox, inbox, cursors
Downstream http Optional sync routes via ScopedHubServer
Downstream search Optional SearchIndexer on pull apply
Downstream jobs Retry push, scheduled pull, conflict processing, event replay

When to use it

  • Offline-first apps that write to SQLite and sync when online
  • Edge/cloud hubs that accept device writes into Postgres event_log
  • Workers that replay outbox events or process sync retry jobs
  • Tests that need push/pull round-trips without a real network stack
  • HTTP gateways that expose hub push/pull to authenticated devices

Alias the import when you also use the standard library sync package:

import hasync "github.com/degoke/haistack/pkg/sync"

Usage modes

1. Enable outbox in core (local writes)
import (
    hasync "github.com/degoke/haistack/pkg/sync"
    "github.com/degoke/haistack/pkg/core"
)

svc, err := core.NewResourceService(core.ResourceServiceConfig{
    Resources: db.ResourceStore(),
    History:   db.HistoryStore(),
    Sessions:  db,
    Outbox:    &hasync.EventStoreOutbox{Events: db.OutboxStore()},
})

Core routes outbox appends through the active write session so resource, history, search, and outbox commit or roll back together. Use hasync.WithWriteSession / SessionOutbox when binding outbox to an explicit session.

2. Device node: push, pull, or both
hub := &hasync.PostgresHub{Tenant: tdb}

engine := hasync.NewEngine(hasync.Config{
    NodeID:    "device-1",
    TenantID:  "tenant-a",
    Events:    sqliteDB.OutboxStore(),
    Cursors:   sqliteDB.CursorStore(),
    Inbox:     sqliteDB.InboxStore(),
    Resources: sqliteDB.ResourceStore(),
    History:   sqliteDB.HistoryStore(),
    Sessions:  sqliteDB,
    Conflicts: sqliteDB.ConflictStore(),
    Jobs:      jobStore,
    Audit:     auditStore,
    Hub:       hub,
})

push, pull, err := engine.SyncOnce(ctx)
// or separately:
pushSummary, err := engine.Push(ctx)
pullSummary, err := engine.Pull(ctx)

Cursor names default to sync.push and sync.pull (CursorPush, CursorPull).

3. Canonical hub (Postgres) without device engine
hub := &hasync.PostgresHub{Tenant: tdb}

results, err := hub.Push(ctx, localEvents)
canonical, err := hub.Pull(ctx, afterSequence, limit)

PostgresHub dedupes push by client event_id, checks base versions for stale writes, applies accepted writes via postgres.ApplyWrite, and returns per-event acknowledgements.

4. Pull apply with search index updates
engine := hasync.NewEngine(hasync.Config{
    // …
    Sessions:      sqliteDB,
    Search:        sqliteDB.SearchStore(),
    SearchIndexer: indexer, // implements hasync.SearchIndexer
})

When both Sessions and SearchIndexer are set, pull apply can persist resource, history, inbox, and search rows atomically.

5. Conflict jobs and custom resolution handler
engine := hasync.NewEngine(hasync.Config{
    NodeID:                    "node-a",
    TenantID:                  "tenant-a",
    ConflictEngine:            conflict.NewDefaultEngine(),
    ConflictResolutionHandler: myHandler,
    // … stores and Hub …
})

processor := &hasync.JobProcessor{Engine: engine, Jobs: jobStore}
processed, err := processor.ProcessNext(ctx)

Job types (from pkg/jobs, re-exported in sync):

Constant Purpose
JobTypeRetryPush Retry a failed push batch
JobTypeScheduledPull Background pull
JobTypeConflictProcessing Run pkg/conflict on a persisted conflict
JobTypeEventReplay Replay push or pull from a sequence
6. HTTP-scoped hub server

Implement ScopedHubServer when node and tenant identity come from the HTTP request:

type tenantHub struct{ Inner hasync.HubServer }

func (h tenantHub) PushFor(ctx context.Context, nodeID, tenantID string, events []hasync.LocalEvent) ([]hasync.PushResult, error) {
    return h.Inner.Push(ctx, events)
}

Wire through pkg/http NewRootHandlerWithSyncMiddleware for /sync/push and /sync/pull.

7. Test doubles implementing Hub

In-process tests can implement hasync.Hub with memory stores (see integration_test.go) without Postgres.

Examples

Stable event IDs for idempotency:

pushID := hasync.OutboxEventID(nodeID, tenantID, outboxSequence)
pullID := hasync.CanonicalEventID(tenantID, canonicalSequence)

Inspect push acknowledgement:

for _, ack := range pushSummary.Results {
    switch ack.State {
    case hasync.AckAccepted, hasync.AckAlreadyProcessed:
        // terminal — cursor may advance
    case hasync.AckNeedsRetry:
        // cursor does not advance; retry job may enqueue
    case hasync.AckConflicted:
        // conflict record + conflict_processing job
    }
}

Enqueue scheduled pull:

err := hasync.EnqueueScheduledPull(ctx, jobStore, nodeID, tenantID, time.Now().UTC().Add(time.Minute))

Push and pull behaviour

Push

  1. Read pending outbox events after the push cursor
  2. Enrich into LocalEvent (stable event_id, base cloud version, payload)
  3. Batch to hub in outbox sequence order
  4. Handle ack per event: accepted, rejected, conflicted, already_processed, needs_retry
  5. Record conflicts, audit, and retry jobs as needed
  6. Advance push cursor only for terminal acks (not needs_retry)

Pull

  1. Fetch canonical events after the pull cursor
  2. Apply accepted events locally (idempotent via inbox)
  3. Update resources/history without appending to outbox
  4. Advance pull cursor after successful apply

Idempotency keys

Direction Key
Push dedupe OutboxEventID(nodeID, tenantID, outboxSequence)
Pull dedupe CanonicalEventID(tenantID, canonicalSequence)

Configuration reference

Field Required? Purpose
NodeID, TenantID Yes Device identity for protocol events and audit
Events Yes (push) Local outbox (store.EventStore)
Hub Yes Push/pull protocol adapter
Resources, History Yes (pull) Local apply target
Sessions Recommended (pull) Atomic resource/history/search/inbox apply
Cursors No Push/pull checkpoints
Inbox No Pull apply idempotency
Conflicts, Jobs, Audit No Side effects on push conflict/retry
Search, SearchIndexer No Index updates on pull apply
ConflictEngine No Defaults to conflict.NewDefaultEngine()
ConflictResolutionHandler No Replay/resubmit or surface review UI
PushBatchSize, PullBatchSize No Default 100

Where it fits

Package Role
core CRUD + optional outbox emission
store EventStore, CursorStore, InboxStore, ConflictStore, JobStore, AuditStore
sqlite Device outbox, inbox, cursors, local apply target
postgres Canonical event_log, hub inbox, PostgresHub backend
conflict Merge policy invoked from conflict jobs
search Optional pull-time indexing
http Optional REST sync endpoints
sync Protocol models, engine, push/pull, scheduler hooks

Limits

  • Network transport adapters beyond in-process Hub and optional HTTP routes are application-owned
  • Peer-to-peer sync and encrypted/signed payloads are deferred
  • Partial sync by patient/module/facility is not implemented
  • Rich merge policy defaults to human review except safe-list paths in pkg/conflict
  • ChangedPaths / Patch on LocalEvent exist but are not populated by enrich yet
  • Push cursor does not advance on needs_retry — callers must retry or run jobs

Documentation

Overview

Package sync implements haistack-sync, the offline-first replication library for HAIStack.

haistack-sync layers a device-to-edge protocol on top of the minimal store.ResourceEvent outbox emitted by pkg/core. Local SQLite nodes act as provisional branches; canonical Postgres hubs act as accepted branches. Push proposes local events; pull replays accepted canonical events back to the node.

Public concepts

  • Engine — high-level entrypoint for Push, Pull, and SyncOnce
  • Config — local stores, hub adapter, node id, tenant id, clock
  • Hub — protocol boundary for push/pull against a canonical server
  • LocalEvent — rich local sync protocol payload enriched from outbox events
  • CanonicalEvent — hub-assigned replay payload for ordered pull/apply
  • PushResult — per-event acknowledgement with canonical metadata
  • PostgresHub — canonical hub implementation backed by pkg/postgres

Outbox (existing)

Outbox, EventStoreOutbox, SessionOutbox, and WithWriteSession remain the write-path emission boundary used by pkg/core. See outbox.go and session_outbox.go.

Store contracts

The engine reuses pkg/store contracts directly:

  • store.EventStore — local outbox on SQLite, canonical event_log on Postgres
  • store.CursorStore — push and pull checkpoints
  • store.InboxStore — pull/apply idempotency (and hub push dedupe)
  • store.ConflictStore — stale-base and sync conflicts
  • store.JobStore — retry and conflict follow-up jobs (processed via pkg/jobs)
  • store.AuditStore — sync audit trail (actions via pkg/audit)

Typical device wiring

hub := &sync.PostgresHub{Tenant: tdb}
engine := sync.NewEngine(sync.Config{
    NodeID:    "device-1",
    TenantID:  "tenant-a",
    Events:    sqliteDB.OutboxStore(),
    Cursors:   sqliteDB.CursorStore(),
    Inbox:     sqliteDB.InboxStore(),
    Resources: sqliteDB.ResourceStore(),
    History:   sqliteDB.HistoryStore(),
    Hub:       hub,
})
_, _, err := engine.SyncOnce(ctx)

Ownership boundaries

haistack-sync owns protocol models, outbox batching, inbox flow, push/pull orchestration, canonical acknowledgement handling, base-version checks, tombstone delete replication, cursor progression, retry scheduling hooks, and conflict/job/audit side effects. Detailed merge policy belongs in future haistack-conflict.

File layout

  • doc.go — package documentation
  • outbox.go — Outbox interface and EventStoreOutbox
  • session_outbox.go — transactional outbox routing for core
  • event.go — LocalEvent and CanonicalEvent models
  • ack.go — acknowledgement states and PushResult
  • hub.go — Hub interface, Config, cursor names
  • enrich.go — ResourceEvent → LocalEvent enrichment
  • apply.go — canonical pull apply pipeline
  • push.go / pull.go — push and pull orchestration
  • engine.go — Engine entrypoint
  • server_postgres.go — PostgresHub server
  • jobs.go / audit.go — job payloads and audit action names
  • scheduler.go — JobProcessor and scheduled pull enqueue
  • search.go — SearchIndexer hook for pull apply indexing

Index

Constants

View Source
const (
	AuditSyncAccepted        = audit.ActionSyncAccepted
	AuditSyncRejected        = audit.ActionSyncRejected
	AuditSyncConflicted      = audit.ActionSyncConflicted
	AuditDevicePushed        = audit.ActionDevicePushed
	AuditDevicePulled        = audit.ActionDevicePulled
	AuditConflictAutoMerged  = audit.ActionConflictAutoMerged
	AuditConflictNeedsReview = audit.ActionConflictNeedsReview
)

Audit action identifiers written by the sync engine. Canonical definitions live in pkg/audit; re-exported here for callers.

View Source
const (
	CursorPush = "sync.push"
	CursorPull = "sync.pull"
)

Cursor names used by the sync engine.

View Source
const (
	JobTypeRetryPush          = jobs.TypeSyncRetryPush
	JobTypeScheduledPull      = jobs.TypeSyncScheduledPull
	JobTypeConflictProcessing = jobs.TypeSyncConflictProcessing
	JobTypeEventReplay        = jobs.TypeSyncEventReplay
)

Job type identifiers enqueued by the sync engine. Canonical names live in pkg/jobs; re-exported here for callers.

Variables

This section is empty.

Functions

func CanonicalEventID

func CanonicalEventID(tenantID string, sequence int64) string

CanonicalEventID returns the stable, tenant-scoped idempotency key for pull/apply dedupe.

func DefaultClock

func DefaultClock() time.Time

DefaultClock returns UTC now.

func EnqueueScheduledPull

func EnqueueScheduledPull(ctx context.Context, jobStore store.JobStore, nodeID, tenantID string, runAfter time.Time) error

EnqueueScheduledPull schedules a future pull attempt.

func OutboxEventID

func OutboxEventID(nodeID, tenantID string, sequence int64) string

OutboxEventID returns a stable client event id for one outbox row.

func ResourceEnvelopeFromCanonical

func ResourceEnvelopeFromCanonical(event CanonicalEvent) *types.ResourceEnvelope

ResourceEnvelopeFromCanonical builds a minimal envelope for tombstone deletes.

Types

type AckState

type AckState string

AckState is the per-event acknowledgement returned by the hub on push.

const (
	AckAccepted         AckState = "accepted"
	AckRejected         AckState = "rejected"
	AckConflicted       AckState = "conflicted"
	AckAlreadyProcessed AckState = "already_processed"
	AckNeedsRetry       AckState = "needs_retry"
)

type Applier

type Applier struct {
	TenantID  string
	Resources store.ResourceStore
	History   store.HistoryStore
	Sessions  store.WriteSessionProvider
	Inbox     store.InboxStore
	Search    store.SearchStore
	Indexer   SearchIndexer
	Clock     Clock
}

Applier applies accepted canonical events to a local node without emitting outbox events.

func (*Applier) ApplyCanonical

func (a *Applier) ApplyCanonical(ctx context.Context, event CanonicalEvent) (bool, error)

ApplyCanonical replays one accepted canonical event locally with inbox idempotency.

type CanonicalEvent

type CanonicalEvent struct {
	EventID               string                  `json:"eventId"`
	OriginNodeID          string                  `json:"originNodeId,omitempty"`
	TenantID              string                  `json:"tenantId"`
	ResourceType          string                  `json:"resourceType"`
	ResourceID            string                  `json:"resourceId"`
	Operation             EventType               `json:"operation"`
	BaseCloudVersion      string                  `json:"baseCloudVersion,omitempty"`
	LocalVersion          string                  `json:"localVersion,omitempty"`
	ResourceAfter         *types.ResourceEnvelope `json:"resourceAfter,omitempty"`
	ResourceHash          string                  `json:"resourceHash,omitempty"`
	CanonicalSequence     int64                   `json:"canonicalSequence"`
	CanonicalVersionID    string                  `json:"canonicalVersionId"`
	Status                CanonicalStatus         `json:"status"`
	AcknowledgedAt        time.Time               `json:"acknowledgedAt,omitempty"`
	ConflictReason        string                  `json:"conflictReason,omitempty"`
	ConflictRemoteVersion string                  `json:"conflictRemoteVersion,omitempty"`
}

CanonicalEvent is a hub-assigned replay event returned to device nodes on pull.

type CanonicalStatus

type CanonicalStatus string

CanonicalStatus describes hub disposition for a canonical replay event.

const (
	CanonicalStatusAccepted   CanonicalStatus = "accepted"
	CanonicalStatusRejected   CanonicalStatus = "rejected"
	CanonicalStatusConflicted CanonicalStatus = "conflicted"
)

type Clock

type Clock func() time.Time

Clock returns the current time; tests may inject a deterministic clock.

type Config

type Config struct {
	NodeID   string
	TenantID string

	Events    store.EventStore
	Cursors   store.CursorStore
	Inbox     store.InboxStore
	Resources store.ResourceStore
	History   store.HistoryStore
	// Sessions enables atomic pull application. Database-backed sessions should
	// expose store.InboxWriteSession so the inbox mark commits with the apply.
	Sessions  store.WriteSessionProvider
	Conflicts store.ConflictStore
	Jobs      store.JobStore
	Audit     store.AuditStore
	Search    store.SearchStore

	Hub Hub

	// ConflictEngine evaluates persisted conflicts and produces merge/rebase artifacts.
	ConflictEngine *conflict.Engine

	// ConflictResolutionHandler receives the merge/review result so the runtime can replay/resubmit.
	ConflictResolutionHandler ConflictResolutionHandler

	// SearchIndexer optionally builds search rows when applying canonical events locally.
	SearchIndexer SearchIndexer

	Clock Clock

	PushCursorName string
	PullCursorName string
	PushBatchSize  int
	PullBatchSize  int
}

Config wires local stores and the hub adapter for one device node.

type ConflictJobPayload

type ConflictJobPayload struct {
	NodeID          string `json:"nodeId"`
	TenantID        string `json:"tenantId"`
	ConflictID      string `json:"conflictId,omitempty"`
	EventID         string `json:"eventId"`
	ResourceType    string `json:"resourceType"`
	ResourceID      string `json:"resourceId"`
	LocalVersionID  string `json:"localVersionId"`
	RemoteVersionID string `json:"remoteVersionId"`
	Reason          string `json:"reason"`
	// LocalEvent carries the full sync payload so the conflict engine can
	// evaluate the local intent without needing to reconstruct it from history.
	LocalEvent []byte `json:"localEvent,omitempty"`
}

ConflictJobPayload schedules conflict follow-up processing.

type ConflictResolutionHandler

type ConflictResolutionHandler interface {
	OnConflictResolution(ctx context.Context, payload ConflictJobPayload, result conflict.MergeResult) error
}

ConflictResolutionHandler receives the result of a conflict-processing job so the sync runtime can replay or resubmit an auto-merge, or surface review metadata.

type Engine

type Engine struct {
	Config Config
}

Engine is the high-level sync entrypoint for device nodes.

func NewEngine

func NewEngine(cfg Config) *Engine

NewEngine constructs a sync engine from config.

func (*Engine) Pull

func (e *Engine) Pull(ctx context.Context) (*PullResultSummary, error)

Pull fetches and applies canonical hub events.

func (*Engine) Push

func (e *Engine) Push(ctx context.Context) (*PushResultSummary, error)

Push proposes pending local outbox events to the hub.

func (*Engine) SyncOnce

func (e *Engine) SyncOnce(ctx context.Context) (push *PushResultSummary, pull *PullResultSummary, err error)

SyncOnce runs one push pass followed by one pull pass.

type EventStoreOutbox

type EventStoreOutbox struct {
	Events store.EventStore
}

EventStoreOutbox adapts a store.EventStore to the Outbox interface. When used with pkg/core, Append is routed through sync.WithWriteSession for transactional writes.

func (*EventStoreOutbox) Append

Append delegates to the underlying event store.

type EventType

type EventType string

EventType names a sync protocol event family.

const (
	EventTypeResourceCreated    EventType = "resource.created"
	EventTypeResourceUpdated    EventType = "resource.updated"
	EventTypeResourceDeleted    EventType = "resource.deleted"
	EventTypeResourceConflicted EventType = "resource.conflicted"
)

type Hub

type Hub interface {
	Push(ctx context.Context, events []LocalEvent) ([]PushResult, error)
	Pull(ctx context.Context, afterSequence int64, limit int) ([]CanonicalEvent, error)
}

Hub is the protocol boundary used by Engine to push local events and pull canonical events.

type HubServer

type HubServer interface {
	PushServer
	PullServer
}

HubServer combines push and pull handlers for a canonical postgres hub.

type JobProcessor

type JobProcessor struct {
	Engine *Engine
	Jobs   store.JobStore
	Clock  Clock
}

JobProcessor executes sync background jobs against an Engine.

func (*JobProcessor) ProcessNext

func (p *JobProcessor) ProcessNext(ctx context.Context) (bool, error)

ProcessNext claims and runs one pending sync job of any supported type using the shared jobs.Runner runtime.

type LocalEvent

type LocalEvent struct {
	EventID          string                  `json:"eventId"`
	OriginNodeID     string                  `json:"originNodeId"`
	TenantID         string                  `json:"tenantId"`
	ResourceType     string                  `json:"resourceType"`
	ResourceID       string                  `json:"resourceId"`
	Operation        EventType               `json:"operation"`
	BaseCloudVersion string                  `json:"baseCloudVersion,omitempty"`
	LocalVersion     string                  `json:"localVersion"`
	ChangedPaths     []string                `json:"changedPaths,omitempty"`
	Patch            []byte                  `json:"patch,omitempty"`
	ResourceAfter    *types.ResourceEnvelope `json:"resourceAfter,omitempty"`
	ResourceHash     string                  `json:"resourceHash,omitempty"`
	Status           LocalEventStatus        `json:"status"`
	CreatedAt        time.Time               `json:"createdAt"`
	OutboxSequence   int64                   `json:"outboxSequence,omitempty"`
}

LocalEvent is the rich sync protocol payload proposed from a device node.

func EnrichLocalEvent

func EnrichLocalEvent(
	ctx context.Context,
	event store.ResourceEvent,
	nodeID, tenantID string,
	history store.HistoryStore,
) (LocalEvent, error)

EnrichLocalEvent maps a store.ResourceEvent into a sync protocol LocalEvent.

type LocalEventStatus

type LocalEventStatus string

LocalEventStatus tracks device-side sync state for one outbox-derived event.

const (
	LocalEventStatusPending    LocalEventStatus = "pending"
	LocalEventStatusPushed     LocalEventStatus = "pushed"
	LocalEventStatusAccepted   LocalEventStatus = "accepted"
	LocalEventStatusRejected   LocalEventStatus = "rejected"
	LocalEventStatusConflicted LocalEventStatus = "conflicted"
	LocalEventStatusRetry      LocalEventStatus = "retry"
)

type Outbox

type Outbox interface {
	// Append stores one ResourceEvent and returns it with Sequence when assigned by the backend.
	Append(ctx context.Context, event store.ResourceEvent) (store.ResourceEvent, error)
}

Outbox appends resource change events for downstream sync pipelines.

func WithWriteSession

func WithWriteSession(o Outbox, session store.WriteSession) Outbox

WithWriteSession returns an Outbox that routes Append through session for transactional writes. EventStoreOutbox instances use the session event store; other Outbox implementations are called directly.

type PostgresHub

type PostgresHub struct {
	Tenant        *postgres.TenantDB
	Clock         Clock
	SearchIndexer SearchIndexer
	Validator     validate.Validator
}

PostgresHub implements Hub and HubServer against a canonical postgres tenant database.

func (*PostgresHub) Pull

func (h *PostgresHub) Pull(ctx context.Context, afterSequence int64, limit int) ([]CanonicalEvent, error)

Pull returns accepted canonical events after a sequence checkpoint.

func (*PostgresHub) PullFor

func (h *PostgresHub) PullFor(ctx context.Context, nodeID, tenantID string, afterSequence int64, limit int) ([]CanonicalEvent, error)

PullFor validates the HTTP caller's tenant binding and verifies that the tenant-scoped store cannot return cross-tenant events.

func (*PostgresHub) Push

func (h *PostgresHub) Push(ctx context.Context, events []LocalEvent) ([]PushResult, error)

Push accepts proposed local events, applies accepted writes, and returns per-event acks.

func (*PostgresHub) PushFor

func (h *PostgresHub) PushFor(ctx context.Context, nodeID, tenantID string, events []LocalEvent) ([]PushResult, error)

PushFor validates the HTTP caller's node and tenant binding before using the tenant-scoped hub implementation.

type PullResultSummary

type PullResultSummary struct {
	Fetched int
	Applied int
	Skipped int
	Cursor  int64
}

PullResultSummary aggregates one pull pass.

type PullServer

type PullServer interface {
	Pull(ctx context.Context, afterSequence int64, limit int) ([]CanonicalEvent, error)
}

PullServer returns canonical events after a sequence checkpoint.

type Puller

type Puller struct {
	Config  Config
	Applier *Applier
}

Puller fetches canonical events and applies them locally.

func (*Puller) Pull

func (p *Puller) Pull(ctx context.Context) (*PullResultSummary, error)

Pull fetches canonical events after the pull cursor and applies accepted events locally.

type PushResult

type PushResult struct {
	EventID                 string                  `json:"eventId"`
	State                   AckState                `json:"state"`
	CanonicalSequence       int64                   `json:"canonicalSequence,omitempty"`
	CanonicalVersionID      string                  `json:"canonicalVersionId,omitempty"`
	RejectionReason         string                  `json:"rejectionReason,omitempty"`
	RejectionOutcome        *types.OperationOutcome `json:"rejectionOutcome,omitempty"`
	ConflictReason          string                  `json:"conflictReason,omitempty"`
	ConflictRemoteVersionID string                  `json:"conflictRemoteVersionId,omitempty"`
	RetryAfter              time.Time               `json:"retryAfter,omitempty"`
}

PushResult carries hub acknowledgement metadata for one proposed local event.

func (PushResult) IsTerminal

func (r PushResult) IsTerminal() bool

IsTerminal reports whether the device can advance its push cursor past this event.

type PushResultSummary

type PushResultSummary struct {
	Proposed int
	Results  []PushResult
	Cursor   int64
}

PushResultSummary aggregates one push pass.

type PushServer

type PushServer interface {
	Push(ctx context.Context, events []LocalEvent) ([]PushResult, error)
}

PushServer accepts proposed local events from device nodes.

type Pusher

type Pusher struct {
	Config Config
}

Pusher reads pending outbox events and proposes them to the hub.

func (*Pusher) Push

func (p *Pusher) Push(ctx context.Context) (*PushResultSummary, error)

Push reads local outbox events after the push cursor and sends them to the hub.

type ReplayJobPayload

type ReplayJobPayload struct {
	NodeID       string `json:"nodeId"`
	TenantID     string `json:"tenantId"`
	FromSequence int64  `json:"fromSequence,omitempty"`
	EventID      string `json:"eventId,omitempty"`
	CanonicalSeq int64  `json:"canonicalSequence,omitempty"`
	Reason       string `json:"reason,omitempty"`
}

ReplayJobPayload schedules a push or pull replay attempt.

type RetryPushJobPayload

type RetryPushJobPayload struct {
	NodeID   string `json:"nodeId"`
	TenantID string `json:"tenantId"`
	EventID  string `json:"eventId"`
	Reason   string `json:"reason,omitempty"`
}

RetryPushJobPayload is a narrow alias for push retry scheduling.

type ScopedHubServer

type ScopedHubServer interface {
	HubServer
	PushFor(ctx context.Context, nodeID, tenantID string, events []LocalEvent) ([]PushResult, error)
	PullFor(ctx context.Context, nodeID, tenantID string, afterSequence int64, limit int) ([]CanonicalEvent, error)
}

ScopedHubServer is the HTTP-safe variant of HubServer. The request's node and tenant identity are part of the server operation rather than merely metadata carried beside an unscoped call.

type SearchIndexer

type SearchIndexer interface {
	BuildSearchEntries(ctx context.Context, res *types.ResourceEnvelope) ([]store.SearchIndexEntry, error)
}

SearchIndexer builds search index entries for one resource envelope.

type SessionOutbox

type SessionOutbox struct {
	Session store.WriteSession
}

SessionOutbox appends events through a write session's event store.

func (*SessionOutbox) Append

Append delegates to the session-scoped event store.

Jump to

Keyboard shortcuts

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