connect

package
v0.10.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 20, 2026 License: MIT Imports: 28 Imported by: 0

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.

Record mode

With Config.Records the connector runs in record mode instead: one external record, such as a file, syncs with a root row and its member rows. The adopter implements a RecordStore for the native I/O and a Codec that maps a record to rows and back; the connector owns the scheduling, the bookkeeping, the quiet period before a write, the delete grace, rename detection and the first pass. See Records.

Single instance

Nothing leases a workspace to one connector, and in row mode 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. In record mode it is in the engine's store, but nothing keeps two instances from writing the same record. 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

Examples

Constants

This section is empty.

Variables

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

View Source
var ErrRecordNotFound = errors.New("connect: record not found")

ErrRecordNotFound is the error a RecordStore wraps when a record does not exist.

Functions

func MatchKeys added in v0.9.0

func MatchKeys[P comparable](prev []P, prevKeys []string, next []P) []string

MatchKeys gives the parts of next the keys of the parts of prev they continue, for content whose parts carry no key in the store, such as the lines of a text file. prevKeys[i] is the key of prev[i].

A part of next that is equal to a part of prev in a longest common subsequence of the two takes its key. Between two such pairs, the parts of next take the keys of the parts of prev in order, so that an edited part keeps its key. A part with no key gets "": give it a new key. When the keys in prevKeys are distinct, each key goes to one part at most.

MatchKeys panics when prev and prevKeys differ in length. It takes memory in proportion to len(prev)+len(next), and time in proportion to that sum times the number of parts inserted and deleted.

func PlainTextField

func PlainTextField(msg proto.Message, field string) (string, error)

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

func RetryAfter(err error, d time.Duration) error

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 Agreed added in v0.9.0

type Agreed struct {
	Locator     string
	Fingerprint string
	Payload     []byte
}

Agreed is the state of a record that the store and the engine last agreed on.

type Binding

type Binding struct {
	Prototype proto.Message
	Direction Direction
	// Fields names the fields the source owns, by top-level proto field name,
	// or by oneof name for a whole oneof group. Ingest takes only these fields
	// from an Item, in Msg and in TextFields, and every other field keeps its
	// engine value: a new row starts with them empty, and an existing row
	// keeps a field that another writer computes and the source cannot hold.
	// Egress writes the whole row to the source, but only for a change to an
	// owned field. A text field compares by its visible string.
	//
	// The key fields are always owned. Empty means every field. New returns an
	// error for a name the entity does not declare, and for a member of a
	// oneof.
	Fields []string
}

Binding declares one entity, the direction it syncs in, and the fields the source owns. Config.Entities is the shorthand for Bidirectional bindings that own every field.

type Codec added in v0.9.0

type Codec interface {
	// Merge applies a store record to the rows of the record with key
	// in.Key, through tx. With a base, it applies the changes from the base
	// to the record, and keeps engine edits the record did not change. With
	// no base, the record is new to the connector, and Merge makes the rows
	// equal to it.
	//
	// A replay of a merge that committed, with the old base, must write
	// nothing. Write a row only when it changes.
	Merge(tx *server.EntityTx, in MergeInput) (Merged, error)
	// Render returns the record's native form from its rows. ok false means
	// the record has no native form, and the connector deletes it from the
	// store. Render can write rows, for example to give new rows a key the
	// native form holds.
	Render(tx *server.EntityTx, in RenderInput) (out Rendered, ok bool, err error)
}

Codec maps the records of one record type to rows and back. Its methods run inside a trusted write transaction, under the workspace write lock, so keep them free of I/O. The transaction can roll back and run again, also when another record merged in it fails, so the methods must have no effect outside tx. Render must give the same content for the same rows: the connector writes each render whose content differs from the store's. A Codec is shared by all workspaces and must be safe for concurrent use.

An error from Merge or Render rolls back the transaction: no row and no shadow of the record changes. The connector logs the error, lists the record in Health.Refused, skips it, and tries it again when it next sees a change of it. In a first pass, a refused record can fail the pass instead; see FirstPass.

type Config

