upstream

package
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Nov 8, 2026 License: MIT Imports: 39 Imported by: 0

Documentation

Overview

Package upstream keeps a local syncplane engine converged with an origin syncplane server, so that a Go process can serve, read and write synced data while offline: a desktop app whose webview syncs against the local engine, a server that syncs with another, or a local engine that forwards an origin to browsers.

A Link binds one local *server.Server to one origin. Per linked workspace it pulls the origin's changes into the local engine and pushes local writes to the origin. The origin orders every write; a local write is optimistic until the origin confirms it. Local rows always hold the rows the origin confirmed with the writes it has not confirmed yet replayed on top, with the semantics the origin applies them with: per-field last-writer-wins for PATCH, a union for collaborative text, and the origin's arrival order deciding between concurrent writes. A write the origin rejects is reverted locally and reported through Config.OnRejected, and, when a downstream client pushed it, to that client as a late rejection on its next pull.

Every local write to a bound entity is captured, whichever path made it: a downstream client's push, server.Apply, Mutate and Invoke, mutators, effects and connectors. Config.Bindings decides which entities sync and in which direction; an entity no binding names stays local. The link's state (the confirmed rows, the pending writes, the origin cursor) lives in the local store, in the same transactions as the rows, so a restart resumes where the process stopped.

Workspace is a typed handle for a Go app that reads and writes the local engine itself: Get, Query, Put, Patch, Delete, Invoke, Watch and Flush, with a Receipt per write to await the origin's verdict.

Shutdown

Stop the parts in the reverse order of their dependencies: cancel the context of blobbridge's Run and wait for it to return, then Close the Link, then Close the local engine (server.Server.Close), then Close the presencebridge and blobbridge stores the engine was built with, then Close the storage adapter. Link.Close tolerates an engine or store that is already closed: its in-flight state writes fail, and it returns once its goroutines have stopped.

Example

Example links a local engine to an origin, writes through the local engine, and reads the row back once the origin confirmed it. The origin runs in-process here; in an app it is a remote server.

package main

import (
	"context"
	"fmt"
	"log"
	"net/http/httptest"
	"os"
	"path/filepath"

	todov1 "github.com/levelfourab/syncplane/engine/gen/example/todo/v1"
	"github.com/levelfourab/syncplane/engine/server"
	"github.com/levelfourab/syncplane/engine/storage/sqlitestore"
	"github.com/levelfourab/syncplane/engine/upstream"
)

func main() {
	ctx := context.Background()
	dir, err := os.MkdirTemp("", "upstream-example-*")
	if err != nil {
		log.Fatal(err)
	}
	defer os.RemoveAll(dir)

	originStore, err := sqlitestore.Open(filepath.Join(dir, "origin.db"))
	if err != nil {
		log.Fatal(err)
	}
	defer originStore.Close()
	origin, err := server.New(originStore, server.WithEntities(&todov1.Todo{}))
	if err != nil {
		log.Fatal(err)
	}
	defer origin.Close()
	ts := httptest.NewServer(origin.HTTPHandler())
	defer ts.Close()

	// The link is built first: the local engine needs its options, and the
	// link needs the engine.
	link, err := upstream.New(upstream.Config{
		OriginURL: ts.URL,
		Bindings:  []upstream.Binding{{Prototype: &todov1.Todo{}}},
	})
	if err != nil {
		log.Fatal(err)
	}
	store, err := sqlitestore.Open(filepath.Join(dir, "local.db"))
	if err != nil {
		log.Fatal(err)
	}
	defer store.Close()
	srv, err := server.New(store, append([]server.Option{server.WithEntities(&todov1.Todo{})}, link.ServerOptions()...)...)
	if err != nil {
		log.Fatal(err)
	}
	defer srv.Close()
	if err := link.Start(ctx, srv); err != nil {
		log.Fatal(err)
	}
	defer link.Close()
	if err := link.AddWorkspace(ctx, "demo"); err != nil {
		log.Fatal(err)
	}

	w := link.Workspace("demo")
	receipt, err := w.Put(ctx, &todov1.Todo{Id: "t1", Title: "buy milk"})
	if err != nil {
		log.Fatal(err)
	}
	if err := receipt.Wait(ctx); err != nil {
		log.Fatal(err)
	}
	if err := w.Flush(ctx); err != nil {
		log.Fatal(err)
	}
	row, _, err := upstream.Get[*todov1.Todo](ctx, w, "t1")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(row.Value.GetTitle())
}
Output:
buy milk

