client

package
v0.9.0 Latest Latest
Warning

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

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

Documentation

Overview

Package client is a Go client for a remote syncplane server, for code that keeps no local copy of the data: backend jobs, tools and tests.

A Client wraps the generated Connect clients of SyncService, BlobService and PresenceService. Workspace handles add typed calls on top:

  • Writes: Workspace.Put, Patch, Delete, Apply (several operations as one atomic batch) and Invoke (a custom mutator). Each returns when the server has applied or rejected the mutation. WithExpectedVersion makes a write a compare-and-swap, and WithText sets a collaborative-text field from a plain string.
  • Reads: Get and Query (generic functions over the entity message type), Workspace.Bootstrap and Pull for the change feed, and Client.Subscribe for a live stream.
  • Blobs: Workspace.UploadBlob and DownloadBlob.
  • Presence: Workspace.Room.

Entity names and row keys come from the (syncplane.v1.entity) options of the message, derived as the server derives them; EntityKey exposes the derivation.

Every mutation carries the Client's client id and a mutation id from a counter the Client keeps per workspace in memory. A push that fails in transit is sent again under the same id, so the server applies it at most once. A rejected mutation reports a *RejectedError, and a push the server refuses for the whole workspace reports a *WorkspaceError; CodeOf reads the code of either. The raw services remain available through Client.SyncService, BlobService and PresenceService.

Example

Example writes rows to a workspace on a remote server and reads them back. An in-process server stands in for the remote one.

package main

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

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

// Example writes rows to a workspace on a remote server and reads them back.
// An in-process server stands in for the remote one.
func main() {
	ctx := context.Background()
	url, stop := exampleServer()
	defer stop()

	c, err := client.New(url)
	if err != nil {
		log.Fatal(err)
	}
	ws := c.Workspace("acme")

	// Each write returns once the server has applied or rejected it.
	res, err := ws.Put(ctx, &todov1.Todo{Id: "t1", Title: "Write the report"})
	if err != nil {
		log.Fatal(err)
	}

	// A compare-and-swap against the version the put left.
	_, err = ws.Patch(ctx, &todov1.Todo{Id: "t1", Completed: true}, []string{"completed"},
		client.WithExpectedVersion(res.Seq))
	if err != nil {
		log.Fatal(err)
	}

	// The same guard again is stale now, and the server rejects it.
	_, err = ws.Patch(ctx, &todov1.Todo{Id: "t1", Title: "Late edit"}, []string{"title"},
		client.WithExpectedVersion(res.Seq))
	var rej *client.RejectedError
	if errors.As(err, &rej) {
		fmt.Println("rejected:", rej.Code)
	}

	// Several operations as one atomic mutation.
	if _, err := ws.Apply(ctx,
		client.Put(&todov1.Todo{Id: "t2", Title: "Send the invoice"}),
		client.Delete(&todov1.Todo{}, "t1"),
	); err != nil {
		log.Fatal(err)
	}

	for row, err := range client.QueryAll[*todov1.Todo](ctx, ws, query.Spec{Where: query.Eq("completed", false)}) {
		if err != nil {
			log.Fatal(err)
		}
		fmt.Println(row.Key, row.Value.GetTitle())
	}
}

func exampleServer() (url string, stop func()) {
	dir, err := os.MkdirTemp("", "syncplane-client-example-*")
	if err != nil {
		log.Fatal(err)
	}
	store, err := sqlitestore.Open(filepath.Join(dir, "app.db"))
	if err != nil {
		log.Fatal(err)
	}
	srv, err := server.New(store,
		server.WithEntities(&todov1.Todo{}),
		server.WithLogger(slog.New(slog.DiscardHandler)))
	if err != nil {
		log.Fatal(err)
	}
	ts := httptest.NewServer(srv.HTTPHandler())
	return ts.URL, func() {
		ts.Close()
		_ = srv.Close()
		_ = store.Close()
		_ = os.RemoveAll(dir)
	}
}
Output:
rejected: conflict
t2 Send the invoice

Index

Examples

Constants