type Config struct {
	// Server is the engine the connector ingresses into (server.Mutate) and
	// egresses out of (server.Changes).
	Server *server.Server
	// Records switches the connector to record mode, where one external
	// record syncs with a root row and its member rows; see Records. It
	// cannot be used with Source, OpenSource, Entities, Bindings or State,
	// and it requires WriterID: all its bookkeeping is in the engine's store.
	Records *Records
	// Source is the adopter's port over the external store, shared by every
	// workspace. Exactly one of Source and OpenSource is required, except in
	// record mode.
	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,
	// except in record mode.
	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, where the source owns every field. 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, or whose
	// source owns only some fields. 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. It labels the connector's writes on the
	// change feed as "connect:<WriterID>", the name an effect or another
	// connector suppresses its echo by. Give each instance of one connector the
	// same WriterID, also an origin and its replicas, so that one constant
	// skips the writes of all of them. Empty labels the writes "connect", which
	// tells a connector's write from a GC pass but not one connector from
	// another.
	//
	// With a WriterID, the connector also records how far it has egressed in
	// the engine's store, as the consumer position of "connect:<WriterID>".
	// That copy outlives a lost State: a row the engine changed after it is a
	// client edit the source has not received, and the next pass sends it to
	// the source instead of taking the source's older value. Without a
	// WriterID, a lost State loses such edits (see State).
	//
	// When TextPeer is empty, WriterID also sets the collaborative-text peer,
	// as "connector:<WriterID>"; see TextPeer.
	WriterID string
	// TextPeer is the collaborative-text writer identity the connector mints
	// text items under, used as given with no prefix. Two connectors that can
	// write the same rows at the same time, such as an origin and its replicas,
	// must have different peers, because two live writers that share a peer
	// mint colliding item ids. Keep the same value across restarts of one
	// instance: a document keeps an entry for each peer that wrote to it and
	// nothing removes it, so a peer per run adds one dead entry per restart to
	// each document the connector wrote.
	//
	// Empty means "connector:<WriterID>", or a new peer for each instance when
	// WriterID is empty too, which is safe but pays the cost of a peer per run.
	TextPeer 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 store converged: a Source in row mode, the record stores of Config.Records in record mode. Build one with New, then drive it manually (Ingress, Reconcile, Drain, Flush) or via Start. Its methods are safe for concurrent use; passes for one workspace never overlap.

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, or in the engine's store in record mode. Tracked reports that set.

func New

func New(cfg Config) (*Connector, error)

New validates cfg and builds a Connector.

func (*Connector) Close

func (c *Connector) Close() error

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.

In record mode Close first flushes each workspace whose records wait for egress, or whose last pass failed (see Flush), for at most one minute each, and returns the errors of those flushes with the rest.

func (*Connector) Drain

func (c *Connector) Drain(ctx context.Context, workspaceID string) error

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.

In record mode Drain marks the records that the feed reports changed, and writes those whose last change is at least Records.Quiet old, or whose first unwritten change is at least Records.MaxDelay old. Before a write it reads the store record, and when its fingerprint or its content changed since the last agreed state, it ingests the record first, so the store edit stays. It also deletes the rows of records whose delete grace is over.

func (*Connector) Flush added in v0.9.0

func (c *Connector) Flush(ctx context.Context, workspaceID string) error

Flush writes the pending egress of the workspace now. In record mode it drains the feed and writes every record that waits for egress, also those whose quiet period is not over; for a workspace that has had no first pass it does nothing. In row mode it is Drain. Close and Forget flush in record mode.

func (*Connector) Forget

func (c *Connector) Forget(workspaceID string)

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.

In record mode Forget first flushes the workspace (see Flush), for at most one minute, so the edits that wait out the quiet period reach the store; a flush error is logged.

func (*Connector) Health

func (c *Connector) Health(workspaceID string) (Health, bool)

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

func (c *Connector) HealthAll() []Health

HealthAll returns every workspace the connector has run a pass for, ordered by workspace id.

func (*Connector) Ingress

func (c *Connector) Ingress(ctx context.Context, workspaceID string) error

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.

In record mode Ingress ingests the locators Touch reported, and deletes the rows of records whose delete grace is over. It does not list the store.

func (*Connector) Kick

func (c *Connector) Kick(workspaceID string)

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

func (c *Connector) Reconcile(ctx context.Context, workspaceID string) error

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.

In record mode Reconcile lists every record of every type: it ingests the records whose fingerprint changed and the new ones, marks the missing ones for delete after Records.DeleteGrace, and deletes the rows of records whose grace is over. A record whose content the engine also changed is written back to the store when the merge kept engine edits.

func (*Connector) Refused added in v0.9.0

func (c *Connector) Refused(ctx context.Context, workspaceID string, rows []RowRef) error

Refused reports rows whose write the host could not keep and reverted, such as writes of this connector that an origin server refused. On a replica, call it from upstream.Config.OnRejected, as the example shows.

The connector marks the record of each row, durably, and schedules a pass. The next egress of a marked record gives the store content it replaces or deletes to Records.Overwrite with OverwriteRefused first, so that a store edit the engine did not keep is not lost without a trace. When egress wrote the record before the call, the content it replaced is given instead, if Records.KeepReplaced kept it; else nothing is given. One refusal can give two contents: the one egress replaced, when it was kept, and the one the store holds. A mark is cleared after use, and after a pass that finds its record written and no kept content. A call that comes while a pass uses an earlier mark of the record makes a mark of its own, which the next pass uses.

Rows of entities outside record mode, of types that are not Bidirectional, and rows no record holds are ignored. Calling it more than once for one refusal is safe. Refused is safe for concurrent use. It returns an error in row mode and when the engine's store fails; nothing is marked then.

Example

A replica hands the rows of each write the origin refused to its record-mode connector.

package main

import (
	"context"
	"log/slog"

	engineconnect "github.com/levelfourab/syncplane/engine/connect"
	"github.com/levelfourab/syncplane/engine/upstream"
)

func main() {
	var conn *engineconnect.Connector // the record-mode connector of the replica

	cfg := upstream.Config{
		OnRejected: func(r upstream.Rejection) {
			rows := make([]engineconnect.RowRef, len(r.Rows))
			for i, row := range r.Rows {
				rows[i] = engineconnect.RowRef(row)
			}
			if err := conn.Refused(context.Background(), r.Workspace, rows); err != nil {
				slog.Error("mark refused records", "workspace", r.Workspace, "err", err)
			}
		},
	}
	_ = cfg
}

func (*Connector) Start

func (c *Connector) Start(ctx context.Context) error

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.

func (*Connector) Touch added in v0.9.0

func (c *Connector) Touch(workspaceID string, locators ...string)

Touch reports that the store records at locators changed, and schedules a near-immediate pass that ingests them, coalescing with one already pending. Wire native change events here, such as fsnotify. A periodic pass still lists the whole store (Config.ReconcileInterval), which catches what the events miss. Like Kick, it brings a workspace the connector does not manage into the managed set.

The locators are held in memory until a pass ingests them; Ingress ingests them on a connector that is not started. A locator of no record type is ignored. A new locator whose fingerprint is that of a record the store no longer holds is a rename of that record, in whatever order and in however many calls the two locators arrive. In row mode Touch is Kick and ignores the locators.

func (*Connector) Tracked

func (c *Connector) Tracked() int

Tracked reports how many workspaces the connector is holding state for. It is the managed set — what discovery found plus what Kick announced — and is what the resident cost of a running connector is proportional to.

type DecodeInput added in v0.9.0

type DecodeInput struct {
	// Key is the record key. A root row with an empty key gets it.
	Key    string
	Record Record
	// Base holds the rows as the store held them when the store and the
	// engine last agreed. Base.Root is nil when there is no agreed state.
	// Match the parts of the content to these rows to give each part the key
	// of its row; see MatchKeys. When the connector cannot tell whether its
	// last store write was done (see MergeInput.Alternate), Base holds the
	// rows before or after that write, whichever Encode makes into content
	// nearer Record.Content.
	Base RecordRows
	// Rows holds the rows of the record in the engine now. A member row here
	// that Base does not hold is a row a client added, or a row an earlier
	// merge of this same content wrote: give a part the key of such a row
	// when they are equal, so that a repeated merge writes nothing.
	Rows RecordRows
	// Payload is the adopter's data of the agreed state, from
	// Decoded.Payload or from the Rendered.Payload of Encode; nil when there
	// is none.
	Payload []byte
}

DecodeInput is the input of RowCodec.Decode. The rows are read in the merge transaction and are not retained after Decode returns; Decode must not change them. Their collaborative-text fields hold documents: read them with PlainTextField.

type Decoded added in v0.9.0

type Decoded struct {
	// Root is the root row. It is required. An empty key gets the record key
	// when the root entity has one string key field; any other key must be the
	// record key.
	Root proto.Message
	// Members are the member rows, with their keys set. A member whose
	// Member.RecordField is empty gets the record key; one that names another
	// record refuses the record.
	Members []proto.Message
	// Payload is the adopter's data for this content, given back as
	// DecodeInput.Payload and EncodeInput.Payload.
	Payload []byte
	// contains filtered or unexported fields
}

Decoded is the result of RowCodec.Decode. The connector can change the messages.

func (*Decoded) SetText added in v0.9.0

func (d *Decoded) SetText(row proto.Message, field, value string)

SetText gives the collaborative-text field of row, a message in Root or Members, the visible text value. field is the top-level proto field name. A text field the record owns and that SetText does not set is empty in the record. Leave the bytes of a text field unset on the message: the connector merges value into the engine's document.

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
	// EgressOnly writes engine rows to the store and never takes a store edit
	// into the engine. Only a record type can be EgressOnly (see
	// RecordType.Direction); New refuses it on a Binding.
	EgressOnly
)