Index

Examples

Constants

View Source
const CodeClientIDInUse = "client_id_in_use"

CodeClientIDInUse is the Rejection.Code of a write whose mutation id the origin reports as applied before the link ever sent it: another writer, for example a second link started over a copy of this link's store, writes under the same client id. The origin did not apply the write.

Variables

View Source
var (
	// ErrNotStarted is returned by a call that needs a started link, Workspace
	// calls included, and by a local write to a bound entity made before
	// Start.
	ErrNotStarted = errors.New("upstream: link not started")
	// ErrClosed is returned by a call made after Close.
	ErrClosed = errors.New("upstream: link closed")
	// ErrNotLinked is returned for a workspace the link does not sync.
	ErrNotLinked = errors.New("upstream: workspace not linked")
	// ErrRevoked is returned by Flush, Await and Receipt.Wait for a workspace
	// the origin refused for good.
	ErrRevoked = errors.New("upstream: workspace access revoked")
	// ErrUnknownWrite is returned by Await for a local sequence the link holds
	// no record of: a write that forwarded nothing, one confirmed before the
	// process started, or one confirmed long enough ago to be forgotten.
	ErrUnknownWrite = errors.New("upstream: no record of the write")
	// ErrSchemaSkew is returned by a write-through write to a workspace that
	// SkewBlock holds. The write did not commit locally and did not reach the
	// origin.
	ErrSchemaSkew = errors.New("upstream: schema revision differs from the origin's; forwarding is blocked")
)
View Source
var ErrOriginUnavailable = errors.New("upstream: origin unavailable")

ErrOriginUnavailable is wrapped by the error a write-through write fails with when the origin did not answer. The write did not commit locally; it may have been applied at the origin, and arrives back through a pull then.

Functions

func WriteBehind

func WriteBehind(ctx context.Context) context.Context

WriteBehind returns a context whose local writes use ModeWriteBehind, whatever Config.WriteMode says.

func WriteThrough

func WriteThrough(ctx context.Context) context.Context

WriteThrough returns a context whose local writes use ModeWriteThrough, whatever Config.WriteMode says.

Types

type AddOptions

type AddOptions struct {
	// Subscriptions scope the workspace, as for AddWorkspace.
	Subscriptions []*syncplanev1.Subscription
	// AdoptLocalRows makes the workspace's first snapshot push every local row
	// of a bound entity that the origin does not hold, as a PUT, instead of
	// deleting it. A row the origin holds takes the origin's value either way.
	// It applies to a workspace that is not linked yet, and only until its
	// first snapshot is applied.
	AdoptLocalRows bool
}

AddOptions configures AddWorkspaceWith.

type Binding

type Binding struct {
	// Prototype is a message of the entity. One of Prototype and Entity is
	// required.
	Prototype proto.Message
	// Entity is the entity's wire name, for an entity without a generated
	// message.
	Entity string
	// Direction is how the entity syncs. The zero value is Both.
	Direction Direction
}

Binding names one entity the link keeps in sync with the origin, by Prototype or by Entity name.

type BootstrapProgress added in v0.7.0

type BootstrapProgress struct {
	// RowsApplied is the number of snapshot rows applied to the local store.
	RowsApplied uint64
	// RowsEstimated is the expected size of the snapshot in rows, 0 when the
	// origin gives no estimate. The origin gives none when read permissions or
	// a narrowing subscription hide rows of the shipped entities. Rows written
	// during the download can make it end above or below the estimate. It is
	// never below RowsApplied.
	RowsEstimated uint64
	// EntitiesDone is the number of entities whose rows are all applied.
	EntitiesDone int
	// EntitiesTotal is the number of entities the snapshot ships, 0 until the
	// origin announces them.
	EntitiesTotal int
}