View Source
const (
	CodePermissionDenied       = "permission_denied"
	CodeAccessDenied           = "access_denied"
	CodeInvalidArgument        = "invalid_argument"
	CodeConflict               = "conflict"
	CodeTextFullStateRequired  = "text_full_state_required"
	CodeTextStateStale         = "text_state_stale"
	CodeWorkspaceAccessRevoked = "workspace_access_revoked"
	CodeWorkspaceNoAccess      = "workspace_no_access"
	CodeMutationIDGap          = "mutation_id_gap"
	CodeClientIDInUse          = "client_id_in_use"
	CodeInternal               = "internal"
	CodeMutationFailed         = "mutation_failed"
)

Machine-readable codes the server reports on a rejected mutation, on a failed workspace batch, and in the "syncplane-error-code" metadata of an RPC error. Applications may define more codes of their own.

Variables

View Source
var ErrClientIDInUse = errors.New("client: client id in use by another writer")

ErrClientIDInUse is returned by a write when another writer advanced the watermark of this client id past the ids this Client sent, so two live Clients share one id. The server applied nothing of the write. When the error also matches ErrUnconfirmed, an earlier attempt of the mutation may have applied, and no later answer can tell. The next write to the workspace learns the watermark again and continues under the same id.

View Source
var ErrReset = errors.New("client: cursor reset; bootstrap again")

ErrReset is returned by Pull, and reported by Subscribe, when a cursor can no longer continue: it predates the collected tombstones, or its scope changed in a way the server cannot resynchronize. Bootstrap again to get a new cursor.

View Source
var ErrUnconfirmed = errors.New("client: mutation outcome unknown")

ErrUnconfirmed is wrapped by a write error when the client could not learn whether the server applied the mutation: the context ended, every attempt failed in transit or with a transient server failure, or the server refused a resend of a mutation that an earlier attempt may have applied. The error also wraps the last failure, which can be a *WorkspaceError or a *connect.Error, so test for ErrUnconfirmed before those. The mutation stays queued in the Client, which sends it again, under the same mutation id, before the next write to the workspace. Workspace.Confirm sends it again at once and reports its outcome.

Functions

func CodeOf

func CodeOf(err error) string

CodeOf returns the machine-readable code err carries: the Code of a *RejectedError or *WorkspaceError, or the "syncplane-error-code" metadata of a *connect.Error. It returns "" when err carries none.

func EntityKey

func EntityKey(msg proto.Message) (entity, key string, err error)

EntityKey returns the entity name and row key that msg addresses, derived from its (syncplane.v1.entity) options exactly as the server derives them.

It returns an error when msg carries no entity options, when the options name a key field msg does not have or of a kind that cannot form a key, and when the derived key breaks the row-key rules — for example an empty key from unset key fields.

func EntityName

func EntityName(msg proto.Message) (string, error)

EntityName returns the entity name of the message type of msg. msg may be a nil pointer of a generated message type.

func QueryAll

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

QueryAll runs spec like Query and yields every matching row, fetching the next page after the last one when the server reports more. spec.Limit is the page size. spec.Offset applies to the first page only. Rows written between two pages may be missed or seen twice. A spec with Before but no After yields an error, because it pages backward.

Iteration stops after the first error.

Types

type Client

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

Client talks to one syncplane server. It holds no rows: every read goes to the server, and every write is pushed before the call returns.

A Client is safe for concurrent use. Writes to one workspace are serialized: each waits until the previous one has its outcome. Writes to different workspaces run concurrently.

func New

func New(baseURL string, opts ...Option) (*Client, error)

New returns a Client for the server at baseURL, for example "https://sync.example.com" or the URL of an httptest.Server. The services are expected at their standard paths below baseURL.

New does not connect. It returns an error when baseURL is not an absolute URL or when the WithClientID value breaks the client-id rules.

func (*Client) BlobService

func (c *Client) BlobService() syncplanev1connect.BlobServiceClient

BlobService returns the generated BlobService client the Client calls.

func (*Client) ClientID

func (c *Client) ClientID() string

ClientID returns the client id the Client sends.

func (*Client) PresenceService

func (c *Client) PresenceService() syncplanev1connect.PresenceServiceClient

PresenceService returns the generated PresenceService client the Client calls.

func (*Client) Subscribe

func (c *Client) Subscribe(ctx context.Context, scopes []Scope, opts ...ReadOption) iter.Seq2[Event, error]

