Documentation
¶
Overview ¶
Package connect binds the sync engine to an external source of truth — an adopter-owned store the engine does not manage (a folder of files, an existing database) — and keeps the two converged bidirectionally.
The engine remains the ordering authority: every external change enters through the trusted write path (server.Mutate) where it is sequenced and conflict-resolved exactly like a client write, and every committed engine change flows back out through the change feed (server.Changes). The adopter implements one port (Source) over their store; the Connector owns the scheduling, the loop-prevention bookkeeping, and crash recovery.
Scale ¶
A connector is expected to run against many workspaces at once — one per connected account — so nothing here runs per workspace. Work is scheduled onto a fixed pool of workers (Config.Workers): a commit wakes its workspace through the notifier's activity stream, one subscription for the whole store, and one sweep discovers workspaces and runs the periodic pass. What the process holds is a small record per managed workspace, and what it does at once is the size of the pool — which is also what keeps a fleet of workspaces from arriving at one rate-limited API together.
Single instance ¶
Nothing leases a workspace to one connector, and the bookkeeping that keeps a write from echoing — cursors and shadows — lives in the connector's own State rather than the engine's store, where a second instance would not see it. Two processes converging the same workspace both egress to the source, so run exactly one instance. A rolling deploy counts: the outgoing process converges while the incoming one starts, and Close waiting on in-flight passes narrows that window without closing it.
Index ¶
- Variables
- func PlainTextField(msg proto.Message, field string) (string, error)
- func RetryAfter(err error, d time.Duration) error
- type Binding
- type Config
- type Connector
- func (c *Connector) Close() error
- func (c *Connector) Drain(ctx context.Context, workspaceID string) error
- func (c *Connector) Forget(workspaceID string)
- func (c *Connector) Health(workspaceID string) (Health, bool)
- func (c *Connector) HealthAll() []Health
- func (c *Connector) Ingress(ctx context.Context, workspaceID string) error
- func (c *Connector) Kick(workspaceID string)
- func (c *Connector) Reconcile(ctx context.Context, workspaceID string) error
- func (c *Connector) Start(ctx context.Context) error
- func (c *Connector) Tracked() int
- type Deletion
- type Delta
- type Direction
- type FailureKind
- type Health
- type Incremental
- type Item
- type Shadow
- type Source
- type SourceSync
- type State
- type Writer
Constants ¶
This section is empty.
Variables ¶
var ( // ErrCursorInvalid says an incremental cursor can no longer be resolved — // IMAP's UIDVALIDITY bumped, a history window expired, the account was // rebuilt. Wrap it from Incremental.Changes and the connector falls back // to a fresh Checkpoint plus a full List within the same pass. ErrCursorInvalid = errors.New("connect: source cursor is invalid") // ErrNeedsUserAction says the failure will not heal by retrying: a refresh // token expired, consent was revoked, the account was disconnected. Wrap // it from any Source method (or from Config.OpenSource) and the connector // classifies the workspace's Health as FailureUserAction and drops its // cached source, so the next pass rebuilds credentials from scratch. ErrNeedsUserAction = errors.New("connect: source needs user action") )
The sentinels a Source wraps to tell the connector something it cannot infer from an opaque error.
Functions ¶
func PlainTextField ¶
PlainTextField decodes the collaborative-text field `field` (top-level proto name) of an engine message to its visible string — the egress rendering a Source.Write uses to serialize a text field natively.
func RetryAfter ¶
RetryAfter wraps err with a delay the source asked for — an HTTP Retry-After header, a documented quota reset. The runner then waits exactly that long before the workspace's next attempt instead of applying its own exponential backoff, so a rate-limited API is obeyed rather than guessed at. Returns nil when err is nil.
Types ¶
type Binding ¶
Binding declares one entity and the direction it syncs in. Config.Entities is the all-Bidirectional shorthand for the same thing.
type Config ¶
type Config struct {
// Server is the engine the connector ingresses into (server.Mutate) and
// egresses out of (server.Changes).
Server *server.Server
// Source is the adopter's port over the external store, shared by every
// workspace. Exactly one of Source and OpenSource is required.
Source Source
// OpenSource builds a Source for one workspace, so a per-user credentialed
// store has somewhere to keep its token, connection and rate-limit state.
// It is called lazily on the workspace's first pass and the result is
// reused; when the returned Source implements io.Closer it is closed once
// the connector is done with it (Close, Forget, or a pass failing with
// ErrNeedsUserAction). Exactly one of Source and OpenSource is required.
OpenSource func(ctx context.Context, workspaceID string) (Source, error)
// State is the connector's durable bookkeeping (e.g. sqlitestate.Open).
// The Connector owns it after New succeeds; Close closes it.
State State
// Entities are prototypes of the entities this connector binds
// bidirectionally — the shorthand for one Bindings entry per prototype
// with the default Direction. Each must be registered on Server. Changes
// to entities outside this set (and outside Bindings) never reach the
// Source.
Entities []proto.Message
// Bindings declares entities whose direction is not the default. Merged
// with Entities; binding the same entity through both is an error.
Bindings []Binding
// BatchSize bounds rows per change-feed page during egress (default 256).
BatchSize int
// Workers bounds how many convergence passes run at once, across every
// workspace (default 16). It is the connector's only concurrency bound: a
// sweep queues every managed workspace, and what keeps them from arriving
// at the source together is the size of this pool, not the size of the
// queue.
//
// It is the setting that decides how hard a connector leans on the far
// side. Lower it for an API with a shared per-account rate limit; raise it
// when passes are slow and independent, since a fleet of workspaces takes
// this number of passes per round trip to get through. Passes for one
// workspace never overlap whatever this is set to.
Workers int
// ReconcileInterval is how often Start runs a periodic pass per workspace
// (and how often workspaces are discovered and dropped). 0 means the
// default (1 minute); negative disables periodic passes, leaving commit
// signals, Kick and manual calls as the only triggers — discovery still
// runs, at a fixed one-minute cadence. For an Incremental source this is
// how often Changes is polled, not how often the store is enumerated.
ReconcileInterval time.Duration
// FullReconcileInterval bounds how long an Incremental source may run on
// its cursor alone before a full List runs as a safety net — catching
// whatever a change feed silently omits. 0 means the default (1 hour);
// negative runs a full pass only when there is no cursor or the source
// rejects the one it has. Ignored for a source that is not Incremental,
// where every pass is already a full List.
FullReconcileInterval time.Duration
// RetryMin and RetryMax bound the per-workspace backoff after a failed
// pass: the delay doubles from RetryMin (default 5s) up to RetryMax
// (default 5m), jittered. A negative RetryMin disables backoff, so every
// trigger attempts. An error carrying RetryAfter overrides both.
RetryMin time.Duration
RetryMax time.Duration
// IngestChunk and IngestPause pace bulk ingress: after every IngestChunk
// engine writes, an ingress pass sleeps IngestPause before continuing.
// Both default to 0, which is off — set both to keep a cold-start import
// of a large account from starving interactive writes behind the
// workspace's write lock. Unchanged items are free; only writes count.
IngestChunk int
IngestPause time.Duration
// OnHealth is called with the workspace's status after every pass,
// successful or not. Persist it, render it, alert on it. It runs on the
// calling goroutine — a worker's, or that of a direct Ingress / Reconcile
// / Drain call — so it must not block for long.
OnHealth func(Health)
// Workspaces enumerates the workspaces Start manages, and is re-read on
// every sweep: a workspace it stops naming is dropped, releasing its
// source and its health. Default: the engine's workspace list —
// sufficient once a workspace has been written, but a source-first
// workspace (data exists only in the external store) must be supplied here
// or nudged with Kick, which manages it regardless of this list.
Workspaces func(ctx context.Context) ([]string, error)
// WriterID names this connector as a collaborative-text writer, and must be
// unique among connectors that can run at the same time — two live writers
// sharing one mint colliding item ids (see applyTextFields). Reusing the
// same value across restarts of a single connector is the point: the peer
// is spelled out in every document it writes to and nothing reclaims it, so
// a per-run identity leaves one dead entry per restart in every document
// the connector has touched. Empty means a fresh identity per instance,
// which is always safe but pays that cost.
//
// It also labels the connector's writes on the change feed, as
// "connect:<WriterID>" — the name an effect or another connector suppresses
// its own echo by. Empty labels them "connect", which is enough to tell a
// connector's write from a GC pass but not one connector from another.
WriterID string
// Logger is the structured logger the background loops write to. Loop
// failures are logged (never returned — convergence work must not take the
// process down) with "component" and "workspace" attributes. nil means
// slog.Default(); a discard-handler logger silences the connector.
Logger *slog.Logger
// TracerProvider and MeterProvider are the OpenTelemetry providers the
// connector records on. nil means the global provider, which is no-op until
// the process installs an SDK — the same fallback Logger makes to
// slog.Default().
//
// Per-workspace health is deliberately NOT a metric (workspace is an
// unbounded partition key); use OnHealth or HealthAll for that. What these
// carry is the aggregate: pass rate, pass duration, and the failure-kind
// split. See docs/reference/telemetry.md.
TracerProvider trace.TracerProvider
MeterProvider metric.MeterProvider
}
Config wires a Connector to a server and a source.
type Connector ¶
type Connector struct {
// contains filtered or unexported fields
}
Connector keeps the engine and one external source converged. Build one with New, then drive it manually (Ingress, Reconcile, Drain) or via Start.
A started connector holds a fixed pool of workers, one activity subscription, one sweep timer, and a small record per managed workspace — not a loop per workspace. What runs at once is Config.Workers; what is remembered is the workspaces Config.Workspaces names plus the ones Kick announced, since everything durable about a workspace's progress lives in State. Tracked reports that set.
func (*Connector) Close ¶
Close stops the workers and the loops Start launched, waiting for in-flight passes to finish, closes any per-workspace sources it opened, and releases the connector's state store. Idempotent.
func (*Connector) Drain ¶
Drain egresses committed engine changes to the source, resuming from the durable cursor and advancing it page by page until the feed is dry. Delivery is at-least-once: a crash between writing the source and persisting bookkeeping redelivers the change, and the shadow makes the redelivery a no-op.
Entities bound IngressOnly are skipped: their changes advance the cursor like any other, they just never reach the source.
func (*Connector) Forget ¶
Forget drops the workspace from the managed set and releases its source — the teardown half of Config.OpenSource, for when a user disconnects an account. A pass in flight for it is cancelled. Shadows and cursors are left in place, so reconnecting resumes rather than re-imports; drop them separately if the data should not survive.
A workspace Config.Workspaces still lists comes back on the next sweep with a freshly opened source, which is what makes this the right call after revoking a credential too. Exclude it from Config.Workspaces to keep it gone — a sweep drops what that list no longer names, so with the default list a workspace that disappears from the engine needs no Forget at all.
func (*Connector) Health ¶
Health returns the workspace's last known status. The bool is false when the connector has never run a pass for it.
func (*Connector) HealthAll ¶
HealthAll returns every workspace the connector has run a pass for, ordered by workspace id.
func (*Connector) Ingress ¶
Ingress runs one source→engine pass: incremental when the source implements Incremental and its stored cursor is still live, a full Reconcile otherwise. It is the entry point a runner uses, and the one to call by hand for a source that reports its own changes; Reconcile remains available for forcing the full enumeration.
For a source that is not Incremental this is exactly Reconcile.
func (*Connector) Kick ¶
Kick schedules a near-immediate ingress+drain for the workspace, coalescing with one already pending. Wire external change hints here — fsnotify watchers, database triggers, webhooks. Kicking a workspace the engine has never seen brings it into the managed set, so source-first workspaces can announce themselves; a sweep will not drop one again, since Config.Workspaces does not name it.
func (*Connector) Reconcile ¶
Reconcile runs one full convergence pass for the workspace: it scans the source, ingresses every change made there since the last sync (field- precisely, so concurrent client edits to other fields survive), tombstones rows deleted at the source, and repairs any bookkeeping a crash left stale. Unchanged items cost one fingerprint compare.
The first Reconcile over an empty shadow set is the initial import: every source item flows into the engine, and the engine's pre-existing rows flow out on the next Drain.
An Incremental source normally reaches this through Ingress, which runs it only when there is no live cursor or the safety-net interval is due. Calling it directly forces the enumeration but takes no checkpoint, so a change racing the scan is caught by the next incremental pass rather than stepped over.
func (*Connector) Start ¶
Start launches the connector's background loops and returns. Close (or cancelling ctx) stops everything.
Work reaches a workspace three ways: the activity stream drains it as soon as the engine commits to it, a sweep discovers workspaces and runs the periodic ingress+drain pass (Config.ReconcileInterval), and Kick is the manual nudge. All three feed one queue drained by a fixed pool of workers (Config.Workers), which is what keeps a fleet of workspaces from arriving at one rate-limited source together.
Errors inside the workers are logged and retried on the next trigger — convergence work must never take the process down. A workspace whose pass failed backs off (Config.RetryMin/RetryMax), coalescing everything that arrives inside the window into one deferred pass, and reports why through Health.
type Deletion ¶
type Deletion struct {
// Prototype is any message of the entity type, as in Writer.Delete.
Prototype proto.Message
// Key is the engine row key.
Key string
}
Deletion is one item the source no longer holds.
type Delta ¶
type Delta struct {
Items []Item
// Deletions are applied after Items. A source that must interleave the two
// (a delete that precedes a recreate under the same key) splits the work
// across pages with More.
Deletions []Deletion
// NextCursor is the position to resume from. It is persisted only after
// this page has been applied.
NextCursor string
// More reports that another page is ready now: the connector loops
// immediately instead of waiting for the next tick.
More bool
}
Delta is one page of source changes.
type Direction ¶
type Direction int
Direction declares which way an entity's changes flow.
const ( // Bidirectional converges the entity both ways: source edits ingress into // the engine and engine commits egress back out. The default, and what // requires the source to implement Writer. Bidirectional Direction = iota // IngressOnly mirrors the source into the engine and never writes back. // Every egress path skips the entity, so client edits to it stay local to // the engine — and are overwritten field-by-field whenever the source // changes the same field (see the shadow-base note on Shadow.BaseText). IngressOnly )
type FailureKind ¶
type FailureKind int
FailureKind buckets why a workspace's last pass failed. The distinction that matters to a product is "wait" versus "ask the user": a network blip heals on its own, an expired token never does.
const ( // FailureNone is the zero value: the last pass succeeded. FailureNone FailureKind = iota // FailureTransient is anything unclassified — network errors, 5xx, // timeouts, rate limits. Retried with backoff. FailureTransient // FailureUserAction is a failure wrapping ErrNeedsUserAction: the account // needs re-consent, a new token, reconnecting. Still retried (the user may // fix it at any moment), but a product should surface it. FailureUserAction )
func (FailureKind) String ¶
func (k FailureKind) String() string
type Health ¶
type Health struct {
WorkspaceID string
// LastAttempt is when the most recent pass ran; zero if none has.
LastAttempt time.Time
// LastSuccess is when a pass last completed without error; zero if never.
LastSuccess time.Time
// LastError is the most recent failure, cleared to nil by any success.
LastError error
// Kind classifies LastError.
Kind FailureKind
// ConsecutiveFailures counts failures since the last success, and is the
// backoff exponent.
ConsecutiveFailures int
// NextAttempt is the earliest time the runner will retry this workspace.
// Zero when not backing off — after a success, or when backoff is
// disabled (Config.RetryMin < 0). Direct calls to Ingress, Reconcile and
// Drain ignore it: the caller asked.
NextAttempt time.Time
}
Health is one workspace's sync status, as of its last pass. Convergence failures are logged and never returned from the background loops — the process must not fall over because one account's token expired — so this is the surface a product renders and alerts on instead.
type Incremental ¶
type Incremental interface {
// Checkpoint returns an opaque cursor for the source's position *now*. It
// is taken BEFORE a full List so that changes racing that list are
// redelivered by the following Changes call rather than lost between the
// two.
Checkpoint(ctx context.Context, workspaceID string) (cursor string, err error)
// Changes returns everything that changed since cursor. Returning an error
// that wraps ErrCursorInvalid — UIDVALIDITY bumped, the history window
// expired, the cursor came from a store that has since been rebuilt —
// forces a fresh Checkpoint and a full List in the same pass.
Changes(ctx context.Context, workspaceID, cursor string) (Delta, error)
}
Incremental is implemented by sources with a native change cursor (Gmail historyId, IMAP HIGHESTMODSEQ, CalDAV sync-token). Connector.Ingress then polls Changes instead of re-enumerating the store, and List becomes the periodic safety net (Config.FullReconcileInterval) rather than the primary ingress path.
Delivery stays at-least-once: the connector persists NextCursor only after the page it came with has been applied, so a crash in between redelivers that page. Both halves are idempotent — an item whose fingerprint matches the shadow is a no-op, and a deletion whose row is already gone writes no second tombstone.
type Item ¶
type Item struct {
Msg proto.Message
// Fingerprint is a cheap stamp of the source's content for this item — a
// content hash, mtime+size, a DB rowversion. Equal content MUST yield
// equal fingerprints between List and Write: fingerprint equality is how
// the connector tells its own echoed writes apart from real concurrent
// edits.
Fingerprint string
// TextFields carries the plain-string values of the entity's
// collaborative-text fields ((syncplane.v1.field_behavior).text), keyed by
// top-level proto field name. A source cannot fabricate the encoded
// document (it has no CRDT history), so it reports the text it holds and
// the connector applies it as a minimal diff onto the engine's current
// document — an external edit then MERGES with concurrent client edits
// instead of clobbering them. Leave the field bytes unset on Msg; the
// connector fills them. Egress renders the document back to a string via
// PlainTextField.
TextFields map[string]string
}
Item is one record of the external store, decoded into a registered entity message.
type Shadow ¶
type Shadow struct {
SourceFP string
EngineVersion uint64
Base []byte
// BaseText is the plain text the source last reported, per collaborative-
// text field. Those fields carry no comparable bytes on an Item (a source
// holds strings, not CRDT documents), so this is what ingress diffs a
// reported string against.
//
// For a Bidirectional row it is the rendering of Base's documents, because
// ingress writes the merge back and both sides genuinely agree. For an
// IngressOnly row the two legitimately diverge — Base is the SOURCE's view
// of the row rather than the merged engine row, and its text fields are
// empty — so this is the only record of what the source last showed. Nil
// on shadows written before this field existed, where the fallback is to
// decode Base.
BaseText map[string]string
}
Shadow records what both sides of one row looked like the last time they were known equal. It is the connector's loop-breaker and merge ancestor:
- EngineVersion lets egress skip changes the connector itself ingressed (change seq <= EngineVersion means "that was us").
- SourceFP lets ingress skip source content the connector itself wrote (fingerprint equality means "unchanged, or our own echo").
- Base is the entity bytes of the last-synced state — the three-way ancestor that lets ingress apply only the fields the source actually changed.
type Source ¶
type Source interface {
// List streams every item of every bound entity in the workspace, in any
// order. Used by reconcile and initial sync.
List(ctx context.Context, workspaceID string, fn func(Item) error) error
}
Source is the minimum port an adopter implements over their store: read everything. A source that is also written back to implements Writer, and one with a native change cursor implements Incremental; the connector type-asserts for both.
Identity mapping is the port's job: List decodes native records into entity messages (populating the key fields), and Writer's methods derive their native key from the message / engine key they are handed.
Every method takes workspaceID even when Config.OpenSource already mints one instance per workspace, so a single implementation can serve both wirings.
type SourceSync ¶
type SourceSync struct {
// Cursor is the opaque position last reported by Incremental (Checkpoint
// before a full pass, NextCursor after each applied page). Empty means the
// workspace has never synced incrementally, which forces a full pass.
Cursor string
// LastFullSync is when List last enumerated the whole source; zero means
// never. Config.FullReconcileInterval measures from here.
LastFullSync time.Time
}
SourceSync is the connector's ingress bookkeeping for one workspace: how far an Incremental source's change feed has been consumed, and when a full enumeration last ran.
type State ¶
type State interface {
// Shadow returns the shadow for a row, or nil if none is recorded.
Shadow(ctx context.Context, workspaceID, entity, key string) (*Shadow, error)
PutShadow(ctx context.Context, workspaceID, entity, key string, s Shadow) error
DeleteShadow(ctx context.Context, workspaceID, entity, key string) error
// ScanShadows yields every shadow of the workspace. Used by reconcile to
// detect rows deleted at the source.
ScanShadows(ctx context.Context, workspaceID string, fn func(entity, key string, s Shadow) error) error
// Cursor returns the egress position (zero Cursor if never set).
Cursor(ctx context.Context, workspaceID string) (server.Cursor, error)
SetCursor(ctx context.Context, workspaceID string, c server.Cursor) error
// SourceSync returns the ingress position (zero SourceSync if never set).
SourceSync(ctx context.Context, workspaceID string) (SourceSync, error)
SetSourceSync(ctx context.Context, workspaceID string, s SourceSync) error
Close() error
}
State is the connector's durable bookkeeping: shadows, the egress cursor into the change feed, and the source's ingress position. It is a cache, not a ledger — losing it costs a full reconcile (content comparison, idempotent writes), never data.
Implementations need no cross-row transactionality; the connector orders its writes so that any crash between two State calls is healed by redelivery or reconcile. The shipped default is sqlitestate.
type Writer ¶
type Writer interface {
// Write upserts engine state into the source and returns the resulting
// fingerprint (observed after the write, so store-stamped versions are
// captured).
Write(ctx context.Context, workspaceID string, msg proto.Message) (fingerprint string, err error)
// Delete removes the item identified by the entity prototype's type and
// the engine row key. Deleting a missing item is a no-op.
Delete(ctx context.Context, workspaceID string, prototype proto.Message, key string) error
}
Writer is implemented by sources the connector may write back to. It is required only when some entity is bound Bidirectional — which is the default, so a read-only source must declare its entities IngressOnly (Config.Bindings) to be allowed to omit it.
The connector delivers at-least-once: Write MUST be an idempotent upsert and Delete MUST treat a missing item as a no-op.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package sqlitestate implements connect.State on SQLite via modernc.org/sqlite (pure Go, no CGO) — the shipped default for connector bookkeeping.
|
Package sqlitestate implements connect.State on SQLite via modernc.org/sqlite (pure Go, no CGO) — the shipped default for connector bookkeeping. |