BootstrapProgress is how far a workspace's snapshot download has got.

The numbers survive a resumed snapshot and a restart of the process: an attempt that continues an interrupted snapshot starts from what the earlier attempts applied. A snapshot the origin starts over (it refused the resume) starts from zero.

RowsApplied / RowsEstimated is at most 1 and never goes down during one snapshot, so it can drive a progress bar as it is.

type ChangePage

type ChangePage struct {
	Changes []server.Change
	// Cursor is the feed position after Changes, with the store lineage the
	// feed stamped on it. Pass it to Watch to resume after them.
	Cursor server.Cursor
}

ChangePage is one page of Workspace.Watch.

type Config

type Config struct {
	// OriginURL is the base URL of the origin server, for example
	// "https://sync.example.com". The sync service is expected at its
	// standard path below it. Required.
	OriginURL string
	// HTTPClient carries every call to the origin. nil means
	// http.DefaultClient. A client Timeout also ends the live stream when it
	// passes, so leave it unset and bound calls with the link's own limits.
	HTTPClient connect.HTTPClient
	// Interceptors are added to every call to the origin, in order, for
	// example one that sets an Authorization header. The link holds one
	// identity at the origin: every workspace is synced as the caller these
	// establish.
	Interceptors []connect.Interceptor
	// ConnectOptions are added to every call to the origin, for example
	// connect.WithGRPC.
	ConnectOptions []connect.ClientOption

	// Bindings name the entities kept in sync with the origin. An entity no
	// binding names is local-only: the link neither pulls it nor forwards a
	// write to it, and a local mutation that writes only local-only entities
	// is not forwarded at all, a custom mutation the local engine runs
	// included. At least one binding is required.
	Bindings []Binding
	// WriteMode is the write mode of a local write whose context names none
	// (see WriteThrough and WriteBehind). The zero value is ModeWriteBehind.
	WriteMode WriteMode
	// ClientID is the client id the link writes to the origin under. Empty
	// means the id the link stored with its workspaces, or a new random id
	// when it stores none. Two links must never share an id. The id must be
	// 1 to 128 bytes with no control characters (\u0000 to \u001f).
	ClientID string

	// OnRejected is called for each local write the origin rejected, after
	// the link has reverted the write's rows: per workspace one call at a
	// time, in the order the rejections arrived, on a goroutine of its own.
	// Delivery is at least once. A rejection is forgotten once its call
	// returns; one whose call ran when the process crashed, before that, is
	// reported again after the next Start, with the same
	// Rejection.MutationID. Close waits for a running call and then forgets
	// its rejection.
	OnRejected func(Rejection)
	// OnReset is called after the link replaced a workspace's rows with a
	// fresh snapshot of the origin, for a reason other than the workspace's
	// first sync.
	OnReset func(workspace string)
	// OnAccessRevoked is called when the origin refused a workspace for good.
	// The link stops syncing the workspace and refuses local writes to its
	// bound entities.
	OnAccessRevoked func(workspace string)
	// OnStatus is called with a workspace's status each time it changes,
	// except that a change of Status.Bootstrap alone is reported at most
	// every 250 ms, and the newest one within 250 ms. The start and the end
	// of a snapshot download are always reported.
	OnStatus func(Status)
	// OnSchemaSkew decides how a workspace reacts when the local engine's
	// schema revision (server.WithSchemaRevision) differs from the one the
	// origin advertises. It is called once per workspace for each new pair
	// of revisions, before the workspace next forwards local writes. The link
	// compares the revisions before each round of forwarding: after a local
	// write, a Flush, a retry, or a change of the origin's revision. nil
	// means SkewWarn for every pair. The link compares nothing when either
	// side advertises no revision.
	OnSchemaSkew func(workspace, local, origin string) SkewAction
	// DeleteOnRevoke deletes the local rows of the bound entities of a
	// workspace the origin revoked, as RemoveWorkspace with
	// RemoveOptions.DeleteRows does.
	DeleteOnRevoke bool

	// RetryMin and RetryMax bound the backoff after a failed call to the
	// origin: the wait is drawn at random up to a window that doubles from
	// RetryMin to RetryMax. 0 means 1s and 30s.
	RetryMin, RetryMax time.Duration
	// ConcurrentSyncs is how many workspaces bootstrap or catch up with the
	// origin at once; the others wait their turn. 0 means 4.
	ConcurrentSyncs int
	// StreamIdleTimeout is how long the live stream may deliver nothing
	// before the link takes it for dead and opens another. 0 means three
	// times the longest gap seen between the origin's heartbeats, from 2s to
	// 90s; until two heartbeats were seen, 10s, doubled up to 90s each time a
	// stream is ended for silence.
	StreamIdleTimeout time.Duration
	// PageLimit is the most changes the link asks for per pull or stream page.
	// 0 asks for the origin's default.
	PageLimit uint32
	// MaxPushMutations is the most mutations one push carries. 0 means 256.
	MaxPushMutations int
	// MaxPushBytes is the encoded size a push stops adding mutations at. A
	// single larger mutation is pushed alone. 0 means 4 MiB.
	MaxPushBytes int
	// OriginLimits are the limits the origin enforces (its server.Limits). The
	// link reads MaxValueBytes, MaxFieldMaskPaths, MaxMutationsPerPush and
	// MaxRequestBytes, and a field at zero or below means the server's
	// default. A local write whose forwarded form is over one of them is
	// refused before it commits, with a server Rejection of code
	// invalid_argument: an Apply returns it, and a downstream client's
	// mutation is rejected with it. A collaborative-text field is measured as
	// the full document the link forwards; a PATCH whose full document is over
	// MaxValueBytes forwards a fragment against the origin's document the
	// link holds, and is measured as that. One local write is one origin
	// mutation, so the rows of one write count against MaxMutationsPerPush,
	// and its encoded form must fit one request of MaxRequestBytes.
	OriginLimits server.Limits
	// WriteThroughTimeout bounds the call a write-through write makes to the
	// origin. 0 means 10s.
	WriteThroughTimeout time.Duration
	// PoisonThreshold is how many times in a row the origin may fail the
	// first pending write the same way, with mutation_failed,
	// invalid_argument or an unknown code, before the link drops it and
	// reports it as rejected with that code. 0 means 5; negative never drops.
	PoisonThreshold int

	// Logger receives the link's background failures. nil means
	// slog.Default().
	Logger *slog.Logger
	// TracerProvider and MeterProvider are the OpenTelemetry providers the
	// link records on. nil means the global providers.
	TracerProvider trace.TracerProvider
	MeterProvider  metric.MeterProvider
}