Subscribe opens one stream over scopes and yields its events: catch-up pages, then live changes. Heartbeats are not yielded. WithPageLimit and WithNoDeltaEntities apply to every scope.

The stream does not reconnect. Iteration ends when ctx is done (without an error), when every scope has been dropped, or when the stream fails, which it yields as an error. Each scope carries the highest sequence this Client's writes to the workspace were applied at, as Pull does.

func (*Client) SyncService

func (c *Client) SyncService() syncplanev1connect.SyncServiceClient

SyncService returns the generated SyncService client the Client calls, configured with its HTTP client and options. Mutations pushed through it bypass the Client's mutation-id counter, so do not push under the Client's client id.

func (*Client) Workspace

func (c *Client) Workspace(id string) *Workspace

Workspace returns a handle on one workspace. Handles are cheap; all handles on one id share the Client's per-workspace write state. The id is not checked until a call sends it.

type Event

type Event struct {
	Workspace      string
	SchemaRevision string
	// Page holds changes for the workspace. Store its NextCursor once the
	// changes are applied; an empty NextCursor keeps the previous one.
	Page *syncplanev1.PullResponse
	// CaughtUp reports that the workspace's backlog is drained; live changes
	// follow.
	CaughtUp bool
	// Dropped reports that the workspace left the stream: ErrReset when its
	// cursor cannot continue, or a *WorkspaceError with
	// CodeWorkspaceAccessRevoked, CodeWorkspaceNoAccess or CodeInternal.
	Dropped error
}

Event is one frame of a Subscribe stream. Exactly one of Page, CaughtUp and Dropped is set.

type Op

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

Op is one CRUD operation for Workspace.Apply. Build it with Put, Patch or Delete; the zero Op is invalid. Errors in building it, such as a message without entity options, are reported by Apply.

func Delete

func Delete(prototype proto.Message, key string, opts ...WriteOption) Op

Delete deletes the row of prototype's entity that key names. Only the type of prototype is read. Deleting an absent row is not an error.

func Patch

func Patch(msg proto.Message, paths []string, opts ...WriteOption) Op

Patch writes the fields that paths name from msg to the row msg addresses, field by field, last writer wins. paths are dotted proto field paths, the form a google.protobuf.FieldMask carries. A patch does not create a row: the server rejects a patch of an absent row with CodeConflict.

func Put

func Put(msg proto.Message, opts ...WriteOption) Op

Put replaces the whole row msg addresses, or creates it. Collaborative-text fields are merged with the stored documents, and fields the caller may not write keep their stored values. Apply marshals msg; msg is not changed.

type Option

type Option func(*config)

Option configures New.

func WithClientID

func WithClientID(id string) Option

WithClientID sets the client id that mutations, pulls and streams carry. The default is a random id per Client.

The server keeps one mutation watermark per workspace, caller and client id. With a set id, the Client reads that watermark from the server before its first write to a workspace and continues after it. Two live Clients must never share an id: their writes report ErrClientIDInUse or mutation-id gaps.

The id must be 1 to 128 bytes with no control characters (\u0000 to \u001f); New returns an error otherwise.

func WithConnectOptions

func WithConnectOptions(opts ...connect.ClientOption) Option

WithConnectOptions adds Connect client options to every call, for example connect.WithGRPC to speak gRPC instead of the Connect protocol, or connect.WithSendGzip.

func WithHTTPClient

func WithHTTPClient(c connect.HTTPClient) Option

WithHTTPClient sets the HTTP client every call goes through. The default is http.DefaultClient. A client with a Timeout also ends Subscribe and presence streams when the timeout passes.

func WithInterceptors

func WithInterceptors(interceptors ...connect.Interceptor) Option

WithInterceptors adds Connect interceptors to every call, in order, for example one that sets an Authorization header.

func WithMaxAttempts

func WithMaxAttempts(n int) Option

WithMaxAttempts sets how many times a write sends its push when it fails in transit or the server reports a transient failure. The default is 5. Values below 1 mean 1.

type Page

type Page[T proto.Message] struct {
	// Rows are ordered by the query's OrderBy, ties broken by row key.
	Rows []Row[T]
	// StartCursor and EndCursor are the positions of the first and last row,
	// for Spec.Before and Spec.After. Both are empty for an empty page.
	StartCursor, EndCursor []byte
	// HasMore reports rows past the end the limit counted from.
	HasMore bool
}

