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
- func CanonicalEventID(tenantID string, sequence int64) string
- func DefaultClock() time.Time
- func EnqueueScheduledPull(ctx context.Context, jobStore store.JobStore, nodeID, tenantID string, ...) error
- func OutboxEventID(nodeID, tenantID string, sequence int64) string
- func ResourceEnvelopeFromCanonical(event CanonicalEvent) *types.ResourceEnvelope
- type AckState
- type Applier
- type CanonicalEvent
- type CanonicalStatus
- type Clock
- type Config
- type ConflictJobPayload
- type ConflictResolutionHandler
- type Engine
- type EventStoreOutbox
- type EventType
- type Hub
- type HubServer
- type JobProcessor
- type LocalEvent
- type LocalEventStatus
- type Outbox
- type PostgresHub
- func (h *PostgresHub) Pull(ctx context.Context, afterSequence int64, limit int) ([]CanonicalEvent, error)
- func (h *PostgresHub) PullFor(ctx context.Context, nodeID, tenantID string, afterSequence int64, limit int) ([]CanonicalEvent, error)
- func (h *PostgresHub) Push(ctx context.Context, events []LocalEvent) ([]PushResult, error)
- func (h *PostgresHub) PushFor(ctx context.Context, nodeID, tenantID string, events []LocalEvent) ([]PushResult, error)
- type PullResultSummary
- type PullServer
- type Puller
- type PushResult
- type PushResultSummary
- type PushServer
- type Pusher
- type ReplayJobPayload
- type RetryPushJobPayload
- type ScopedHubServer
- type SearchIndexer
- type SessionOutbox
Constants ¶
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.
const ( CursorPush = "sync.push" CursorPull = "sync.pull" )
Cursor names used by the sync engine.
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 ¶
CanonicalEventID returns the stable, tenant-scoped idempotency key for pull/apply dedupe.
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 ¶
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.
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 ¶
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 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 (*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 ¶
func (o *EventStoreOutbox) Append(ctx context.Context, event store.ResourceEvent) (store.ResourceEvent, error)
Append delegates to the underlying event store.
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 ¶
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 ¶
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 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.
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 ¶
func (o *SessionOutbox) Append(ctx context.Context, event store.ResourceEvent) (store.ResourceEvent, error)
Append delegates to the session-scoped event store.