Config configures a Link.

The callbacks run on the link's own goroutines, and two of them can run at the same time. They may call the link and write to the local engine; the workspace's sync waits while one runs.

type Direction

type Direction int

Direction is the way a bound entity syncs.

const (
	// Both pulls the entity from the origin and forwards local writes to it.
	Both Direction = iota
	// PullOnly pulls the entity from the origin. A local write to it is
	// rejected with code permission_denied, except inside a custom mutation,
	// which the origin runs.
	PullOnly
)
type Link struct {
	// contains filtered or unexported fields
}

Link keeps the bound entities of a local engine converged with an origin server, per linked workspace: it pulls the origin's changes into the local engine and forwards local writes to the origin.

A Link is built with New, installed on the local engine with ServerOptions, and run with Start; see the package example. It is safe for concurrent use.

func New

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

New validates cfg and returns a Link that is not started. It does not connect to the origin.

It returns an error when OriginURL is not an absolute URL, when no binding is given, when a binding names neither a prototype nor an entity, or names one entity twice, and when ClientID breaks the client-id rules.

func (*Link) AddWorkspace

func (l *Link) AddWorkspace(ctx context.Context, workspaceID string, subs ...*syncplanev1.Subscription) error

AddWorkspace links a workspace and starts syncing it in the background, with the given subscriptions; none means every row of every bound entity. The link persists the workspace and its subscriptions, so a later Start resumes it. Adding a linked workspace sets its subscriptions; adding a revoked one asks the origin again.