type EncodeInput added in v0.9.0

type EncodeInput struct {
	Key string
	// Locator is the locator of the agreed state; empty when the store does
	// not hold the record yet, and Encode must then return one.
	Locator string
	// Payload is the adopter's data of the agreed state, as in DecodeInput.
	Payload []byte
	// Rows are the rows of the record. Rows.Root is not nil. Render a
	// collaborative-text field with PlainTextField.
	Rows RecordRows
}

EncodeInput is the input of RowCodec.Encode. The rows are read in the transaction and are not retained after Encode returns; Encode must not change them.

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 FirstPass added in v0.9.0

type FirstPass int

FirstPass is the policy of the first pass of a workspace in record mode. Records.FirstPass sets it for every workspace, and Records.ChooseFirstPass for each workspace.

The first pass runs when the consumer "connect:<WriterID>" has no position in the workspace: on the first sync, and after server.ResetConsumer. A connector that did not run for longer than the tombstone retention (see server.WithGC) keeps its position and marks every record for egress; it does not run the first pass again.

const (
	// SourceWins imports the store: each record is merged with no base, and
	// root rows and member rows that no store record holds are deleted. When
	// the codec refuses a record, the pass fails and deletes no row.
	SourceWins FirstPass = iota
	// EngineWins rebuilds the store from the rows: each root row is rendered
	// and written to the store, and Records.Overwrite gets each store record
	// it replaces with other content. A store record with no rows is ingested
	// as a new record. No row is deleted. When the codec cannot render a root
	// row, the pass fails before it ingests a store record.
	EngineWins
)

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
	// Refused lists, in record mode, the records the connector skips and
	// tries again: the codec refused them, or their locator belongs to
	// another record. A skipped record does not fail the pass. Ordered by
	// Entity, Locator and Key. A record leaves the list when it syncs, when
	// a full list no longer finds it in the store, or when it is deleted. A
	// new Connector starts with an empty list.
	Refused []RecordFailure
}

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 Member added in v0.9.0