Page is one page of a query.

func Query

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

Query runs spec against T's entity on the server, with the caller's read rules applied, and returns one page. Build spec.Where and spec.OrderBy with the engine/query constructors.

spec.Limit of 0 or less asks for the server's default page size, and the server clamps every limit to its maximum. Without a secondary index that covers the predicate and order, the server scans the whole entity per call. The server's errors arrive as *connect.Error, for example InvalidArgument for an unknown field path or a cursor of another query.

type ReadOption

type ReadOption func(*readOpts)

ReadOption configures Bootstrap, Pull and Subscribe.

func WithNoDeltaEntities

func WithNoDeltaEntities(entities ...string) ReadOption

WithNoDeltaEntities makes Pull and Subscribe send every collaborative-text field of the named entities in full. Without it, a page may send such a field as a fragment relative to the cursor (RowChange.text_deltas), which only a caller that keeps the rows can apply.

func WithPageLimit

func WithPageLimit(n uint32) ReadOption

WithPageLimit sets the most changes per Pull page or Subscribe catch-up page. 0, the default, asks for the server's default; the server clamps to its maximum.

func WithSubscriptions

func WithSubscriptions(subs ...*syncplanev1.Subscription) ReadOption

WithSubscriptions scopes Bootstrap and Pull to subs. Without it they cover every entity. Subscribe ignores it; set Scope.Subscriptions instead.

type RejectedError

type RejectedError struct {
	Workspace  string
	MutationID uint64
	// Code is one of the Code constants or an application-defined code.
	Code string
	// Message is human-readable detail for logs. Branch on Code instead.
	Message string
}

RejectedError reports a mutation the server rejected. A rejection is final: the server wrote nothing for the mutation and will give the same answer to every resend.

func (*RejectedError) Error

func (e *RejectedError) Error() string

type Result

type Result struct {
	// MutationID is the id the write was pushed under.
	MutationID uint64
	// Seq is the workspace sequence the write took: the version of every row
	// it wrote. It is 0 when AlreadyApplied is true.
	Seq uint64
	// AlreadyApplied reports that the server had applied the mutation before:
	// an earlier attempt landed although its response was lost.
	AlreadyApplied bool
}

Result is the outcome of a write the server accepted.

type Room

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

Room is one presence session in one room: what this Client publishes there and watches there. Presence state and broadcasts are ephemeral; the server stores none of them. A Room is safe for concurrent use.

func (*Room) Broadcast

func (r *Room) Broadcast(ctx context.Context, payload []byte) error

Broadcast sends payload to every session watching the room now, this one included. Nobody receives it later.

func (*Room) Leave

func (r *Room) Leave(ctx context.Context) error

Leave withdraws this session from the room; watchers see it leave at once.

func (*Room) SessionID

func (r *Room) SessionID() string

SessionID returns the session id the Room publishes and watches as.

func (*Room) SetPresence

func (r *Room) SetPresence(ctx context.Context, state []byte, seq uint64) (*syncplanev1.PublishResponse, error)

SetPresence replaces this session's presence state in the room with state, at the next revision. seq is the workspace sequence the state was made at, or 0 when it does not matter. While no Watch of this Room is open, the state expires unless SetPresence is called again at the interval the returned response names.

func (*Room) Watch

Watch opens a stream on the room and yields its frames: the roster first, then updates, departures, broadcasts and at most one TopicDropped. Heartbeats are not yielded. While the stream is open the server keeps this session's presence alive.

The stream does not reconnect. Iteration ends when ctx is done (without an error), after a dropped frame, or when the stream fails, which it yields as an error.

type Row

type Row[T proto.Message] struct {
	Key string
	// Version is the workspace sequence that last wrote the row; pass it to
	// WithExpectedVersion for a compare-and-swap.
	Version uint64
	// Value is the row. It is the zero T (nil) when Deleted is true. A field
	// named in Hidden, or in the RowChange's text_deltas, reads as its zero
	// value.
	Value T
	// Hidden names the fields the caller may not read.
	Hidden []string
	// Deleted reports a tombstone. Only rows from a pull or a stream can be
	// tombstones.
	Deleted bool
}