The origin decides what the workspace holds: when its first snapshot arrives, every local row of a bound entity that the snapshot does not carry and no pending local write touches is deleted. Such rows exist only when the local engine was written to without the link installed. To push them to the origin instead, link with AddWorkspaceWith and AddOptions.AdoptLocalRows.

It returns ErrNotStarted before Start and ErrClosed after Close, and an error for a subscription to an entity that is not bound.

func (*Link) AddWorkspaceWith

func (l *Link) AddWorkspaceWith(ctx context.Context, workspaceID string, opts AddOptions) error

AddWorkspaceWith is AddWorkspace with options.

func (*Link) Await

func (l *Link) Await(ctx context.Context, workspaceID string, seq uint64) error

Await blocks until the origin has decided the local write that took local sequence seq. It returns nil when the origin applied it, and a *RejectedError when the origin rejected it. Before a verdict it returns ErrUnknownWrite when the link holds no record of a forwarded write at seq, ErrRevoked once the origin revoked the workspace, ErrNotLinked when the link does not sync the workspace (any more), ErrClosed when the link closed, and ctx's error when ctx ends.

func (*Link) ClientID

func (l *Link) ClientID() string

ClientID returns the client id the link writes to the origin under, "" before Start.

func (*Link) Close

func (l *Link) Close() error

Close stops syncing: it ends the stream to the origin, waits for in-flight calls and state writes to finish, and returns. Local writes made after Close still queue for the next Start. Close is safe to call more than once.

func (*Link) Flush

func (l *Link) Flush(ctx context.Context, workspaceID string) error

Flush blocks until a linked workspace has no write the origin has not confirmed, every rejection was handed to Config.OnRejected, and the workspace is caught up with the origin. It may be called from a callback. It returns ErrNotLinked for a workspace the link does not sync, the status's LastError for a StateFailed one (ErrNotLinked when its link state was deleted), ErrRevoked once the origin revoked it, and ctx's error when ctx ends first. While SkewBlock holds local writes, Flush waits for the block to lift.

func (*Link) RemoveWorkspace

func (l *Link) RemoveWorkspace(ctx context.Context, workspaceID string, opts RemoveOptions) error

RemoveWorkspace stops syncing a workspace and deletes the link's state for it, its pending writes included: writes the origin has not received are lost, so call Flush first to keep them. Local writes to the workspace's bound entities are refused afterwards. Removing a workspace that is not linked does nothing, whatever opts says.

With RemoveOptions.DeleteRows the rows are deleted in pages, one local transaction each; a removal the process stopped in the middle of finishes after the next Start.

func (*Link) ServerOptions

func (l *Link) ServerOptions() []server.Option

ServerOptions returns the options that install the link on the local engine: the write capture that records local writes, the forwarding of custom mutations the local engine declares no mutator for, and the exclusion of bound entities from the engine's text compaction, since the origin compacts them and sends the result. Pass them to server.New of the engine later given to Start; a link installs on one engine only.

With them installed, the engine refuses a local write to a bound entity made before Start (ErrNotStarted), and one to a workspace the link does not sync (a server Rejection with code permission_denied).

func (*Link) SetSubscriptions

func (l *Link) SetSubscriptions(ctx context.Context, workspaceID string, subs ...*syncplanev1.Subscription) error

SetSubscriptions replaces the subscriptions of a linked workspace; none means every row of every bound entity. The origin sends what enters the new scope and removes what leaves it. A local write to a row outside the scope is forwarded as any other; the row shows locally until the origin confirms the write, and then leaves the local engine, as the origin does not send it. It returns ErrNotLinked for a workspace the link does not sync.

func (*Link) Start

func (l *Link) Start(ctx context.Context, srv *server.Server) (err error)