type Member struct {
	// Prototype is a prototype of the member entity.
	Prototype proto.Message
	// RecordField is the dotted path of the singular string field that holds
	// the key of the record's root row, such as "page_id", or "page.id" for a
	// reference. The connector finds the members of a record with a query on
	// this field, so declare an index on it for records with many rows.
	RecordField string
}

Member is one member entity of a record type.

type MergeInput added in v0.9.0

type MergeInput struct {
	// Key is the record key: the key of the root row the record merges into.
	Key    string
	Record Record
	// Base is the state the store and the engine last agreed on; nil when the
	// connector has no shadow of the record.
	Base *Agreed
	// Alternate is set when the connector wrote the record to the store
	// after Base, and cannot tell whether the write was done before the
	// store changed the record again: it is the state that write would have
	// agreed on. The store's content continues Base or Alternate. A Merge
	// that ignores it merges against Base, and then applies the engine edits
	// of a write that was done a second time; collaborative text holds them
	// twice. Nil when there is no such write.
	Alternate *Agreed
	// Root is the root row; nil when there is none.
	Root proto.Message
	// Members are the member rows of the record, of each member entity in
	// the order of RecordType.Members, in key order.
	Members []proto.Message
	// TextPeer is the collaborative-text peer to write text under, for
	// example with server.ApplyTextStrings. See Config.TextPeer.
	TextPeer string
	// TextClock is the highest text counter the record's rows have held,
	// also in text the host reverted since (see Connector.Refused); 0 for
	// none. Text written under TextPeer must take counters above it, or an
	// item can get the id of a reverted item that a client still holds:
	// decode the document with text.Decode under TextPeer and call
	// ObserveVersion(map[string]uint64{TextPeer: TextClock}) before the
	// edit. server.ApplyTextStrings observes only the documents it is given.
	TextClock uint64
	// contains filtered or unexported fields
}

MergeInput is the input of Codec.Merge. The messages are rows read in the transaction; Merge must not change them.

type Merged added in v0.9.0