Row is one row as the server sent it, decoded into its entity message.

func DecodeRow

func DecodeRow[T proto.Message](rc *syncplanev1.RowChange) (Row[T], error)

DecodeRow decodes one RowChange of T's entity. It returns an error when rc belongs to another entity or its value does not decode as T. T must be a pointer to a generated message type.

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. It reports false when the row is absent, deleted, or hidden from the caller by a read rule. T must be a pointer to a generated message type.

type Scope

type Scope struct {
	Workspace string
	// Cursor is where the stream resumes, from a Snapshot, a Pull page or a
	// stream page. Nil starts at the beginning, as for Pull.
	Cursor []byte
	// Subscriptions scope the workspace; empty means every entity.
	Subscriptions []*syncplanev1.Subscription
}

Scope is one workspace of a Subscribe stream.

type Snapshot

type Snapshot struct {
	// Cursor is the position the snapshot captures. Pass it to Pull or
	// Subscribe to receive every change written after it.
	Cursor []byte
	// Seq is the workspace sequence Cursor captures.
	Seq uint64
	// LastAckedMutationID is the server's mutation watermark for the Client's
	// client id.
	LastAckedMutationID uint64
	// SchemaRevision is the server's schema revision, or "" when it advertises
	// none.
	SchemaRevision string
	// Entities lists every entity the snapshot ships rows of, in delivery
	// order.
	Entities []string
	// contains filtered or unexported fields
}

Snapshot is a Bootstrap in progress: the position it captures, and its rows.

func (*Snapshot) Close

func (s *Snapshot) Close() error

Close releases the snapshot's stream. It is safe to call more than once.

func (*Snapshot) Rows

Rows yields the snapshot's rows in delivery order, and closes the stream when the iteration ends. A snapshot holds no tombstones. Rows can be ranged over once; a second range yields an error. Iteration stops after the first error.

type Workspace

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

Workspace addresses one workspace of a Client. It is safe for concurrent use.

func (*Workspace) AnchoredRoom

func (w *Workspace) AnchoredRoom(name, entity, key string) *Room

AnchoredRoom returns a session in the room named name that is anchored to the row of entity and key: only a caller that can read the row is admitted.

func (*Workspace) Apply

func (w *Workspace) Apply(ctx context.Context, ops ...Op) (Result, error)

Apply pushes ops as one mutation and returns when its outcome is known. More than one op form a batch: the server applies them in order and atomically, at one sequence, or rejects them all. Apply with no ops returns an error.

Apply blocks until the server answers, retrying a push that fails in transit (see WithMaxAttempts), and until every earlier write of the Client to the workspace has its outcome. An unconfirmed earlier write is sent again first; when its outcome still cannot be learned, Apply returns that error and sends nothing. Errors:

  • *RejectedError: the server rejected the mutation, for example with CodeConflict for a failed compare-and-swap.
  • *WorkspaceError: the server refused the push for the whole workspace.
  • ErrUnconfirmed: the outcome is unknown; see its documentation.
  • ErrClientIDInUse: another writer uses the client id.
  • A *connect.Error the server returned for the request, which then did not apply.
  • An error for an invalid op, before anything is sent.

func (*Workspace) Bootstrap

func (w *Workspace) Bootstrap(ctx context.Context, opts ...ReadOption) (*Snapshot, error)

Bootstrap opens a snapshot of the workspace: every row the caller can read, within the WithSubscriptions scope. It returns when the server has sent the snapshot's position; read the rows with Snapshot.Rows. The caller must range over Rows or call Close to release the stream.

func (*Workspace) Client

func (w *Workspace) Client() *Client

Client returns the Client the handle belongs to.

func (*Workspace) Confirm

func (w *Workspace) Confirm(ctx context.Context) (Result, error)

Confirm sends the write whose outcome is unknown again, under its mutation id, and returns its outcome with the errors of Apply. It returns a zero Result and nil when no write of the workspace is unconfirmed.

func (*Workspace) Delete

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

Delete deletes the row of prototype's entity that key names; see the Delete function. It is Apply with one operation.

func (*Workspace) DownloadBlob

func (w *Workspace) DownloadBlob(ctx context.Context, digest string, dst io.Writer) (int64, error)