Start binds the link to srv, the engine built with ServerOptions, and starts syncing every workspace linked before, with the subscriptions it was linked with. It returns once the link state is loaded; syncing runs in the background until Close or until ctx ends. Loading reads each workspace of the local store once. A workspace whose link state does not load is reported as StateFailed, and the others sync.

It returns an error when the link was started before, when srv is nil, and when a bound entity is not registered on srv or its schema cannot be replayed. A Start that returned an error can be called again.

func (*Link) Status

func (l *Link) Status(workspaceID string) (Status, bool)

Status returns the status of a linked workspace, and false when the link does not sync it.

func (*Link) Workspace

func (l *Link) Workspace(id string) *Workspace

Workspace returns a handle on a workspace of the local engine. The id is not checked until a call uses it.

func (*Link) Workspaces

func (l *Link) Workspaces() []string

Workspaces returns the linked workspace ids, sorted.

type Receipt

type Receipt struct {
	Workspace string
	// Seq is the local sequence the write took, 0 when it wrote no row.
	Seq uint64
	// Forwarded reports that the write was queued for the origin. A write
	// to local-only entities is not.
	Forwarded bool
	// contains filtered or unexported fields
}

Receipt identifies one local write for awaiting the origin's verdict.

func (Receipt) Wait

func (r Receipt) Wait(ctx context.Context) error

Wait blocks until the origin has decided the write. It returns nil when the origin applied it or when nothing was forwarded, and a *RejectedError when the origin rejected it. Before a verdict it returns ErrRevoked once the origin revoked the workspace, ErrNotLinked when the link does not sync the workspace (any more), ErrClosed when the link closed, ErrUnknownWrite when the link holds no record of the write (one decided before the process started, or long enough ago to be forgotten), and ctx's error when ctx ends.

type RejectedError

type RejectedError struct {
	Rejection
}

RejectedError reports a local write the origin rejected. Await and Receipt.Wait return it.

func (*RejectedError) Error

func (e *RejectedError) Error() string

type Rejection

type Rejection struct {
	Workspace string
	// LocalSeq is the local sequence the write took, 0 for a custom mutation
	// that wrote no local row.
	LocalSeq uint64
	// MutationID is the id the link pushed the write under.
	MutationID uint64
	// Code is the origin's rejection code, for example "conflict" or
	// "permission_denied", or CodeClientIDInUse.
	Code string
	// Message is human-readable detail for logs.
	Message string
	// Mutator is the name of the custom mutation, "" for a CRUD write.
	Mutator string
	// Rows are the bound rows the write touched locally, which the link
	// reverted.
	Rows []RowRef
}

Rejection is a local write the origin rejected.

type RemoveOptions

type RemoveOptions struct {
	// DeleteRows deletes the workspace's local rows of every bound entity.
	// Rows of local-only entities stay.
	DeleteRows bool
}

RemoveOptions configures RemoveWorkspace.

type Row

type Row[T proto.Message] struct {
	Key string
	// Version is the local sequence that last wrote the row.
	Version uint64
	Value   T
}

Row is one row of the local engine, decoded.

func Get

func Get[T proto.Message](ctx context.Context, w *Workspace, key string) (Row[T], bool, error)

Get reads the row of T's entity that key names from the local engine. It reports false when the row is absent, deleted, or hidden from ctx's caller. T must be a pointer to a generated message type.

func Query

func Query[T proto.Message](ctx context.Context, w *Workspace, spec query.Spec) ([]Row[T], error)

Query returns the rows of T's entity in the local engine that spec matches, in spec's order. Build spec with the engine/query constructors. T must be a pointer to a generated message type.

The whole result is decoded into the returned slice in one read; bound it with spec.Limit, and page with spec.Offset. Without a secondary index that covers the predicate and order, the read scans the whole entity whatever the limit.

type RowRef

type RowRef struct {
	Entity string
	Key    string
}

RowRef names one row.

type SchemaSkew