type Merged struct {
	// Key is the key of the root row the record merged into, when Merge
	// matched a new record to an existing root row with another key. Empty
	// keeps MergeInput.Key. A record with a base cannot change its key.
	Key string
	// Payload is the codec's data for the agreed state, such as the row key
	// of each part of the record. The connector stores it with the shadow and
	// gives it back as Agreed.Payload.
	Payload []byte
	// contains filtered or unexported fields
}

Merged is the result of Codec.Merge.

type Overwrite added in v0.9.0

type Overwrite struct {
	WorkspaceID string
	// Entity is the root entity of the record type.
	Entity  string
	Key     string
	Locator string
	Reason  OverwriteReason
	// Old is the content the store holds now, New the content that replaces
	// it; New is nil when egress deletes the record.
	Old []byte
	New []byte
}

Overwrite describes a store record that an egress write is about to replace or delete. Old and New are not retained after the call returns.

type OverwriteReason added in v0.9.0

type OverwriteReason int

OverwriteReason tells why egress replaces store content that holds edits the engine does not have.

const (
	// OverwriteFirstPass is a first pass with EngineWins that replaces a
	// store record with other content.
	OverwriteFirstPass OverwriteReason = iota + 1
	// OverwriteEgressOnly is a record of an EgressOnly type whose store
	// content changed since the connector wrote it.
	OverwriteEgressOnly
	// OverwriteRefused is a record of rows that Connector.Refused reported.
	// Old can be content an earlier egress replaced; New is then the content
	// the store holds now, which can hold store edits made after that
	// egress, and is nil when the store holds no record there.
	OverwriteRefused
)

func (OverwriteReason) String added in v0.9.0

func (r OverwriteReason) String() string

String returns "first_pass", "egress_only" or "refused", and "unknown" for any other value.

type Record added in v0.9.0

type Record struct {
	RecordRef
	Content []byte
}

Record is one record and its content.

type RecordFailure added in v0.9.0

type RecordFailure struct {
	// Entity is the root entity of the record type.
	Entity string
	// Key is the record key; empty for a store record new to the connector.
	Key string
	// Locator is where the store holds the record; empty for an engine
	// record the store does not hold yet.
	Locator string
	// Err is the error of the latest attempt.
	Err error
	// Failures counts the attempts that failed since the record last
	// synced.
	Failures int
}

RecordFailure is one record in Health.Refused.

type RecordRef added in v0.9.0

type RecordRef struct {
	// Key is the record key, when the store knows it, such as an id the
	// content holds. The connector uses it for a locator it does not know
	// yet, so that a record the store moved keeps its key; a locator it
	// knows keeps the key of its record. Empty finds the key of a renamed
	// record by Fingerprint, or gives a new record a new key.
	Key     string
	Locator string
	// Fingerprint is a stamp of the content, such as a content hash. Equal
	// content must give an equal fingerprint, in List, Read and Write: it is
	// how the connector tells its own writes from edits. A content hash also
	// lets the connector find a renamed record by its content.
	Fingerprint string
}

RecordRef addresses one record in a store.

type RecordRows added in v0.9.0

type RecordRows struct {
	// Root is the root row; nil when there is none.
	Root proto.Message
	// Members are the member rows. In DecodeInput.Rows and EncodeInput.Rows
	// they are in the order of RecordType.Members, and in key order within
	// one entity. In DecodeInput.Base they are in no fixed order.
	Members []proto.Message
}

RecordRows are the root row and the member rows of one record.

type RecordStore added in v0.9.0

type RecordStore interface {
	// List yields each record of the type in the workspace, in any order. It
	// must be cheap: the connector reads the content only of the records
	// whose fingerprint changed.
	List(ctx context.Context, workspaceID string, fn func(RecordRef) error) error
	// Read returns the record at locator. It returns an error that wraps
	// ErrRecordNotFound when there is none, also for a locator of another
	// record type.
	Read(ctx context.Context, workspaceID, locator string) (Record, error)
	// Write puts rec.Content at rec.Locator, replacing what is there, and
	// returns the fingerprint of the content as stored. from is the old
	// locator when the record moved, which the store removes; else from is
	// empty.
	Write(ctx context.Context, workspaceID string, rec Record, from string) (fingerprint string, err error)
	// Delete removes the record at locator. Removing a missing record is not
	// an error.
	Delete(ctx context.Context, workspaceID, locator string) error
}

RecordStore is the adopter's port over the records of one record type. The connector delivers at least once, so each method must be idempotent. Every method takes the workspace id, so one store set as RecordType.Store serves all workspaces; a store RecordType.OpenStore returns gets only the id of its own workspace. The connector calls the methods of one workspace from one goroutine at a time, but calls for different workspaces can run at the same time.