DownloadBlob writes the blob that digest names to dst, checking each chunk against its hash, and returns the number of bytes written.

When the server reports the blob as being uploaded, DownloadBlob blocks until the upload completes or ctx ends; it then returns ctx's error. It fails with a *connect.Error of code NotFound when no row the caller can read refers to the blob, when the server has no bytes for it, and when an upload it waits for is removed. On an error dst may hold part of the blob.

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) (Result, error)

Invoke runs the custom mutator registered on the server under name, with args packed as a google.protobuf.Any; nil args sends none. Its outcome and errors are those of Apply: a mutator that rejects reports a *RejectedError, and one that fails reports a *WorkspaceError with CodeMutationFailed.

func (*Workspace) Patch

func (w *Workspace) Patch(ctx context.Context, msg proto.Message, paths []string, opts ...WriteOption) (Result, error)

Patch writes the fields paths name to the row msg addresses; see the Patch function. It is Apply with one operation.

func (*Workspace) Pull

func (w *Workspace) Pull(ctx context.Context, cursor []byte, opts ...ReadOption) iter.Seq2[*syncplanev1.PullResponse, error]

Pull yields the pages of changes after cursor, one Pull call per page, until the server reports no more. Store each page's NextCursor once its changes are applied; the last one resumes from where the iteration ended. A nil cursor starts at the beginning of the workspace, which only a workspace that has collected no tombstones can serve.

When the cursor cannot continue, Pull yields ErrReset; bootstrap again. Iteration stops after the first error. Each request carries the highest sequence this Client's writes were applied at, so a server reading from a replica never answers with state older than them. A response whose head is below that sequence tells that the workspace's history no longer holds it, and later requests carry that head instead.

func (*Workspace) Put

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

Put replaces the whole row msg addresses, or creates it; see the Put function. It is Apply with one operation.

func (*Workspace) Room

func (w *Workspace) Room(name string) *Room

Room returns a session in the room named name of the workspace. The room is unanchored: workspace access admits a caller. Use AnchoredRoom for a room that follows the read access of one row. The session id is random per Room.

func (*Workspace) UploadBlob

func (w *Workspace) UploadBlob(ctx context.Context, r io.ReaderAt, size int64, mediaType string) (*syncplanev1.BlobRef, error)

UploadBlob uploads the size bytes of r into the workspace's blob store and returns the reference a row stores to point at them. mediaType is carried in the reference as given.

It reads r twice: once to compute the digest, then again for each chunk the server is missing. A blob the server already holds sends no chunks, and an interrupted upload resumes where it stopped. Memory use is one chunk (blob.ChunkSize bytes). The server's errors arrive as *connect.Error, for example ResourceExhausted for a blob above its size limit.

type WorkspaceError

type WorkspaceError struct {
	Workspace string
	Code      string
	Message   string
}

WorkspaceError reports a push the server refused as a whole for one workspace, so nothing of it applied. Code is CodeWorkspaceAccessRevoked, CodeWorkspaceNoAccess, CodeMutationFailed, CodeInvalidArgument or another workspace-scoped code. A Subscribe stream that drops a workspace for lost access reports the same type.

func (*WorkspaceError) Error

func (e *WorkspaceError) Error() string

type WriteOption

type WriteOption func(*writeOpts)

WriteOption configures one write operation.

func WithExpectedVersion

func WithExpectedVersion(version uint64) WriteOption

WithExpectedVersion makes the operation a compare-and-swap: the server applies it only when the stored row's version equals version, and rejects it with CodeConflict otherwise. An absent or deleted row has version 0, so WithExpectedVersion(0) means "only when the row does not exist". Read the version from Row.Version or Result.Seq.

func WithText

func WithText(path, value string) WriteOption

WithText sets the collaborative-text field at path from a plain string. path is the dotted proto path; a document inside a keyed list element or a map entry is named by its instance path ("notes.<key>.body"), and the written message must carry that element or entry. On a Patch the path joins the field mask. Repeat the option for more fields.

The write reads the stored row first, makes the document read as value with the fewest edits, and sends the whole document. The server merges it with the stored document, so edits that land between the read and the write are kept. An empty value deletes all text the read saw. Each such write adds one writer identity to the document's peer table. Not allowed on a Delete.

Jump to

Keyboard shortcuts

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