type SchemaSkew struct {
	Local  string
	Origin string
	// Action is what Config.OnSchemaSkew answered for this pair of
	// revisions.
	Action SkewAction
}

SchemaSkew is a difference between the schema revision of the local engine (server.WithSchemaRevision) and the one the origin advertises.

type SkewAction

type SkewAction int

SkewAction is how a workspace reacts to a schema skew.

const (
	// SkewWarn reports the skew in Status and keeps syncing.
	SkewWarn SkewAction = iota
	// SkewIgnore keeps syncing and reports nothing.
	SkewIgnore
	// SkewBlock reports the skew in Status and stops forwarding local writes
	// to the origin. Pulls continue. Local writes queue and are forwarded
	// once the revisions agree, or once Config.OnSchemaSkew answers another
	// action for a new pair. A write-through write fails with ErrSchemaSkew
	// and commits nothing.
	SkewBlock
)

func (SkewAction) String

func (a SkewAction) String() string

type State

type State int

State is where a workspace's sync with the origin stands.

const (
	// StateConnecting is a workspace the link has not reached the origin for
	// since it started.
	StateConnecting State = iota
	// StateBootstrapping is a workspace whose rows are being replaced with a
	// snapshot of the origin.
	StateBootstrapping
	// StateLive is a workspace that is caught up with the origin and receives
	// its changes as they happen.
	StateLive
	// StateOffline is a workspace whose last call to the origin failed. The
	// link retries with backoff; local writes queue meanwhile.
	StateOffline
	// StateNoAccess is a workspace in which the origin grants the link's
	// caller no permission yet. The link asks again with backoff; local
	// writes queue meanwhile.
	StateNoAccess
	// StateRevoked is a workspace the origin refused for good. The link no
	// longer syncs it.
	StateRevoked
	// StateFailed is a workspace the link cannot sync: its link state does
	// not load, or it was deleted from the local store. Status.LastError says
	// why.
	StateFailed
)

func (State) String

func (s State) String() string

type Status

type Status struct {
	Workspace string
	State     State
	// Pending is how many local writes the origin has not confirmed through
	// a pull yet, those it has applied but not sent back included. A local
	// write counts from when the link notices it, shortly after it commits.
	Pending int
	// OriginSeq is the origin sequence the workspace's confirmed rows are
	// current through.
	OriginSeq uint64
	// OriginHeadSeq is the origin's newest sequence for the workspace, as of
	// the last page or snapshot the link received in this process. 0 means
	// unknown: nothing received yet, or a page from an origin that does not
	// report it.
	// See Behind.
	OriginHeadSeq uint64
	// SchemaRevision is the schema revision the origin advertised last, ""
	// when it advertises none.
	SchemaRevision string
	// SchemaSkew is the standing difference between the local engine's
	// schema revision and the origin's, nil when they agree, when either
	// side advertises none, or when Config.OnSchemaSkew answered SkewIgnore.
	SchemaSkew *SchemaSkew
	// LastError is the last failure, nil after the next success.
	LastError error
	// Bootstrap is how far the snapshot download has got, nil while no
	// bootstrap runs. It is set for the whole of a bootstrap attempt, also
	// while State is StateOffline after a failed call, and goes back to nil
	// when the attempt ends, completed or failed.
	Bootstrap *BootstrapProgress
}

Status is the sync health of one linked workspace.

func (Status) Behind added in v0.7.0

func (s Status) Behind() uint64

Behind returns how many sequences of origin writes the confirmed rows trail the origin by, as of the last page the link received: OriginHeadSeq minus OriginSeq, and 0 when the workspace is up to date or OriginHeadSeq is unknown. It counts writes, not rows: one write can change many rows, and a write the link's caller may not read still takes a sequence. While the origin cannot be reached, it does not grow.

type Workspace

type Workspace struct {
	// contains filtered or unexported fields
}

Workspace is the Go app's handle on one workspace of the local engine. Its writes go through the local engine's write path, so the link captures and forwards them like any other local write; its reads see the local rows, pending writes included. Handles are cheap and safe for concurrent use.