type RecordType added in v0.9.0

type RecordType struct {
	// Root is a prototype of the root entity. Its row key is the record key.
	Root proto.Message
	// Members are the entities whose rows belong to a record. A type with no
	// members syncs one row as one record.
	Members []Member
	// Store reads and writes the records of every workspace. Exactly one of
	// Store and OpenStore is required.
	Store RecordStore
	// OpenStore builds the store of one workspace, such as one that watches
	// a folder for each workspace. It is called on the workspace's first
	// pass, and the store is reused by the passes after it. When the store
	// implements io.Closer, it is closed once the connector is done with it:
	// on Close, on Forget, and after a pass that fails with
	// ErrNeedsUserAction. An error fails the pass, and the next pass calls
	// OpenStore again.
	OpenStore func(ctx context.Context, workspaceID string) (RecordStore, error)
	// Codec maps records to rows and rows to records.
	Codec Codec
	// Direction is Bidirectional (the default), IngressOnly or EgressOnly.
	//
	// An IngressOnly type never writes to the store: engine edits stay in the
	// engine, and ingest does not render the record.
	//
	// An EgressOnly type never writes a row: the engine is the only source of
	// its records. A store edit of one of its records is not merged; the
	// next pass that sees it, or egresses the record, writes the engine's
	// render over it, after a call to Records.Overwrite with the store's
	// content. A record the store deleted is written again and keeps its
	// rows. A store record no root row renders to is left in the store. The
	// first pass writes every root row to the store, whatever the
	// FirstPass policy is.
	Direction Direction
}

RecordType binds one root entity and its member entities to a store and a codec.

type Records added in v0.9.0

type Records struct {
	// Types are the record types. Each entity can be the root or a member of
	// one type only.
	Types []RecordType
	// FirstPass decides which side wins when a workspace has no record-mode
	// bookkeeping yet. The zero value is SourceWins.
	FirstPass FirstPass
	// ChooseFirstPass, when set, decides the policy for one workspace and
	// overrides FirstPass. It is called at the start of each first pass of
	// the workspace, also again after a first pass that failed, and never on
	// a later pass. It can be called for different workspaces at the same
	// time. An error, or a value that is not SourceWins or EngineWins, fails
	// the pass before it reads the store or writes a row. Nil uses FirstPass
	// for every workspace.
	ChooseFirstPass func(ctx context.Context, workspaceID string) (FirstPass, error)
	// Quiet is how long a record must have no engine change before egress
	// writes it to the store, so that a run of edits makes one write. 0 means
	// the default (1 second); negative writes at the next pass.
	Quiet time.Duration
	// MaxDelay bounds how long a record waits for egress after its first
	// engine change the store has not received, also while changes keep
	// coming faster than Quiet. 0 means the default (10 × Quiet); negative
	// means no bound. It has no effect when Quiet is negative: records then
	// do not wait.
	MaxDelay time.Duration
	// DeleteGrace is how long a record must be missing from the store before
	// its rows are deleted. A store record that comes back in this time keeps
	// its rows, and a new record with the fingerprint of a missing one is a
	// rename of it. 0 means the default (2 seconds); negative deletes at the
	// end of the pass that found it missing.
	DeleteGrace time.Duration
	// BatchRows bounds the rows that one ingest transaction merges across
	// records, so that the import of many small records takes the workspace
	// write lock for a bounded time. A record with more rows is merged alone.
	// 0 means the default (1000). Config.IngestChunk and Config.IngestPause
	// count these transactions.
	BatchRows int
	// Overwrite is called before egress replaces or deletes store content
	// that holds edits the engine does not have, so that the adopter can
	// keep a copy of it; Overwrite.Reason tells why. An error stops the
	// write and fails the pass. Nil writes without a call.
	//
	// Outside these cases, egress never replaces a store record the
	// connector does not know: it ingests it as a new record, and the engine
	// record whose locator it holds waits until the locator is free.
	Overwrite func(ctx context.Context, o Overwrite) error
	// KeepReplaced is how long the connector keeps the store content that an
	// egress write or delete replaced, when the record had an ingest within
	// this time before. It lets a Connector.Refused call that comes after the
	// egress still give the refused content to Overwrite. The content is kept
	// in the engine's store, one copy for each record at most. 0 keeps
	// nothing.
	KeepReplaced time.Duration
}

Records configures record mode, where one external record syncs with a group of rows: one root row and the member rows that name it. A record is what the external store reads and writes whole, such as a file, a JSON document or an API resource. Set it as Config.Records.

The record key is the key of the root row and does not change. The locator is the record's address in the store, such as a path, and can change on either side.

All bookkeeping is in the engine's store, under the consumer "connect:<WriterID>": the feed position, one shadow for each record, an index from member row to record, an index from locator to record, the records that wait out Quiet, and the records that wait out DeleteGrace. It is backed up and restored with the rows. Garbage collection does not remove it (see server.ConsumerUpdate.Retain); server.ResetConsumer does.

type RenderInput added in v0.9.0

type RenderInput struct {
	Key  string
	Base *Agreed
	// Root is the root row. Render is not called when there is none: the
	// record is then deleted from the store.
	Root proto.Message
	// Members are the member rows, as in MergeInput.
	Members []proto.Message
	// TextPeer and TextClock are as in MergeInput.
	TextPeer  string
	TextClock uint64
}

RenderInput is the input of Codec.Render.

type Rendered added in v0.9.0

type Rendered struct {
	// Locator is where the record goes. Empty keeps the locator of the base;
	// a record with no base must have one.
	Locator string
	Content []byte
	// Payload is the codec's data for this content; see Merged.Payload.
	Payload []byte
}

Rendered is the native form of a record.

type RowCodec added in v0.9.0

type RowCodec struct {
	// Decode returns the rows a record holds. It is required, except for an
	// EgressOnly record type.
	//
	// An error refuses the record: no row changes, and the connector skips
	// the record as for any Codec error.
	Decode func(in DecodeInput) (Decoded, error)
	// Encode returns the content of a record from its rows. It is required,
	// except for an IngressOnly record type.
	//
	// The rows that Decode returns for the content must be equal to the rows
	// Encode got, in the fields the record owns: the connector takes them as
	// what the store holds after the write. An error refuses the record, as
	// for Decode.
	Encode func(in EncodeInput) (Rendered, error)
	// Fields names the fields the record owns, for each entity of the record
	// type, keyed by a prototype of the entity. The names follow
	// Binding.Fields: top-level field names, or a oneof name for a whole oneof
	// group. The key fields and the top-level field of Member.RecordField are
	// always owned. An entity with no entry owns every field.
	//
	// A field Decode cannot read back from the store must not be owned: on
	// the next change of the record, the connector would take its empty value
	// as an edit. New returns an error for a prototype of an entity outside
	// the record type, and for a name the entity does not declare.
	Fields map[proto.Message][]string
}

RowCodec is a Codec for records whose parts map to rows: Decode turns the content of a record into its root row and member rows, and Encode turns the rows back into content. The connector merges the decoded rows into the engine one row at a time, against the rows as the store held them when the two sides last agreed:

  • A field the record changed since then takes the record's value. A field the record did not change keeps the engine's value, also when a client changed it.
  • A collaborative-text field the record changed is merged with the engine's document, so an edit in the store and an edit in the engine both survive, also within one field.
  • A member row that the record held and no longer holds is deleted. A member row that a client added and that the record never held stays, and the next write puts it in the store.
  • A member row that Decode gives to another record by its key moves to that record, with the fields that record does not own and with its text history, when the store changes both records in one pass.
  • With no agreed state, as on the first sync of a record, the rows take the record's values for the fields in Fields, and the member rows the record does not hold are deleted.

Fields the record does not own, see Fields, always keep their engine value.

The agreed state of each record holds a copy of its rows, with their collaborative-text documents, and each ingest and each write of the record writes that copy again: a record's bookkeeping costs about the size of its rows in storage, and that much again in writes on each change.

Use a RowCodec as RecordType.Codec. New validates it against the record type; its Merge and Render methods return an error when called directly. Decode and Encode run inside the merge transaction, under the workspace write lock: keep them free of I/O. They can be called more than once for one change, after the transaction rolls back, and at the same time for different records, so they must have no effect outside the call and be safe for concurrent use. Encode must give the same content for the same rows.

Example

A text file is a record: its first line is the name of a Project, and each further line is a Widget of that project, with the line in the collaborative-text field body and its place in count, an order key that clients can also write. The file cannot hold the other Widget fields, so the codec owns body and count only.