Writes and reads are authorized against ctx as server.Apply and server.View authorize them; mark ctx with server.Trusted for system work. A write's mode follows Config.WriteMode unless ctx was made with WriteThrough or WriteBehind.

func (*Workspace) Apply

func (w *Workspace) Apply(ctx context.Context, fn func(tx *server.ApplyTx) error) (Receipt, error)

Apply runs fn as server.Apply does and returns the receipt of the writes it recorded.

func (*Workspace) Delete

func (w *Workspace) Delete(ctx context.Context, prototype proto.Message, key string) (Receipt, error)

Delete deletes the row of prototype's entity with the given key.

func (*Workspace) Flush

func (w *Workspace) Flush(ctx context.Context) error

Flush is Link.Flush for the workspace.

func (*Workspace) ID

func (w *Workspace) ID() string

ID returns the workspace id.

func (*Workspace) Invoke

func (w *Workspace) Invoke(ctx context.Context, name string, args proto.Message) (Receipt, error)

Invoke runs a custom mutation, as server.Invoke does. A mutator the local engine declares runs locally as a prediction that the origin's result replaces; one it does not declare is forwarded and writes nothing locally.

func (*Workspace) Patch

func (w *Workspace) Patch(ctx context.Context, msg proto.Message, mask []string, expected *uint64, opts ...server.WriteOption) (Receipt, error)

Patch merges the fields mask names from msg onto the stored row, as server.ApplyTx.Patch does. A non-nil expected makes it a compare-and-swap against the row's local version.

func (*Workspace) Put

func (w *Workspace) Put(ctx context.Context, msg proto.Message, opts ...server.WriteOption) (Receipt, error)

Put writes msg as a whole row, as server.ApplyTx.Put does.

func (*Workspace) Watch

func (w *Workspace) Watch(ctx context.Context, from *server.Cursor) iter.Seq2[ChangePage, error]

Watch yields the workspace's committed changes after from, page by page as they commit, origin changes and local writes alike. A nil from starts at the current head. Iteration ends when ctx ends, without an error, or after the first error; server.ErrCursorTooOld reports a from the change feed can no longer serve, from another store lineage included. Each change carries the latest state of its row, so changes to one row between two pages arrive as one.

type WriteMode

type WriteMode int

WriteMode is when a local write reaches the origin.

const (
	// ModeWriteBehind commits a local write at once and forwards it later. A
	// write the origin rejects is reverted locally and reported through
	// Config.OnRejected.
	ModeWriteBehind WriteMode = iota
	// ModeWriteThrough forwards a local write before it commits locally, after
	// every earlier pending write. The local write fails with the origin's
	// rejection (a server Rejection with the origin's code), or with an error
	// when the origin cannot be reached, and commits nothing then.
	//
	// The call to the origin runs while the local store's write lock is held,
	// for the whole round trip. Every other write to the workspace waits for
	// it, the link's own included, so the workspace's pulls and live stream
	// stall too; on a store with one writer, such as sqlitestore, so does
	// every write to every workspace.
	//
	// A downstream client's push uses this mode too. When the origin cannot
	// be reached, the push's whole batch fails with code internal, which the
	// client retries.
	ModeWriteThrough
)

Directories

Path Synopsis
Package blobbridge moves blob bytes between a local engine and the origin server it syncs with.
Package blobbridge moves blob bytes between a local engine and the origin server it syncs with.
internal
rebase
Package rebase computes the rows a replica holds from the rows its origin confirmed and the local writes the origin has not confirmed yet.
Package rebase computes the rows a replica holds from the rows its origin confirmed and the local writes the origin has not confirmed yet.
Package presencebridge joins the rooms of a local syncplane engine to the rooms of the origin server it syncs with, so that people connected to the origin and people connected to the local engine see each other's presence and broadcasts.
Package presencebridge joins the rooms of a local syncplane engine to the rooms of the origin server it syncs with, so that people connected to the origin and people connected to the local engine see each other's presence and broadcasts.

Jump to

Keyboard shortcuts

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