codec := engineconnect.RowCodec{
	Decode: func(in engineconnect.DecodeInput) (engineconnect.Decoded, error) {
		lines := strings.Split(string(in.Record.Content), "\n")
		// A line that stays, also when edited, keeps the key of its row.
		var prev, keys []string
		place := make(map[string]int32)
		for _, w := range byPlace(in.Base.Members) {
			body, err := engineconnect.PlainTextField(w, "body")
			if err != nil {
				return engineconnect.Decoded{}, err
			}
			prev, keys = append(prev, body), append(keys, w.GetId())
			place[w.GetId()] = w.GetCount()
		}
		matched := engineconnect.MatchKeys(prev, keys, lines[1:])
		out := engineconnect.Decoded{Root: &testdatav1.Project{Name: lines[0]}}
		last := int32(-1)
		for i, line := range lines[1:] {
			key := matched[i]
			if key == "" {
				key = id.New()
			}
			// A row keeps its place while it still sorts after the line
			// before it, so that the file gives back the places Encode got.
			count, ok := place[key]
			if !ok || count <= last {
				count = last + 1
			}
			last = count
			w := &testdatav1.Widget{Id: key, Count: count}
			out.Members = append(out.Members, w)
			out.SetText(w, "body", line)
		}
		return out, nil
	},
	Encode: func(in engineconnect.EncodeInput) (engineconnect.Rendered, error) {
		root := in.Rows.Root.(*testdatav1.Project)
		lines := []string{root.GetName()}
		for _, w := range byPlace(in.Rows.Members) {
			body, err := engineconnect.PlainTextField(w, "body")
			if err != nil {
				return engineconnect.Rendered{}, err
			}
			lines = append(lines, body)
		}
		out := engineconnect.Rendered{Content: []byte(strings.Join(lines, "\n"))}
		if in.Locator == "" {
			out.Locator = root.GetName() + ".txt"
		}
		return out, nil
	},
	Fields: map[proto.Message][]string{&testdatav1.Widget{}: {"body", "count"}},
}

ctx := context.Background()
dir, err := os.MkdirTemp("", "rowcodec")
if err != nil {
	panic(err)
}
defer os.RemoveAll(dir)
db, err := sqlitestore.Open(filepath.Join(dir, "engine.db"))
if err != nil {
	panic(err)
}
defer db.Close()
srv, err := server.New(db, server.WithEntities(&testdatav1.Project{}, &testdatav1.Widget{}))
if err != nil {
	panic(err)
}
// files is a RecordStore over the text files of each workspace.
files := newMemStore()
conn, err := engineconnect.New(engineconnect.Config{
	Server:   srv,
	WriterID: "files",
	Records: &engineconnect.Records{
		Quiet: -1,
		Types: []engineconnect.RecordType{{
			Root:    &testdatav1.Project{},
			Members: []engineconnect.Member{{Prototype: &testdatav1.Widget{}, RecordField: "label"}},
			Store:   files,
			Codec:   codec,
		}},
	},
})
if err != nil {
	panic(err)
}
defer conn.Close()

files.put("ws1", "Plan.txt", "Plan\nwrite docs\nship")
if err := conn.Reconcile(ctx, "ws1"); err != nil {
	panic(err)
}

// A client edits a line, and the connector writes the file.
err = srv.Mutate(server.TrustedAs(ctx, "client"), "ws1", func(tx *server.EntityTx) error {
	var ship *testdatav1.Widget
	if err := tx.Scan(&testdatav1.Widget{}, func(msg proto.Message) error {
		if body, _ := engineconnect.PlainTextField(msg, "body"); body == "ship" {
			ship = msg.(*testdatav1.Widget)
		}
		return nil
	}); err != nil {
		return err
	}
	next := proto.Clone(ship).(*testdatav1.Widget)
	if err := server.ApplyTextStrings(next, nil, ship, map[string]string{"body": "ship it"}, "client-1"); err != nil {
		return err
	}
	return tx.Put(next)
})
if err != nil {
	panic(err)
}
if err := conn.Flush(ctx, "ws1"); err != nil {
	panic(err)
}
content, _ := files.get("ws1", "Plan.txt")
fmt.Println(content)
Output:
Plan
write docs
ship it

func (RowCodec) Merge added in v0.9.0

Merge returns an error: the connector calls the RowCodec that New binds to its record type instead.

func (RowCodec) Render added in v0.9.0

Render returns an error: the connector calls the RowCodec that New binds to its record type instead.

type RowRef added in v0.9.0

type RowRef struct {
	Entity string
	Key    string
}

RowRef names one row by its entity's wire name and its key.

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. Losing it costs a full reconcile (content comparison, idempotent writes). Without the shadows, nothing records which side changed a row that both sides hold. With Config.WriterID set, the connector keeps a copy of its egress position in the engine, and a row the engine changed after it keeps the client's edit and goes to the source. Without one, every such row takes the source's value, and a client edit the connector had not sent yet is lost.

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.

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.

Jump to

Keyboard shortcuts

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