Documentation
¶
Overview ¶
Reference-following subscriptions: a subscription's synced set is its base predicate scope UNION a bounded-depth closure reached by walking typed reference relations from the base-visible rows. Every following pull brings the closure up to date against current rows and reconciles it with the exact key-set the cursor carries (Cursor.closure), so a row that LEAVES the closure is dropped precisely — following a ref is never a one-way ratchet, and never a permission-escalation path: every closure member passes the same read filter as a base row.
Two directions, resolved from the reference graph by segment name:
- forward (issue→project): a key point-lookup off the holder's ref stub.
- reverse (project→issues): a range probe of the source entity's per-ref-field secondary index for rows whose ref field points back at the holder, falling back to a predicate scan of that entity when the index is not built yet. Bounded by MaxReverseFanOut either way.
The closure is a SET of (entity, key); a row held by ANY path is in it once, which makes multi-path "held by A or B" drop-correctness automatic.
buildClosure walks it from every seed. That is the answer for any shape and the fallback for all of them, but it costs a hop per holder however little moved, so a pull that can see every row written since its cursor MAINTAINS a single-segment closure at depth 1 from those rows instead — either direction — see maintainClosure.
Error text conventions for this package, and the helpers that hold the recurring messages to one wording.
Which audience an error is for decides how it reads, and the prefix is what tells them apart:
- Errors an APPLICATION DEVELOPER gets back from a Go call — RegisterEntity, RegisterMerger, RegisterDynamicEntity, EntityKey, the ViewTx/ApplyTx/ EntityTx methods, the options New applies — carry a "server: " prefix. They surface far from here, wrapped into a startup error or logged beside errors from unrelated libraries, so they must name their origin. They may name Go identifiers, because the reader is holding the Go API.
- Errors a CLIENT gets back over the wire — the connect.Error values the RPC handlers return — carry NO prefix. A Go package name is noise in an RPC status, and the reader is on the far side of the wire, quite possibly not writing Go at all.
A helper whose error is always wrapped by its caller (resolveMergerField, kindToType) inherits the caller's prefix and must not add its own.
Both audiences are owed a way out, which is the harder half of the rule: an error that reports a bound names the bound's current value AND the knob that moves it, and an error about an unregistered entity names the call that registers it. "exceeds MaxClosureSize" is a fact about the engine's internals that leaves the reader exactly where they started.
Delta resync: when a pull's subscription set or filter epoch no longer matches its cursor, the server used to reply reset=true and force a full re-bootstrap — correct but blunt, since a single permission change would stampede every client in the workspace at once. Instead, the server now reconstructs the visibility rules the cursor was issued under, compares the workspace's live rows under both, and ships only the difference between the old visible set and the new one:
visible → hidden tombstone (the client drops the row) hidden → visible value unchanged nothing entity left the set one Patch.drop_entities name, instead of per-row tombstones
The diff covers only rows with Version <= the cursor's seq — exactly the rows the client could already hold. Anything written later is the job of the catch-up pull that follows the resync (the completed cursor keeps the ORIGINAL seq under the new scope), which also makes the paged diff safe without a pinned snapshot: a row edited mid-resync gains a version past the cursor's seq, and the catch-up pull re-delivers or tombstones it under the new visibility, overwriting whatever the diff decided.
Reset remains the fallback whenever the old visibility cannot be reconstructed: legacy cursors without an embedded subscription set, epoch changes without EpochReadFilters (or past its retained history), and a second scope change landing mid-resync (the client's rows are then a mixture of old and new scope that no single diff describes).
Package server implements the sync engine's ConnectRPC service on top of a storage.Adapter.
Windowed subscriptions: a subscription can bound its synced set by RANK rather than only by attribute — "the 1000 most recently updated open issues" instead of "every open issue". Without it the only lever an app has over working-set size is a more selective predicate, which for a real view (a busy project, "all open", an active label) often is not semantically possible.
A window is the same KIND of object a follow closure is: a bounded membership set that cannot be decided per row, is resolved against the rows of a snapshot, is diffed against an exact key-set carried on the cursor, and emits entering rows as values and leaving rows as tombstones-unless- otherwise-visible. So it reuses that machinery (closureRows, emitMembershipDiff) rather than growing a parallel one; the only difference is the membership rule — `rank <= limit` instead of `reachable by a ref path`.
Two orderings:
- order_by: the entity's own fields, via the same query.Order that backs the Query RPC and ViewTx.Query, so a window means what the equivalent query means.
- by_recency: the row's workspace sequence, descending. It sorts without decoding anything, which makes it the cheap window to serve.
What a window bounds first is the CLIENT: what it holds, bootstraps and materializes. On the server it is bounded by whatever serves the ordering. Resolving an order_by window from scratch is exactly its Query — a range read off a serving index, or a scan of the entity into a top-K heap without one — and an unfiltered recency window reads `limit` rows and stops, because the store can produce one entity's rows newest-first.
Resolving from scratch is the FALLBACK, not the steady state. A pull that knows every row written since the cursor maintains the membership from those rows instead (see maintain). The cursor carries the members and the position of the weakest of them, which turns a changed row's membership into one comparison; only a row entering or leaving a full window costs a read, and then a bounded ordered walk either side of that position rather than the whole window. Both paths answer the same question and must produce the same set — the rebuild is what the maintained set is tested against.
Example ¶
Example is the whole server side of a sync app: open a store, declare the schema and the server-authoritative mutations, serve the handler. A client pushes a mutation and pulls the result back, standing in for the TypeScript client's background coordinator.
package main
import (
"context"
"fmt"
"log"
"net/http/httptest"
"os"
"path/filepath"
"connectrpc.com/connect"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/anypb"
todov1 "github.com/levelfourab/syncplane/engine/gen/example/todo/v1"
syncplanev1 "github.com/levelfourab/syncplane/engine/gen/syncplane/v1"
"github.com/levelfourab/syncplane/engine/gen/syncplane/v1/syncplanev1connect"
"github.com/levelfourab/syncplane/engine/server"
"github.com/levelfourab/syncplane/engine/storage/sqlitestore"
)
func main() {
dir, err := os.MkdirTemp("", "syncplane-example-*")
if err != nil {
log.Fatal(err)
}
defer os.RemoveAll(dir)
// The store is the caller's to close: it may outlive the server, and one
// adapter can back several of them.
store, err := sqlitestore.Open(filepath.Join(dir, "app.db"))
if err != nil {
log.Fatal(err)
}
defer store.Close()
srv, err := server.New(store,
// Entities are ordinary proto messages carrying (syncplane.v1.entity).
server.WithEntities(&todov1.Todo{}),
// A mutator is a named write the server owns: clients ask for it by
// name, and it runs inside the push transaction.
server.WithMutator("complete_all", &todov1.CompleteAllArgs{},
func(_ context.Context, tx *server.EntityTx, _ proto.Message) error {
var todos []*todov1.Todo
if err := tx.Scan(&todov1.Todo{}, func(msg proto.Message) error {
todos = append(todos, msg.(*todov1.Todo))
return nil
}); err != nil {
return err
}
for _, todo := range todos {
todo.Completed = true
if err := tx.Put(todo); err != nil {
return err
}
}
return nil
}),
)
if err != nil {
log.Fatal(err)
}
defer srv.Close()
// In a real main this is http.ListenAndServe(":8787", srv.HTTPHandler()).
ts := httptest.NewServer(srv.HTTPHandler())
defer ts.Close()
client := syncplanev1connect.NewSyncServiceClient(ts.Client(), ts.URL)
ctx := context.Background()
value, err := proto.Marshal(&todov1.Todo{Id: "t1", Title: "buy milk"})
if err != nil {
log.Fatal(err)
}
args, err := anypb.New(&todov1.CompleteAllArgs{})
if err != nil {
log.Fatal(err)
}
// One workspace batch: create a todo, then complete every todo. Each
// mutation carries the client's own monotonic id, which is how the server
// acks it exactly once however often the client retries.
if _, err := client.Push(ctx, connect.NewRequest(&syncplanev1.PushRequest{
Batches: []*syncplanev1.WorkspaceBatch{{
WorkspaceId: "demo",
Mutations: []*syncplanev1.Mutation{
{ClientId: "c1", MutationId: 1, Payload: &syncplanev1.Mutation_Crud{
Crud: &syncplanev1.CrudMutation{
Entity: "todo", Key: "t1",
Op: syncplanev1.CrudOp_CRUD_OP_PUT, Value: value,
},
}},
{ClientId: "c1", MutationId: 2, Payload: &syncplanev1.Mutation_Custom{
Custom: &syncplanev1.CustomMutation{Name: "complete_all", Args: args},
}},
},
}},
})); err != nil {
log.Fatal(err)
}
// Pull from an empty cursor: the client's first read of the workspace.
resp, err := client.Pull(ctx, connect.NewRequest(&syncplanev1.PullRequest{WorkspaceId: "demo"}))
if err != nil {
log.Fatal(err)
}
for _, change := range resp.Msg.GetPatch().GetChanges() {
var todo todov1.Todo
if err := proto.Unmarshal(change.GetValue(), &todo); err != nil {
log.Fatal(err)
}
fmt.Printf("%s: %q completed=%t\n", change.GetKey(), todo.GetTitle(), todo.GetCompleted())
}
}
Output: t1: "buy milk" completed=true
Index ¶
- Constants
- Variables
- func ApplyTextStrings(dst, base, cur proto.Message, texts map[string]string, peer string) error
- func BuildDynamicFile(specs ...DynamicEntity) (protoreflect.FileDescriptor, error)
- func BuildDynamicMessageType(spec DynamicEntity) (protoreflect.MessageType, error)
- func Delete[T proto.Message](tx Writer, key string) error
- func DenyRoom(message string) error
- func DenyWorkspace(message string) error
- func Get[T proto.Message](tx Reader, key string) (T, bool, error)
- func Query[T proto.Message](tx Reader, spec query.Spec) iter.Seq2[T, error]
- func QueryRows[T proto.Message](tx Reader, spec query.Spec) iter.Seq2[Row[T], error]
- func RefKeyFields(fd protoreflect.FieldDescriptor) []protoreflect.FieldDescriptor
- func Reject(code, message string) error
- func Scan[T proto.Message](tx Reader) iter.Seq2[T, error]
- func ScanRows[T proto.Message](tx Reader) iter.Seq2[Row[T], error]
- func Trusted(ctx context.Context) context.Context
- func TrustedAs(ctx context.Context, name string) context.Context
- func WithPrincipal(ctx context.Context, p Principal) context.Context
- type AllowAll
- func (AllowAll) CanAccessWorkspace(context.Context, Principal, string) error
- func (AllowAll) CanMutate(context.Context, Principal, string, Write) error
- func (AllowAll) FilterEpoch(context.Context, Principal, string) (uint64, error)
- func (AllowAll) ReadFilter(context.Context, Principal, string, string) (RowFilter, error)
- type AllowAllRooms
- type AppSchema
- type ApplyTx
- func (a *ApplyTx) Delete(prototype proto.Message, key string) error
- func (a *ApplyTx) Get(dst proto.Message, key string) (found bool, version uint64, err error)
- func (a *ApplyTx) GetMeta(dst proto.Message, key string) (found bool, meta RowMeta, err error)
- func (a *ApplyTx) Patch(msg proto.Message, mask []string, expected *uint64, opts ...WriteOption) error
- func (a *ApplyTx) Put(msg proto.Message, opts ...WriteOption) error
- func (a *ApplyTx) Query(prototype proto.Message, spec query.Spec, ...) error
- func (a *ApplyTx) ScanPage(prototype proto.Message, afterKey string, limit int, ...) (lastKey string, more bool, err error)
- type Authenticator
- type AuthenticatorFunc
- type BlobPermissions
- type CallerAccess
- type CallerAccessFunc
- type CapturedOp
- type CapturedWrite
- type Change
- type ConsumerShadowWrite
- type ConsumerUpdate
- type Cursor
- type DenyAll
- type DynamicEntity
- type DynamicField
- type DynamicIndex
- type DynamicIndexKey
- type EntityMeta
- type EntityTx
- func (e *EntityTx) AsCaller() *EntityTx
- func (e *EntityTx) Can(permission string, prototype proto.Message, key string) (bool, error)
- func (e *EntityTx) Delete(prototype proto.Message, key string) error
- func (e *EntityTx) Get(dst proto.Message, key string) (bool, error)
- func (e *EntityTx) GetMeta(dst proto.Message, key string) (found bool, meta RowMeta, err error)
- func (e *EntityTx) Patch(msg proto.Message, mask []string, expected *uint64, opts ...WriteOption) error
- func (e *EntityTx) Put(msg proto.Message, opts ...WriteOption) error
- func (e *EntityTx) Query(prototype proto.Message, spec query.Spec, fn func(msg proto.Message) error) error
- func (e *EntityTx) Scan(prototype proto.Message, fn func(msg proto.Message) error) error
- func (e *EntityTx) ScanPage(prototype proto.Message, afterKey string, limit int, ...) (lastKey string, more bool, err error)
- func (e *EntityTx) Seq() uint64
- func (e *EntityTx) Workspace() string
- type EpochReadFilters
- type FieldPermissions
- type HistoryFilterFunc
- type Limits
- type Manager
- func (m *Manager) AdminHandler() (string, http.Handler)
- func (m *Manager) App(appID string) *Server
- func (m *Manager) AppIDs() []string
- func (m *Manager) Close() error
- func (m *Manager) ListAppSchemas(ctx context.Context) ([]AppSchema, error)
- func (m *Manager) Register(ctx context.Context, appID string, set []byte, opts ...RegisterOption) (ManagerRegisterResult, error)
- func (m *Manager) SyncHandler() http.Handler
- type ManagerOption
- type ManagerRegisterResult
- type MergeFunc
- type MutationOrigin
- type MutatorAccess
- type MutatorFunc
- type MutatorOption
- type Option
- func Mutator[A proto.Message](name string, fn func(ctx context.Context, tx *EntityTx, args A) error, ...) Option
- func WithAuthenticator(a Authenticator) Option
- func WithBlobRetention(d time.Duration) Option
- func WithBlobStore(st blob.Store) Option
- func WithCallerAccess(fn CallerAccessFunc) Option
- func WithChunkSize(n int) Option
- func WithClientRetention(d time.Duration) Option
- func WithCursorStateStore(st cursorstate.Store) Option
- func WithEntities(msgs ...proto.Message) Option
- func WithGC(retention, interval time.Duration) Option
- func WithHeartbeat(d time.Duration) Option
- func WithHistoryFilter(fn HistoryFilterFunc) Option
- func WithHistoryRetention(d time.Duration) Option
- func WithHistorySession(d time.Duration) Option
- func WithIdempotencyRetention(d time.Duration) Option
- func WithIndexBuild(interval time.Duration, batch int) Option
- func WithLeases(l lease.Locker) Option
- func WithLimits(l Limits) Option
- func WithLogger(l *slog.Logger) Option
- func WithMerger(prototype proto.Message, fieldPath string, fn MergeFunc) Option
- func WithMeterProvider(mp metric.MeterProvider) Option
- func WithMutator(name string, argsPrototype proto.Message, fn MutatorFunc, ...) Option
- func WithNotifier(n pubsub.Notifier) Option
- func WithNotifyCoalescing(window time.Duration) Option
- func WithPermissions(p Permissions) Option
- func WithPresenceBus(b presence.Bus) Option
- func WithRoomAnnounce(d time.Duration) Option
- func WithSchemaRevision(rev string) Option
- func WithStrictAccess() Option
- func WithTextCache(budgetBytes int64) Option
- func WithTextCompaction(minPurged int) Option
- func WithTextCompactionPacing(interval time.Duration, batch int) Option
- func WithTextDeltaRetention(d time.Duration) Option
- func WithTracerProvider(tp trace.TracerProvider) Option
- func WithUnknownMutatorForwarding() Option
- func WithWriteCapture(c WriteCapture) Option
- func WithoutTextCompaction(entities ...string) Option
- type ParticipantFilter
- type Permissions
- type Principal
- type Reader
- type Reference
- type RegisterAuthorizer
- type RegisterInfo
- type RegisterOption
- type RegisterResult
- type RegisterStatus
- type Rejection
- type ReplicaTx
- func (r *ReplicaTx) Delete(entity, key string) error
- func (r *ReplicaTx) Get(entity, key string) (row storage.Row, found bool, err error)
- func (r *ReplicaTx) Put(entity, key string, value []byte) error
- func (r *ReplicaTx) RejectLate(origin MutationOrigin, code, message string) error
- func (r *ReplicaTx) Seq() uint64
- func (r *ReplicaTx) Tx() storage.WriteTx
- func (r *ReplicaTx) Workspace() string
- type RoomDenial
- type RoomPermissions
- type Row
- type RowFilter
- type RowMeta
- type RowWriteFilter
- type RowWritePermissions
- type Server
- func (s *Server) AdvanceConsumer(ctx context.Context, workspaceID, consumer string, up ConsumerUpdate) error
- func (s *Server) Apply(ctx context.Context, workspaceID string, fn func(tx *ApplyTx) error) error
- func (s *Server) ApplyIdempotent(ctx context.Context, workspaceID, key string, ...) (WriteOutcome, error)
- func (s *Server) BeginUpload(ctx context.Context, req *connect.Request[syncplanev1.BeginUploadRequest]) (*connect.Response[syncplanev1.BeginUploadResponse], error)
- func (s *Server) BlobHandler() (string, http.Handler)
- func (s *Server) Bootstrap(ctx context.Context, req *connect.Request[syncplanev1.BootstrapRequest], ...) (err error)
- func (s *Server) BuildIndexes(ctx context.Context, workspaceID string) error
- func (s *Server) Changes(ctx context.Context, workspaceID string, after Cursor, limit int, ...) (next Cursor, more bool, err error)
- func (s *Server) Close() error
- func (s *Server) CollectGarbage(ctx context.Context, workspaceID string) error
- func (s *Server) CompactText(ctx context.Context, workspaceID string) (int, error)
- func (s *Server) ConsumerPendingWorkspaces(ctx context.Context, consumer, after string, limit int) ([]string, error)
- func (s *Server) ConsumerPosition(ctx context.Context, workspaceID, consumer string) (Cursor, bool, error)
- func (s *Server) ConsumerPositions(ctx context.Context, workspaceID string) ([]storage.ConsumerPosition, error)
- func (s *Server) ConsumerShadow(ctx context.Context, workspaceID, consumer, entity, key string) ([]byte, error)
- func (s *Server) CurrentSeq(ctx context.Context, workspaceID string) (uint64, error)
- func (s *Server) DeleteWorkspace(ctx context.Context, workspaceID string) error
- func (s *Server) Entities() []EntityMeta
- func (s *Server) Entity(name string) (EntityMeta, bool)
- func (s *Server) EntityKey(msg proto.Message) (entity, key string, err error)
- func (s *Server) GetChunk(ctx context.Context, req *connect.Request[syncplanev1.GetChunkRequest]) (*connect.Response[syncplanev1.GetChunkResponse], error)
- func (s *Server) HTTPHandler() http.Handler
- func (s *Server) Handler() (string, http.Handler)
- func (s *Server) Handlers() map[string]http.Handler
- func (s *Server) Invoke(ctx context.Context, workspaceID, mutatorName string, args proto.Message) error
- func (s *Server) InvokeIdempotent(ctx context.Context, workspaceID, key, mutatorName string, args proto.Message) (WriteOutcome, error)
- func (s *Server) Leases() lease.Locker
- func (s *Server) Mutate(ctx context.Context, workspaceID string, fn func(tx *EntityTx) error) error
- func (s *Server) MutateIdempotent(ctx context.Context, workspaceID, key string, ...) (WriteOutcome, error)
- func (s *Server) PendingWorkspaces(ctx context.Context, consumer string) iter.Seq2[string, error]
- func (s *Server) PresenceHandler() (string, http.Handler)
- func (s *Server) Publish(ctx context.Context, req *connect.Request[syncplanev1.PublishRequest]) (*connect.Response[syncplanev1.PublishResponse], error)
- func (s *Server) Pull(ctx context.Context, req *connect.Request[syncplanev1.PullRequest]) (res *connect.Response[syncplanev1.PullResponse], err error)
- func (s *Server) Push(ctx context.Context, req *connect.Request[syncplanev1.PushRequest]) (*connect.Response[syncplanev1.PushResponse], error)
- func (s *Server) PutChunk(ctx context.Context, req *connect.Request[syncplanev1.PutChunkRequest]) (*connect.Response[syncplanev1.PutChunkResponse], error)
- func (s *Server) Query(ctx context.Context, req *connect.Request[syncplanev1.QueryRequest]) (res *connect.Response[syncplanev1.QueryResponse], err error)
- func (s *Server) ReadState(ctx context.Context, workspaceID string, fn func(tx storage.ReadTx) error) error
- func (s *Server) ReferencedBlobs(ctx context.Context, workspaceID string, want []blob.Digest, ...) (map[blob.Digest]bool, error)
- func (s *Server) RegisterDescriptorSet(set []byte, opts ...RegisterOption) ([]string, error)
- func (s *Server) RegisterDynamicEntities(specs ...DynamicEntity) error
- func (s *Server) RegisterDynamicEntity(spec DynamicEntity, opts ...RegisterOption) error
- func (s *Server) RegisterEntity(msg proto.Message, opts ...RegisterOption) error
- func (s *Server) Replicate(ctx context.Context, workspaceID string, fn func(tx *ReplicaTx) error) error
- func (s *Server) ResetConsumer(ctx context.Context, workspaceID, consumer string) error
- func (s *Server) RestoreWorkspace(ctx context.Context, workspaceID string) error
- func (s *Server) SchemaRevision() string
- func (s *Server) StatBlobs(ctx context.Context, req *connect.Request[syncplanev1.StatBlobsRequest]) (*connect.Response[syncplanev1.StatBlobsResponse], error)
- func (s *Server) Subscribe(ctx context.Context, req *connect.Request[syncplanev1.SubscribeRequest], ...) error
- func (s *Server) SubscribeActivity() (ids <-chan string, cancel func(), ok bool)
- func (s *Server) SubscribeChanges(workspaceID string) (<-chan struct{}, func())
- func (s *Server) View(ctx context.Context, workspaceID string, fn func(tx *ViewTx) error) error
- func (s *Server) Watch(ctx context.Context, req *connect.Request[syncplanev1.WatchRequest], ...) error
- func (s *Server) WatchBlobs(ctx context.Context, req *connect.Request[syncplanev1.WatchBlobsRequest], ...) error
- func (s *Server) WorkspaceIDs(ctx context.Context) ([]string, error)
- type ViewTx
- func (v *ViewTx) Get(dst proto.Message, key string) (found bool, version uint64, err error)
- func (v *ViewTx) GetMeta(dst proto.Message, key string) (found bool, meta RowMeta, err error)
- func (v *ViewTx) Query(prototype proto.Message, spec query.Spec, ...) error
- func (v *ViewTx) ScanPage(prototype proto.Message, afterKey string, limit int, ...) (lastKey string, more bool, err error)
- type WorkspaceDenial
- type Write
- type WriteCapture
- type WriteOption
- type WriteOutcome
- type Writer
Examples ¶
Constants ¶
const ( // CodePermissionDenied rejects a mutation the caller may not perform. CodePermissionDenied = "permission_denied" // CodeAccessDenied rejects a mutation the schema's access model refuses: // no access rule of the entity admits the write for the caller, the caller // grants a role it does not hold, a move needs a read permission the caller // lacks, a mutator's MutatorAccess does not hold, or the entity has no // rule for the operation. The application's own permission hooks refuse // with CodePermissionDenied, except the default row check: on an entity of // the access model, a write to a row ReadFilter hides gets CodeAccessDenied, // as a write to a missing row does. The message names only what the caller // sent; the server logs why at debug level, as "access refused". CodeAccessDenied = "access_denied" // CodeInvalidArgument rejects a mutation whose payload is semantically // invalid for the application. CodeInvalidArgument = "invalid_argument" // CodeConflict rejects a mutation that lost a business-level conflict // (e.g. uniqueness, state machine). CodeConflict = "conflict" // CodeTextFullStateRequired rejects a mutation whose collaborative-text // PATCH carried a delta-state fragment the server could not apply — the // fragment was cut against a state this row is not (or no longer) built on. // Nothing is wrong with the write itself: the client re-sends the same edit // carrying the full document and it lands. Like every rejection it consumes // no sequence and rolls the savepoint back, so the row is untouched. CodeTextFullStateRequired = "text_full_state_required" // CodeTextStateStale rejects a mutation whose collaborative-text value is // built on state a compaction has dropped (see engine/text.Compact): it // would put back characters the document purged, or hangs new text off one // of them. Resending the same bytes cannot help — unlike // CodeTextFullStateRequired, which asks for MORE of the same state. The // client has to re-read the row and re-apply its edit against it, which // costs the marks the stale side had minted. Consumes no sequence. CodeTextStateStale = "text_state_stale" // CodeWorkspaceAccessRevoked reports that the caller may not access the // workspace and that this is PERMANENT — the answer will not change by // retrying. Unlike the codes above it never rides on a MutationResult: it // denies a whole workspace (see DenyWorkspace, and DeleteWorkspace, which // refuses every request to the workspace it deletes), so it arrives as an RPC // error on the single-workspace RPCs, as a WorkspaceResults.error_code on // Push, and as a WorkspaceDropped frame on Subscribe. A client seeing it // should stop syncing that workspace and discard its local copy rather than // back off and retry. CodeWorkspaceAccessRevoked = "workspace_access_revoked" // CodeWorkspaceNoAccess reports that the caller holds no permission in the // workspace's access model. Unlike CodeWorkspaceAccessRevoked it is not // permanent: a grant row written later admits the caller. It arrives where // CodeWorkspaceAccessRevoked does, and as a WorkspaceDropped frame with // reason NO_ACCESS on Subscribe. A client seeing it keeps its local copy and // its queue, and retries with backoff. A Pull from a cursor issued while // the caller held a permission gets it only after a page that tombstones // the rows the caller read and sets has_more. CodeWorkspaceNoAccess = "workspace_no_access" )
Machine-readable rejection codes shared between server and client. The TS client mirrors these in client/src/codes.ts; keep both in sync. Applications may define their own codes, but should prefer these for the common cases so generic client UI can react uniformly.
const ( // CodeMutationIDGap reports that a batch's mutation ids were not contiguous // with the server's watermark for that client, so NOTHING in the batch was // applied. The client resends in order from its watermark. Deterministic: // retrying the identical batch fails identically. CodeMutationIDGap = "mutation_id_gap" // CodeClientIDInUse reports that the client's watermark is above the // highest id the batch says the client sent (WorkspaceBatch.sent_through), // so another writer used the client_id, and NOTHING in the batch was // applied. The client must stop pushing under the client_id and resend its // queue under a new one. Deterministic: retrying the identical batch fails // identically. CodeClientIDInUse = "client_id_in_use" // CodeWorkspaceReplaced reports that the batch's basis cursor names // another store history than the workspace's current one // (WorkspaceBatch.basis): the workspace was deleted and restored, or the // server serves another store. NOTHING in the batch was applied. The // client drops the queue it wrote against that cursor. Deterministic. CodeWorkspaceReplaced = "workspace_replaced" // CodeInternal reports a failure the caller cannot act on and that may not // persist — a storage error, or a permission hook that could not decide. // Retry with backoff. It never means "denied": a denial is always typed. CodeInternal = "internal" // CodeMutationFailed reports that a custom mutator returned an error that // is not a Reject, so NOTHING in the batch was applied. The message names // the mutator and the mutation id; the error itself is logged on the // server only. A retry can succeed only if the mutator's answer changes, // so the client counts repeats of it toward dropping the mutation, and // never counts CodeInternal. CodeMutationFailed = "mutation_failed" )
Workspace-scoped failure codes. These appear on WorkspaceResults.error_code, where a failure belongs to ONE workspace of a multi-workspace request and must not be reported as a failure of the request. CodeWorkspaceAccessRevoked above is used the same way.
const DefaultTextCacheBytes = 8 << 20
DefaultTextCacheBytes is how much encoded text state a server keeps decoded when WithTextCache is not set.
The budget counts ENCODED bytes; a decoded document costs several times that in live heap (a node, a child slice and an id per code point), so the real ceiling is a multiple of this number. It is deliberately small: the value of the cache is almost entirely in the most recent write to each actively edited field, so a few megabytes covers every document a workspace is being typed into at once, and going wider buys little.
const ErrorCodeMetadataKey = "syncplane-error-code"
ErrorCodeMetadataKey is the response-metadata key carrying a machine-readable code (one of the constants above) on an RPC-level error. Connect exposes it to clients as error metadata; the TS client reads it off ConnectError.
RPC errors carry a Connect code, which is coarse — several conditions map to permission_denied — so this key is what lets a client branch on WHICH denial it hit without matching on message text.
const HistoryForever time.Duration = -1
HistoryForever disables time-based expiry of field-history records: a record then lives exactly as long as the row it describes, since a DELETE of that row purges its history whatever the retention.
Pass it to WithHistoryRetention when history is app-visible data with no natural age limit. The cost is that a hot row's log grows without bound for as long as the row lives, so it suits entities whose rows are edited by people rather than rewritten by machinery.
const HistorySessionOff time.Duration = -1
HistorySessionOff turns session folding off: every write that changes a captured field gets a record of its own. Pass it to WithHistorySession when each write to a field has to be separately restorable, rather than only the state a run of writes began from. On an entity carrying a collaborative-text field that is one record per keystroke, each carrying the whole text.
It does not make the log an audit trail. A DELETE is still uncaptured and still purges the row's records (see purgeHistory), so the log answers what a field held, never what happened to the row.
const MaxConsumerNameBytes = 128
MaxConsumerNameBytes bounds an effect consumer's name. The name is the identity of a durable position and is stored per workspace, so the bound is what keeps a caller-supplied string from becoming unbounded storage. It is generous against anything a human names a consumer.
const MaxIdempotencyKeyBytes = 256
MaxIdempotencyKeyBytes bounds a trusted write's idempotency key. Keys are stored per workspace and never truncated, so the bound is what keeps a caller-supplied string from becoming unbounded storage. It is generous against everything real keys are made of — a UUID, a change-feed sequence, a provider's event id.
A key must also be valid UTF-8 without U+0000; MutateIdempotent, InvokeIdempotent and ApplyIdempotent refuse any other key before they run the write.
const ReservedConsumerPrefix = "syncplane."
ReservedConsumerPrefix starts the consumer names the engine keeps for its own state. Every method that takes a consumer name refuses one that starts with it.
const ReservedWorkspacePrefix = "#syncplane."
ReservedWorkspacePrefix starts the ids of workspaces that hold only the engine's own state, such as a replication link's list of linked workspaces. WorkspaceIDs, ConsumerPendingWorkspaces and PendingWorkspaces leave them out, and the wire API refuses them, as it refuses every id that is not a valid workspace id.
Variables ¶
var ErrConsumerMoved = errors.New("server: consumer position moved since the update was read")
ErrConsumerMoved is returned by AdvanceConsumer when ConsumerUpdate.From is set and the consumer's stored position is no longer From: another pass committed since the caller read it. Nothing is recorded. The caller's shadows were derived against the older position, so it reads the position again before it continues.
var ErrCursorForeign = fmt.Errorf("%w: the cursor names a history this store does not hold", ErrCursorTooOld)
ErrCursorForeign is the ErrCursorTooOld that Changes returns when the cursor names a history this store does not hold: another store lineage (see Cursor.Epoch), a sequence above the current one, or a write the store does not hold (see Cursor.Lineage). That is the case after a swap of the store, a restore from backup, or a DeleteWorkspace and RestoreWorkspace. It wraps ErrCursorTooOld, so errors.Is matches both.
The two call for different recoveries. Below the horizon, the history the consumer read is still this store's history, and state the consumer derived from it stays a valid base for the resync. After ErrCursorForeign, that state describes a history the store does not hold: discard it, and resync as on a first run.
var ErrCursorTooOld = errors.New("server: feed cursor cannot be resumed against this store")
ErrCursorTooOld reports a feed cursor that cannot be resumed against this store: it sits below the workspace's tombstone horizon, above its current sequence, names a different store lineage (see Cursor.Epoch), or names a write the store does not hold (see Cursor.Lineage). A cursor AT the horizon that carries a sub-position (Entity/Key set) counts as below it: the rows of that sequence after the sub-position were never delivered. Deletions the consumer never saw may have been garbage-collected, and rows above the cursor may belong to a history it never observed, so only a full resync against current state recovers. After resyncing, resume from the cursor Changes returned alongside this error.
ErrEpochUnavailable is returned by ReadFilterAt when the filter at the requested epoch can no longer be reconstructed. The affected client falls back to a full reset (re-bootstrap), exactly as if the app did not implement EpochReadFilters.
var ErrNoAccess error = DenyWorkspace("the caller holds no permission in this workspace")
ErrNoAccess is the denial for a caller who holds no permission in a workspace whose schema declares a role. It is a WorkspaceDenial, so AsWorkspaceDenial matches it, and test for it with errors.Is. Unlike other denials it is not permanent: a grant row written later admits the caller, and the wire carries it as CodeWorkspaceNoAccess.
var ErrUnauthenticated = errors.New("server: unauthenticated")
ErrUnauthenticated is the sentinel an Authenticator returns to reject a request outright. The engine maps it (and anything wrapping it) to Connect's unauthenticated code, which is HTTP 401.
Wrap it to explain the failure — errors.Join or fmt.Errorf("%w") both work:
return Principal{}, fmt.Errorf("%w: token expired", server.ErrUnauthenticated)
The wrapped message is logged but never sent to the client: a credential verifier's reasons are an oracle, so the wire carries a fixed message.
var ErrUnknownPermission = errors.New("server: no role grants the permission")
ErrUnknownPermission is returned by EntityTx.Can for a permission that no role of the schema grants, which no caller can hold.
var ErrWorkspaceDeleted = storage.ErrWorkspaceDeleted
ErrWorkspaceDeleted reports that DeleteWorkspace deleted the workspace and RestoreWorkspace has not restored it since. Test for it with errors.Is.
The workspace gate refuses every request to a deleted workspace with a WorkspaceDenial that wraps it, so AsWorkspaceDenial also matches, and a sync client receives the permanent denial (CodeWorkspaceAccessRevoked). A Trusted call skips the gate: its write fails with an error that wraps ErrWorkspaceDeleted but is not a WorkspaceDenial, and its read sees an empty workspace.
Functions ¶
func ApplyTextStrings ¶
ApplyTextStrings rewrites each named collaborative-text field of dst from a plain string. texts maps dotted proto paths to the desired visible text; a document inside a keyed list or map element is named by its instance path ("items.<key>.body"), and dst must already carry the addressed element — the write cannot invent an element from its key alone.
Each string is diffed (multi-hunk, see text.SetString) against the field's document in base — the last state the writer observed — falling back to cur and then to an empty document; the result is then unioned with cur's document, so concurrent edits the writer never saw survive. An empty string deletes all visible text (concurrent inserts still survive the union).
peer is the writer identity the diff's operations are minted under, and the caller owes the text package's peer-uniqueness contract: two writers that can run concurrently must never share one. Reusing a peer across calls is sound exactly when cur is read inside the same serialized write transaction as the write — then cur always carries the peer's earlier operations, and observing cur's version before diffing keeps fresh counters past them. The connector's `connector:<writerID>` identity is the model.
func BuildDynamicFile ¶
func BuildDynamicFile(specs ...DynamicEntity) (protoreflect.FileDescriptor, error)
BuildDynamicFile synthesizes one proto file holding every entity in specs as a top-level message (with its (syncplane.v1.entity) options and nested non-entity types) and returns the resolved file descriptor. Building all entities into a SINGLE file is what lets references resolve: intra-file type names are always legal, so self, forward, and mutual references work regardless of declaration order, with no circular file-import graph for protodesc to reject. The only dependency is syncplane/v1/options.proto, resolved against the global registry.
func BuildDynamicMessageType ¶
func BuildDynamicMessageType(spec DynamicEntity) (protoreflect.MessageType, error)
BuildDynamicMessageType synthesizes a proto message type from a single runtime schema and returns it as a dynamicpb message type. See BuildDynamicFile for the multi-entity form that resolves cross-entity references; a lone spec may still reference itself.
The message carries (syncplane.v1.entity) options (and per-field (syncplane.v1.field_behavior) options) resolved against the process's extension registry, so proto.GetExtension on the resulting descriptor returns populated options. It does not touch the global registry.
func Delete ¶ added in v0.3.0
Delete deletes the row of T's entity with the given key, as the handle's own Delete does. It returns an error when T is an interface type or not a registered entity.
func DenyRoom ¶
DenyRoom builds the permanent denial CanJoinRoom returns when the caller may not be in the room.
Return it only when the answer is settled. A lookup that FAILED must return its underlying error instead: that drops the topic as a retryable error, where a denial tells the client to stop asking.
func DenyWorkspace ¶
DenyWorkspace builds the permanent denial CanAccessWorkspace returns when the caller is not (or is no longer) entitled to the workspace.
Return it only when the answer is settled. A membership lookup that FAILED must return its underlying error instead: that surfaces as an infrastructure error the client retries, where a denial would have it discard real data over a transient outage.
func Get ¶ added in v0.3.0
Get reads the row of T's entity with the given key, as the handle's own Get does. It returns the zero T and false for a row that does not exist, is deleted, or is hidden from the caller.
T is a generated message type, such as *todov1.Todo. Get returns an error when T is an interface type or not a registered entity, and on an ApplyTx for a key the closure has already written.
func Query ¶ added in v0.3.0
Query yields the live rows of T's entity that match spec, in spec's order, each as a new T. It answers as the handle's own Query does, with the same errors and the same cost; see ViewTx.Query. An error ends the sequence: Query yields it with the zero T and stops.
The whole result is read before the first row is yielded, so the loop body may read and write through tx, and no write it makes changes which rows are yielded.
for todo, err := range server.Query[*todov1.Todo](tx, query.Spec{
Where: query.Eq("completed", false),
}) {
…
}
func RefKeyFields ¶
func RefKeyFields(fd protoreflect.FieldDescriptor) []protoreflect.FieldDescriptor
RefKeyFields classifies a field as a typed reference to one entity: it returns the target entity's key fields when fd is a reference (a message field whose target message carries (syncplane.v1.entity), or a reference message wrapping one), else nil — also for a polymorphic reference message, which has one key set per case. The fields are the target's own; on a reference message they sit under Reference.Value rather than on the stored value — see RefOf. It is a thin re-export of lww.RefKeyFields so the admin form renderer can distinguish scalar / sub-message / reference fields without importing engine/internal/lww.
func Scan ¶ added in v0.3.0
Scan yields every live row of T's entity in key order, each as a new T. An error ends the sequence: Scan yields it with the zero T and stops.
Scan reads in pages of key order, and the loop body runs between pages, so the body may read and write through tx. Through an ApplyTx the writes are recorded and no later step yields them; through an EntityTx a later step may yield a row the body wrote, with its new value.
for todo, err := range server.Scan[*todov1.Todo](tx) {
if err != nil {
return err
}
…
}
T is a generated message type, such as *todov1.Todo. Scan yields an error when T is an interface type or not a registered entity.
func ScanRows ¶ added in v0.3.0
ScanRows is Scan, yielding each row's RowMeta with it. Hand Version back through WithExpectedVersion, or Patch's expected argument, to make a write a compare-and-swap.
func Trusted ¶
Trusted marks ctx as system work, exempting it from the permission hooks and from the access rules.
A trusted call holds every permission, and EntityTx.Can reports true for it. Every write path still refuses an invalid grant row, trusted ones included: a row with an empty subject, an undeclared role, or no access parent on a grant entity that declares one.
The in-process write and read APIs — Apply, Mutate, Invoke, View — authorize against the ctx principal by default, so an app handler that forgot to authenticate is denied rather than silently admitted. Machinery that has no caller to authorize — a connector reconciling an external source, a migration, a cron job, the admin UI on its private listener — has no principal to offer and would be denied by any real policy. It says so here:
srv.Mutate(server.Trusted(ctx), ws, func(tx *server.EntityTx) error { … })
The engine short-circuits on this marker and never consults Permissions at all, rather than synthesizing a system Principal for policies to recognize. A policy that has to know about an engine-internal identity is a policy that can get it wrong, and the failure would be silent; this way the bypass is one greppable call at the site that takes it.
Forgetting it fails SAFE: unmarked system code authorizes as the anonymous principal, which a deny-by-default policy refuses, so the connector's first reconcile pass errors loudly instead of writing unauthorized. That is the whole reason the bypass is opt-in rather than the default.
It marks the ctx, not the server, so it does not leak: a ctx derived from a request keeps the request's principal for attribution while exempting this one call.
func TrustedAs ¶
TrustedAs marks ctx as system work like Trusted does, and additionally names the machinery taking the bypass so its writes are attributable:
srv.Mutate(server.TrustedAs(ctx, "connect:markdown"), ws, func(…) error { … })
The name is recorded on every row the call writes and surfaces on the change feed as Actor{System: name}. It is a label the operator chooses, never an identity: nothing verifies it and no policy runs against it (a trusted call skips the hooks entirely — that is what Trusted means). What it buys is a feed consumer that can recognize its own writes and not react to them, and an operator who can tell which pass wrote a row.
A principal on the ctx is recorded alongside the name: a bypass taken inside a request records both the label and the caller whose request it ran under. Names longer than 64 bytes are truncated; one carrying a control character or invalid UTF-8 records "system".
Prefer it over bare Trusted for anything that writes on a schedule or in a loop. Trusted stays correct and is the right call for one-off work with nothing to distinguish; its rows record Actor{System: "system"}.
func WithPrincipal ¶
WithPrincipal returns a ctx carrying p as the caller's verified identity.
The engine's authentication interceptor calls this for you (see WithAuthenticator). Call it directly when authentication happens in your own HTTP middleware instead — that is the supported hand-off, and the only one: the permission hooks read the principal the engine finds here, so a middleware that stashes an identity under its own ctx key is invisible to them.
It is also how a server-side caller says who it is acting as. The in-process API — Apply, Mutate, Invoke, View — authorizes against the principal it finds here, so a background job or an API handler that authenticated for itself puts the resulting identity on the ctx and is then held to the same policy a sync client is. A ctx with no principal authorizes as anonymous.
A ctx principal reaches only what runs SYNCHRONOUSLY within the writing ctx: the permission hooks, mutator bodies, post-commit work the writer itself performs. It does not reach the change feed — a feed consumer drains on its own ctx, on its own schedule, so it never sees the writing ctx at all. What crosses that boundary is the actor recorded on the row (see storage.Actor and Change.Actor), and only Subject does: Issuer and Claims stay live inputs to policy and are never stored.
Work with no caller to authorize marks its ctx with Trusted instead, which skips the hooks; the two compose, so a ctx can carry a principal for attribution while a single call opts out of enforcement.
Types ¶
type AllowAll ¶
type AllowAll struct{}
AllowAll is the default Permissions implementation: every caller may do everything. It is the right default for the engine's original posture — embedded behind an app that already authenticated and authorized the request — and the wrong one for anything reachable by untrusted traffic.
Embed it to implement only the hooks you need; the promoted methods satisfy the rest, so a policy that only rejects writes needs one method:
type policy struct{ server.AllowAll }
func (policy) CanMutate(_ context.Context, p server.Principal, ws string, w server.Write) error {
if p.IsAnonymous() {
return server.Reject(server.CodePermissionDenied, "sign in to make changes")
}
return nil
}
That inherits allow-all reads and a constant zero epoch, so an embedding policy never meets the epoch machinery until it needs it. It also means new hooks added to Permissions arrive as allow-all rather than as a compile error — convenient, but check the release notes when upgrading, since a silently-inherited default on a new hook is an authorization decision you did not make.
The workspace gate is the one to think twice about ¶
AllowAll.CanAccessWorkspace admits every caller into every workspace. That is correct for a single-tenant deployment and WRONG for a shared one: since workspace_id is self-asserted, inheriting this hook means any caller who reaches the server can name any workspace and be served it. A multi-tenant deployment must override CanAccessWorkspace — embedding AllowAll will not tell you that you forgot.
It is also what makes AllowAll unsafe behind an app's own API: the in-process paths authorize like the sync surface does, so a handler that forgot to authenticate is caught by a real policy (it authorizes as anonymous) and waved through by this one.
func (AllowAll) CanAccessWorkspace ¶
func (AllowAll) FilterEpoch ¶
type AllowAllRooms ¶
type AllowAllRooms struct{}
AllowAllRooms is the permissive RoomPermissions: every caller who cleared the room's own gate may join, and sees everyone. Embed it to implement only the hook you need:
type policy struct {
server.AllowAll
server.AllowAllRooms
}
func (policy) VisibleParticipants(
_ context.Context, p server.Principal, _ string, _ presence.Topic,
) (server.ParticipantFilter, error) {
if p.IsAnonymous() {
return func(string) bool { return false }, nil
}
return nil, nil
}
func (AllowAllRooms) CanJoinRoom ¶
func (AllowAllRooms) VisibleParticipants ¶
func (AllowAllRooms) VisibleParticipants( context.Context, Principal, string, presence.Topic, ) (ParticipantFilter, error)
type AppSchema ¶
AppSchema is one app's persisted registration: the serialized google.protobuf.FileDescriptorSet it registered, the revision the engine derived from it, and when it was last written.
type ApplyTx ¶
type ApplyTx struct {
// contains filtered or unexported fields
}
ApplyTx is the transaction facade Apply's closure runs against: reads are served from a consistent snapshot, writes are recorded and applied after the closure returns.
The write methods mirror EntityTx exactly — same arguments, same merge semantics, same rejections — so code moves between a mutator and an Apply closure unchanged. What differs is when they take effect, and that reads do not see them (see Apply).
func (*ApplyTx) Get ¶
Get loads the row with the given key into dst and reports whether a live row was found and the sequence (version) it was last written at, so the result can be handed straight back to a compare-and-swap Patch. A missing or deleted row returns (false, 0, nil).
Reading a key this closure has already written is an ERROR, not a stale read. Apply does not maintain a read-your-own-writes overlay, and silently answering with the pre-write row is the one outcome that would be wrong without saying so. Track the value you wrote yourself, or use Mutate if you genuinely need to read back mid-transaction.
func (*ApplyTx) GetMeta ¶
GetMeta is Get, reporting the row's whole RowMeta instead of its version alone — the read that answers "who last wrote this". A missing or deleted row returns (false, RowMeta{}, nil), and reading a key this closure has already written is an error, exactly as in Get.
func (*ApplyTx) Patch ¶
func (a *ApplyTx) Patch(msg proto.Message, mask []string, expected *uint64, opts ...WriteOption) error
Patch records a masked merge onto the stored row, with EntityTx.Patch's semantics: per-field LWW over the named paths, PATCH is not an upsert, and a non-nil expected makes it a compare-and-swap.
The version you read through this same closure is the right thing to pass as expected — that is how a read-modify-write here notices a concurrent edit instead of silently merging with it. Without it, the merge follows arrival order like any other write.
The conflict, mask and key-field rejections all surface when the write applies, after the closure returns, so they come back from Apply rather than from this call.
func (*ApplyTx) Put ¶
func (a *ApplyTx) Put(msg proto.Message, opts ...WriteOption) error
Put records a full-row snapshot write; the key derives from key_fields. It takes effect after the closure returns, with EntityTx.Put's semantics — including the collaborative-text exception, where text fields union with the stored document rather than replacing it, and the stored top-level fields the schema does not declare, which it keeps. That merge happens against the row as it stands at apply time, not as the snapshot saw it, which is what keeps a concurrent editor's work from being dropped.
WithExpectedVersion makes it a compare-and-swap against the row at apply time, so the conflict surfaces from Apply rather than from this call. The version read through this same closure is the right thing to pass.
func (*ApplyTx) Query ¶
func (a *ApplyTx) Query(prototype proto.Message, spec query.Spec, fn func(msg proto.Message, version uint64) error) error
Query iterates the live rows matching spec, in spec's order, decoding each into a fresh message and passing it with its version — the "find everything matching X and write to it" read. It is the same compiled predicate the Query RPC and the TS client use.
A declared secondary index serves it when one covers the predicate and ordering; otherwise it is a full scan of the entity. A spec with no Limit holds every match in memory either way; see query.Spec. Unlike EntityTx.Query it does NOT run under the workspace write lock, so a broad query here blocks no other writer.
A spec that names a field the caller does not read on every row fails as on ViewTx.Query. Recorded writes are not visible to it (see Apply).
func (*ApplyTx) ScanPage ¶
func (a *ApplyTx) ScanPage(prototype proto.Message, afterKey string, limit int, fn func(msg proto.Message, version uint64) error) (lastKey string, more bool, err error)
ScanPage iterates up to limit live rows of the entity identified by prototype with key > afterKey, in key order, decoding each into a fresh message and passing it with its version. It returns the key of the last row visited and whether more rows follow; pass lastKey back as afterKey to continue. limit must be positive.
Rows this closure has recorded writes for are returned as they were in the snapshot; recorded writes are not visible to any read (see Apply).
type Authenticator ¶
type Authenticator interface {
Authenticate(ctx context.Context, header http.Header) (Principal, error)
}
Authenticator turns a request's headers into a verified Principal. It is the engine's authentication seam: install one with WithAuthenticator and the server runs it ahead of every sync RPC, stashing the result where the permission hooks receive it.
The engine calls Authenticate on the public sync surface only (Server.Handler and, through it, Manager.SyncHandler). It never runs for trusted server-side paths — Server.Mutate, Server.Invoke, the admin service — which have no request to authenticate; those are gated by reachability and, for the admin service, by RegisterAuthorizer.
Contract ¶
- Return a Principal with a non-empty Subject to admit an identified caller.
- Return the zero Principal and a nil error to admit an ANONYMOUS caller. Do this deliberately: it hands the request to the permission hooks with no identity, and the default AllowAll policy allows everything.
- Return ErrUnauthenticated (or an error wrapping it) to reject the request as 401.
- Return any other error to fail the request as an infrastructure fault (internal, HTTP 500) — the right outcome when the identity provider is unreachable, since answering "unauthenticated" would let a client treat a transient outage as a credential problem and discard its session.
Authenticate runs on the request's hot path, before the handler and before any storage work. Keep it fast: verify a signature locally and cache introspection results rather than calling out per request.
Implementations must be safe for concurrent use.
func StaticTokenAuthenticator ¶
func StaticTokenAuthenticator(tokens map[string]Principal) Authenticator
StaticTokenAuthenticator admits a request iff it carries "Authorization: Bearer <token>" for one of the given tokens, and returns that token's Principal. It is the smallest useful Authenticator: fixed API keys for a handful of trusted callers (a backend service, a CLI, an integration test), with no identity provider in the loop.
It is NOT a login system. Tokens are long-lived shared secrets with no expiry, no rotation and no revocation short of restarting with a different map, so it does not fit end-user traffic — that wants a real credential (a signed JWT verified against a JWKS, or a session cookie your middleware resolves) behind the same Authenticator interface.
An empty map, an empty token, or a request with no bearer token all reject with ErrUnauthenticated, so a misconfigured deployment fails closed rather than admitting everyone as anonymous.
The returned Principal is the caller's, verbatim; give each token a distinct Subject so policies and logs can tell callers apart. A Principal with an empty Subject would admit that token's holder as anonymous, which is almost never intended.
type AuthenticatorFunc ¶
AuthenticatorFunc adapts a plain function to Authenticator.
func (AuthenticatorFunc) Authenticate ¶
type BlobPermissions ¶ added in v0.4.0
type BlobPermissions interface {
// CanUploadBlob admits or refuses the upload of a blob of size bytes. The
// engine calls it from BeginUpload, after the workspace gate admitted the
// caller and the request was found valid, and not for a Trusted ctx.
// PutChunk does not call it: a chunk only completes an upload that a
// BeginUpload started, and it must match the hash that call gave.
//
// Return a Rejection (see Reject) for a settled no. It reaches the client
// as permission_denied, with the Rejection's code under
// ErrorCodeMetadataKey and its message as the error message. An error
// that carries a Connect code reaches the client unchanged; any other
// error is internal, which a client retries.
CanUploadBlob(ctx context.Context, p Principal, workspaceID string, size int64) error
}
BlobPermissions is an optional Permissions extension that decides who may upload blobs. A Permissions that does not implement it lets every caller admitted to the workspace upload a blob up to Limits.MaxBlobBytes.
Who may READ a blob is not decided here: a caller reads a blob when it reads a row that refers to it.
type CallerAccess ¶ added in v0.2.0
type CallerAccess struct {
// Subjects are the values a grant row's subject field may hold for the row
// to apply to the caller. The first non-empty one is the caller's primary
// subject: an enforced create stores it in each field marked
// (syncplane.v1.field_behavior).creator. Empty strings are ignored, so an
// empty subject never matches a grant row.
Subjects []string
// RootRoles are roles the caller holds at the root of the workspace, in
// addition to what its grant rows give. A role that no grant option of the
// schema declares grants nothing, and the server logs a warning for it.
RootRoles []string
}
CallerAccess is what a caller is in the access model of one workspace. The zero value is a caller with no subjects and no roles at the root.
type CallerAccessFunc ¶ added in v0.2.0
type CallerAccessFunc func(ctx context.Context, p Principal, workspaceID string) (CallerAccess, error)
CallerAccessFunc returns what the caller p is in the access model of the workspace workspaceID. See WithCallerAccess.
type CapturedOp ¶ added in v0.6.0
type CapturedOp struct {
Entity string
Key string
Op syncplanev1.CrudOp
// Value is the value the write submitted, encoded, nil for a DELETE. For a
// PUT it holds the stored value of each field the caller may not write,
// and each plain-string text value resolved to a document. A
// collaborative-text field holds the submitted document or fragment, not
// the union stored in After.
Value []byte
// Mask is the PATCH field mask the write merged. For a PUT it names the
// units the write replaced: the field mask the PUT named, or else every
// top-level field and oneof the caller may write, or the key fields alone
// when the caller may write none of them. It is nil for a DELETE, and for a
// PUT that did not come from a client push.
Mask []string
// ExpectedVersion is the version the write required the row to be at, nil
// for an unguarded write.
ExpectedVersion *uint64
// PrevVersion is the row's version before the write, 0 when the row was
// absent or deleted.
PrevVersion uint64
// Before is the row's stored value before the write, nil when the row was
// absent or deleted. A later write of the same mutation to the same row
// sees what the earlier one stored.
Before []byte
// After is the row's stored value after the write, nil when the write
// deleted it.
After []byte
}
CapturedOp is one row write of a CapturedWrite.
type CapturedWrite ¶ added in v0.6.0
type CapturedWrite struct {
// Workspace is the workspace the mutation wrote to.
Workspace string
// Seq is the sequence the mutation's rows were written at, or 0 when it
// wrote none and was assigned none.
Seq uint64
// Actor is who the mutation's rows are attributed to (see storage.Actor).
Actor storage.Actor
// Custom is the custom mutation that was invoked, nil for a CRUD write.
// Ops then holds the rows its mutator wrote, and is empty for a mutation
// that WithUnknownMutatorForwarding accepted.
Custom *syncplanev1.CustomMutation
// Ops are the row writes the mutation made, in the order they were made.
Ops []CapturedOp
// Origin is the client mutation this write applied, nil for a write that
// did not come from a client push (Apply, Mutate, Invoke and their
// idempotent forms).
Origin *MutationOrigin
// Tx is the mutation's write transaction. What the capture writes through
// it commits or rolls back with the mutation. A row written through it
// skips every derived structure the engine keeps, so use it for consumer
// shadows (see storage.WriteTx.PutConsumerShadow), not for rows.
Tx storage.WriteTx
}
CapturedWrite is one mutation as a WriteCapture sees it. Its fields, and the slices they hold, are valid only for the duration of the call.
type Change ¶
type Change struct {
Entity string
Key string
// Seq is the workspace sequence of the mutation that wrote this state.
// Several rows share a Seq when one mutation wrote them together.
Seq uint64
Deleted bool
// Message is the decoded row value. Nil when Deleted, and nil when the
// entity is not registered on this server (consumers still see the
// Entity/Key/Seq envelope).
Message proto.Message
// Actor is who made the write this change reports — the caller's subject
// for a client push or an in-process write, the label a write made under
// Trusted/TrustedAs gave itself, or both when a bypass ran inside a
// caller's request. The zero Actor means the write was unattributed: no
// authenticated caller made it, which is every push on a server with no
// Authenticator installed.
//
// It is the LAST writer of the row, not the writer of every change that
// coalesced into this one, because the feed reports state rather than
// transitions. That is enough to suppress a consumer's own echo and to
// answer "notify everyone except whoever did this"; it is NOT an audit
// trail, and a consumer that needs every writer must record its own.
//
// Suppressing by Actor therefore drops a genuine trigger when someone
// else's write is coalesced behind the consumer's own — the same blind spot
// a sequence watermark has (see engine/connect's Shadow.EngineVersion), and
// the reason a consumer that must not miss a change reacts to state instead.
Actor storage.Actor
}
Change is one committed row change observed through the feed.
type ConsumerShadowWrite ¶
ConsumerShadowWrite is one row's shadow update produced by a drained page: the snapshot a consumer wants to remember for (Entity, Key), or a deletion when Snapshot is nil. The bytes are opaque to the engine — the consumer decides what a shadow is and is the only thing that reads it back.
type ConsumerUpdate ¶
type ConsumerUpdate struct {
// Cursor is the position the consumer has now fully acted on. Its Epoch
// and Lineage are not retained and ConsumerPosition reads them back as 0:
// the position is held in the workspace's own store, so it is swapped or
// restored along with the changes it points into. AdvanceConsumer checks
// them against the store before it records the position (see
// ErrCursorForeign).
Cursor Cursor
// Shadows are the per-row snapshot writes to land with that position.
Shadows []ConsumerShadowWrite
// From, when set, is the position the caller read before it acted on the
// page, as ConsumerPosition returned it. AdvanceConsumer then records
// nothing and returns ErrConsumerMoved unless the stored position is still
// From. Only Seq, Entity and Key are compared, and a consumer with no
// position matches the zero cursor. Nil skips the check.
From *Cursor
}
ConsumerUpdate is the durable bookkeeping one drained page produces: how far the consumer got, and the shadows it derived along the way.
type Cursor ¶
type Cursor struct {
Seq uint64
Entity string
Key string
// Epoch names the store lineage that issued this cursor (see
// storage.ReadTx.StoreEpoch). Changes stamps it into every cursor it
// returns and answers one naming another lineage with ErrCursorTooOld, so
// a consumer whose cursor lives outside the engine store cannot resume
// against a database swapped or restored underneath it. 0 means the
// lineage is unknown and is always accepted, so bookkeeping that does not
// carry the field still works — without the check. The value is opaque and
// spans all 64 bits; whatever persists it must round-trip every one.
Epoch uint64
// Lineage names the write that allocated Seq (see
// storage.ReadTx.SeqLineage). Changes stamps it into every cursor it
// returns and answers one whose write the store does not hold with
// ErrCursorTooOld: the store was restored from a backup taken before Seq
// and written past it since, which Epoch cannot see because the backup
// carried it. 0 means unknown and is always accepted, as is a cursor whose
// Seq is older than the GC retention and below the workspace's current
// sequence. Opaque and 64 bits wide, like Epoch.
Lineage uint64
}
Cursor is a durable position in a workspace's change feed. It matches the (Version, Entity, Key) order of the underlying change scan: Seq is the last fully consumed sequence; Entity/Key mark a sub-position inside a same-sequence group when a page split one (empty on a clean boundary). The zero Cursor reads the feed from the beginning — but only while the workspace has collected no tombstones, since seq 0 sits below any nonzero horizon. A first run against an older workspace therefore starts with ErrCursorTooOld and the resync it asks for, not with a full replay.
type DenyAll ¶
type DenyAll struct{}
DenyAll rejects every registration. It is the default so a misconfigured deployment fails closed.
func (DenyAll) CanRegister ¶
func (DenyAll) CanRegister(context.Context, RegisterInfo) error
type DynamicEntity ¶
type DynamicEntity struct {
// Name is the wire/storage entity name (CrudMutation.entity), e.g. "todo".
// It must be unique within a server, exactly like a RegisterEntity name.
Name string
// Package namespaces the synthesized proto message so distinct dynamic
// entities get distinct proto full names. Defaults to "sync.dynamic". When
// several entities are built into one file (BuildDynamicFile) they must
// share a package.
Package string
// MessageName is the synthesized proto message name. Defaults to a
// CamelCase of Name (e.g. "task_list" -> "TaskList").
MessageName string
// KeyFields name the fields (in order) whose values form the row key,
// mirroring EntityOptions.key_fields. At least one is required, each must
// name a declared field, and each must be a singular scalar.
KeyFields []string
// Fields are the entity's proto fields. Field numbers must be positive and
// unique; names must be unique.
Fields []DynamicField
// Indexes are composite secondary indexes over this entity, mirroring
// EntityOptions.index. Declare one when a query FILTERS on one field and
// ORDERS by another — the shape a single DynamicField.Indexed mark can
// only serve by re-checking every candidate.
//
// Names must be unique within the entity and must not start with "__",
// which is reserved for indexes the engine derives for itself.
Indexes []DynamicIndex
// Access mirrors (syncplane.v1.entity).access: the rules that decide who
// reads and writes the entity's rows in the access model. Nil declares
// none. The entity keeps the pointer, so do not modify it after
// registration.
Access *syncplanev1.AccessOptions
// Grant mirrors (syncplane.v1.entity).grant and declares the entity's rows
// as grant rows. Nil declares none. A dynamic entity has no enum fields, so
// its role field is a string field. The entity keeps the pointer, so do
// not modify it after registration.
Grant *syncplanev1.GrantOptions
// Members mirrors (syncplane.v1.entity).members and declares the entity's
// rows as teams, whose members are the rows of the entity it names. Nil
// declares none. The entity keeps the pointer, so do not modify it after
// registration.
Members *syncplanev1.MembersOptions
}
DynamicEntity declares a syncable entity schema supplied at runtime, with no generated Go and no rebuild. Build it into a message type with BuildDynamicMessageType (or register it directly with Server.RegisterDynamicEntity); the resulting type is a dynamicpb message carrying the same (syncplane.v1.entity) options the compiled path reads off a generated descriptor, so the descriptor-driven engine treats it identically to a RegisterEntity'd type.
This is the CRUD-only "dynamic tier": the schema is declarative, so it can be provisioned at runtime, but custom Go mutators/mergers cannot — those are funcs and stay on the compiled path.
type DynamicField ¶
type DynamicField struct {
// Name is the proto field name (snake_case by convention).
Name string
// Number is the proto field number (positive, unique within the entity).
Number int32
// Kind is the scalar proto kind (StringKind, Int64Kind, BoolKind, ...) for a
// scalar field. Ignored for message/ref/map fields.
Kind protoreflect.Kind
// Repeated makes the field a list. For a scalar this is a scalar set; for an
// embedded Message with KeyField it is a keyed message list; for a Ref it is
// a to-many reference.
Repeated bool
// Opaque marks a field as replaced-whole during merges (the same
// (syncplane.v1.field_behavior).opaque the compiled path honours). Valid on a
// singular bytes field or a singular embedded Message.
Opaque bool
// Indexed maintains a single-component secondary index over this field (the
// same (syncplane.v1.field_behavior).indexed the compiled path honours), so
// filtering or ordering by it costs O(result) rather than a scan. Rejected
// on a text field and on any leaf a comparison could never reach.
Indexed bool
// Text marks a field as holding an encoded collaborative text document (the
// same (syncplane.v1.field_behavior).text the compiled path honours), so
// registration installs the text merger and concurrent edits merge instead
// of overwriting. Valid only on a singular bytes field, and mutually
// exclusive with Opaque.
Text bool
// Message declares an embedded (non-entity) sub-message: the field's element
// type is a nested message synthesized from these fields. Combined with
// Repeated + KeyField it is a keyed message list.
Message []DynamicField
// Ref names another entity (by DynamicEntity.Name) in the same registration;
// the field becomes a typed reference to it.
Ref string
// RefWorkspace stores a Ref as a reference message — `workspace_id` beside a
// `value` of the target type, the shape (syncplane.v1.reference) declares —
// so a stored value may name the workspace its target lives in. Ignored
// without Ref.
RefWorkspace bool
// ReverseRelation names the reverse relation a Ref adds to its target
// entity (the same (syncplane.v1.field_behavior).reverse_relation the
// compiled path honours). Empty means <plural(entity)>By<Field>, such as
// postsByAuthor. Valid only with Ref, on a field of the entity itself.
ReverseRelation string
// Creator makes the field record who created the row: an enforced create
// stores the caller's primary subject in it, and only a trusted write
// changes it afterwards (the same (syncplane.v1.field_behavior).creator
// the compiled path honours). Valid only on a singular string field.
Creator bool
// KeyField names the identity field(s) of a keyed message list (composite
// allowed). OrderField names the element's fractional position field,
// promoting it to a movable list. Both lower to (syncplane.v1.field_behavior).
KeyField []string
OrderField string
// MapKey / MapValue, when MapKey is non-zero, declare a scalar-valued map
// (map<MapKey, MapValue>). Both must be scalar kinds; MapKey additionally
// must be a valid proto map key kind.
MapKey protoreflect.Kind
MapValue protoreflect.Kind
}
DynamicField is one field of a DynamicEntity. Beyond scalars (and repeated scalars, opaque bytes) it covers the full compiled modeling power, in symmetry with the TS schema builder:
- embedded sub-messages: set Message to the element's fields (singular, or a keyed message list when Repeated + KeyField are set);
- typed references: set Ref to another entity's Name in the same registration (singular, or to-many when Repeated). Detection is annotation-free — a message field whose target is a (syncplane.v1.entity) is a reference;
- scalar-valued maps: set MapKey and MapValue.
Exactly one shape applies per field; the zero value (only Kind set) is a scalar.
type DynamicIndex ¶
type DynamicIndex struct {
// Name is unique within the entity.
Name string
// Key lists the index's components in sort order. At least one is required.
Key []DynamicIndexKey
}
DynamicIndex is one declared secondary index of a dynamic entity, mirroring syncplane.v1.IndexSpec.
type DynamicIndexKey ¶
type DynamicIndexKey struct {
// Path is a dotted proto field path, e.g. "settings.size".
Path string
// Desc sorts this component descending. Missing and NaN values sort last
// whatever this says, exactly as in a query ordering.
Desc bool
}
DynamicIndexKey is one component of a DynamicIndex, mirroring syncplane.v1.IndexKey.
type EntityMeta ¶
type EntityMeta struct {
// Name is the wire/storage entity name (CrudMutation.entity).
Name string
// Descriptor is the entity message's descriptor, the basis for a generic
// reflective form/renderer.
Descriptor protoreflect.MessageDescriptor
// Type is the message type the server decodes the entity's rows as. Its
// Descriptor is Descriptor.
Type protoreflect.MessageType
// KeyFields are the fields (in order) whose values form the row key. They
// are identity, so an editor renders them read-only on edit.
KeyFields []protoreflect.FieldDescriptor
// Managed reports an entity the engine registers and writes for itself
// rather than one the app declared — today only the field-history log. Its
// rows are engine state whose meaning comes from the writes that produced
// them, so a generic editor must not offer them: writing one by hand claims
// a field held a value it never held, and deleting one loses the only copy
// of a value the row no longer carries. A browser may still read them, and
// the RPC surface refuses client writes of them outright.
Managed bool
// Mergers holds the merge hooks WithMerger declared for the entity, keyed
// by field path, or nil when it declares none. The map is a copy.
Mergers map[string]MergeFunc
// TrustedOnlyFields names the units, top-level fields outside a oneof and
// oneofs, whose field guard admits no update to any caller. Only a trusted
// write changes them on a stored row: any other PATCH whose mask path
// starts with one is refused with CodeAccessDenied, and any other PUT
// that updates a row keeps their stored value. Sorted, and nil when no
// guard closes a field.
TrustedOnlyFields []string
}
EntityMeta is an exported view of a registered entity, for trusted introspection (the admin UI). It surfaces the real registered descriptor and key fields — the single source of truth — so reflection-driven callers never rebuild a parallel descriptor.
type EntityTx ¶
type EntityTx struct {
// contains filtered or unexported fields
}
EntityTx is the typed storage facade mutators run against. Entity identity comes from the message type passed in; keys derive from key_fields.
A Put, Patch or Delete that returns an error writes nothing, so a body may take a Rejection as a refusal and go on. When such a write had begun, the body runs once more on a fresh transaction, as on an adapter retry.
func (*EntityTx) AsCaller ¶ added in v0.2.0
AsCaller returns a view of this transaction whose writes are checked as the same writes sent by the invoking caller's client would be: by the access rules, the field write policies and the application's row write filters. A refused write returns a Rejection, with CodeAccessDenied for the access rules and CodePermissionDenied for the others, and writes nothing; the body decides whether to return it and fail the invocation. Permissions.CanMutate does not run for these writes, since the verdict on the invocation covers them.
Reads through the view read as the invoking caller's client would: a row the caller may not read reads as absent from Get, GetMeta, Scan, ScanPage and Query, and each field a field guard hides from the caller reads as its zero value. A Query whose predicate or order names a field that a guard hides from the caller on some row fails with code permission_denied. The reads see the transaction's own earlier writes, grants included. Reads through a mutator body's own transaction are not filtered.
Can and Seq answer as on this transaction, and writes through either one share its sequence. In a transaction whose writes are already checked, such as one Server.Mutate runs for a caller who is not Trusted, AsCaller returns this transaction itself, whose reads are filtered for that caller as above. In a Trusted transaction, AsCaller returns this transaction itself, whose reads are not filtered.
A write or a read through the view can call the application's WriteFilter, ReadFilter and FieldPermissions hooks inside the transaction. The first read through the view, and the first after a write, calls ReadFilter once for each registered entity.
func completeTask(ctx context.Context, tx *server.EntityTx, args proto.Message) error {
id := args.(*taskv1.CompleteTaskArgs).GetTaskId()
return tx.AsCaller().Patch(&taskv1.Task{Id: id, Done: true}, []string{"done"}, nil)
}
func (*EntityTx) Can ¶ added in v0.2.0
Can reports whether the caller of this transaction holds permission at the row of the entity prototype names, with the given key: at the row itself, at a row up its chain of access parents, or at the workspace root. For a row that does not exist only the root counts.
The caller is the one a mutator was invoked by, or the one Mutate, Apply or a push runs for. A Trusted transaction, and any transaction in a schema without the access model, holds every permission. A mutator body uses Can to apply the model to the rows it writes, which are not checked otherwise.
The answer reflects the writes this transaction has made so far.
In a schema with the access model, Can returns an error that wraps ErrUnknownPermission for a permission no role grants, in a Trusted transaction too.
func (*EntityTx) Get ¶
Get loads the row with the given key into dst. Returns false if the row does not exist (or is deleted). Through an AsCaller view, and in a Server.Mutate for a caller who is not Trusted, it also returns false for a row the caller may not read and clears the fields a guard hides from the caller (see AsCaller).
func (*EntityTx) GetMeta ¶
GetMeta is Get, additionally reporting what the engine recorded about the row's last write (see RowMeta). A missing or deleted row returns (false, RowMeta{}, nil).
It is the read a per-row ownership rule — "only the author may edit their own comment", which no write policy can express — is built on, because the actor comes from the engine's own attribution rather than a field the writer filled in:
found, meta, err := tx.GetMeta(&comment, key)
if err != nil {
return err
}
if !found {
return Reject(CodeConflict, "comment is gone")
}
caller, _ := PrincipalFrom(ctx)
if caller.IsAnonymous() || meta.Actor.Subject != caller.Subject {
return Reject(CodePermissionDenied, "not your comment")
}
Refuse the anonymous caller before comparing, as above: an unattributed row and an unauthenticated caller both carry an empty Subject, so equality alone reads as a match.
Attribution follows the row's last write, so a row its author created and a moderator later edited reports the moderator. Where the rule is about who created a row, the entity has to carry that itself.
func (*EntityTx) Patch ¶
func (e *EntityTx) Patch(msg proto.Message, mask []string, expected *uint64, opts ...WriteOption) error
Patch merges only the masked fields of msg onto the stored row, honoring per-field LWW plus keyed-list / opaque merge semantics — the same merge the client PATCH path runs, lifted into a trusted server-side write. msg must carry the row's key fields (they identify the row); mask names the dotted proto paths to merge.
PATCH is NOT an upsert: a missing or deleted target row is a conflict (delete-wins), so an edit of a row a concurrent writer removed is rejected rather than resurrecting a half-formed ghost. When expected is non-nil the row's current version must equal *expected or the patch is rejected as a conflict (optimistic compare-and-swap); an absent/deleted row reads as version 0. Conflicts and poison masks come back as *Rejection errors (AsRejection recovers them on the caller's side), mirroring the push path.
Text fields can be written from plain strings — WithTextString plus WithTextPeer — which diffs the string against the stored document under the given writer identity and adds the field to the mask automatically (see ApplyTextStrings).
A text field of msg holding a plain-string value (text.EncodePlainString, which is what a field-history record's before-state carries) is resolved the same way, so restoring a record needs no option naming its fields. It still requires WithTextPeer: without one the write fails rather than writing under an invented identity. Unlike WithTextString it does not widen mask: a value in a field mask does not name is ignored, like any other unmasked field.
func (*EntityTx) Put ¶
func (e *EntityTx) Put(msg proto.Message, opts ...WriteOption) error
Put stores msg as a full-row snapshot; the key derives from key_fields.
Exception to "PUT replaces whole rows": collaborative-text fields ((syncplane.v1.field_behavior).text) merge with the stored row instead. A Put value carries the writer's view of the document; replacing wholesale would silently drop every concurrent edit the writer had not seen, so Put reads the live row and unions each text field (when both sides carry one) before writing.
A top-level field the schema does not declare keeps its stored value, and one msg carries is dropped; a Put that creates the row stores none. Fields inside nested messages are replaced. Every other field keeps replace semantics.
Text fields can also be written from plain strings — WithTextString plus WithTextPeer — which diffs the string against the stored document under the given writer identity, so a whole-value write turns into minimal edits that merge with concurrent work (see ApplyTextStrings).
A text field of msg holding a plain-string value (text.EncodePlainString, which is what a field-history record's before-state carries) is resolved the same way, so restoring a record needs no option naming its fields. It still requires WithTextPeer: without one the write fails rather than writing under an invented identity.
WithExpectedVersion makes the write a compare-and-swap and is also how it states create-or-update intent; without one the write is unguarded and follows arrival order like any other.
func (*EntityTx) Query ¶
func (e *EntityTx) Query(prototype proto.Message, spec query.Spec, fn func(msg proto.Message) error) error
Query iterates the live rows matching spec, in spec's order, decoding each into a fresh message — the read half of "find the rows matching X and update them", inside the same transaction as the writes so nothing moves underneath. It is the same compiled predicate ViewTx.Query and the Query RPC use.
The cost to keep in mind here specifically is that it runs while the workspace's write lock is held, so a broad query inside a mutation blocks every other writer for its duration — and it is a full scan of the entity unless a declared secondary index covers its predicate and ordering. A spec with no Limit also retains every match in memory. See query.Spec.
Through an AsCaller view, and in a Server.Mutate for a caller who is not Trusted, it answers as ViewTx.Query does for the caller (see AsCaller).
func (*EntityTx) Scan ¶
Scan iterates all live rows of the entity identified by prototype, decoding each into a fresh message. Through an AsCaller view, and in a Server.Mutate for a caller who is not Trusted, it skips the rows the caller may not read and clears the fields a guard hides from the caller (see AsCaller).
func (*EntityTx) ScanPage ¶
func (e *EntityTx) ScanPage(prototype proto.Message, afterKey string, limit int, fn func(msg proto.Message) error) (lastKey string, more bool, err error)
ScanPage iterates up to limit live rows with key > afterKey, in key order. It returns the key of the last row visited and whether more rows follow; pass lastKey back as afterKey to continue. limit must be positive. Through an AsCaller view, and in a Server.Mutate for a caller who is not Trusted, it skips the rows the caller may not read (see AsCaller); a skipped row still counts toward limit.
func (*EntityTx) Seq ¶
Seq returns the workspace sequence this tx's writes are stamped with, or 0 before the first write (Server.Mutate allocates lazily). Trusted callers use it to record which sequence their writes landed at — e.g. a connector stamping its bookkeeping so it can later recognize its own writes in the change feed.
type EpochReadFilters ¶
type EpochReadFilters interface {
ReadFilterAt(ctx context.Context, p Principal, workspaceID, entity string, epoch uint64) (RowFilter, error)
}
EpochReadFilters is an optional Permissions extension. Apps that can evaluate read filters as of an EARLIER FilterEpoch opt into delta resync for permission changes: instead of resetting every client after an epoch bump, the server diffs each client's old visible set (filters at the cursor's epoch) against the new one and sends only the difference — rows that became visible as values, rows that became hidden as tombstones.
ReadFilterAt carries the same purity contract as ReadFilter, evaluated as of the given epoch. Return ErrEpochUnavailable for epochs too old to reconstruct (e.g. beyond retained history); those clients reset as before.
The delta resync needs a cursor-state store (see WithCursorStateStore). Without one, and for a cursor whose sequence and epoch the store does not confirm, the client resets.
type FieldPermissions ¶
type FieldPermissions interface {
// ProtectedFields returns the top-level field names this caller may not
// write in the named entity, beyond the ones its schema marks. Return nil
// for "nothing further", which is the answer for most entities.
//
// Names are proto field names, and a oneof is named by its GROUP — the only
// unit a mask may name it in — though naming a member resolves to the same
// thing. A name that matches no field, or matches a key field, aborts the
// RPC: the hook states a restriction, and one that silently protects nothing
// is the wrong way for a permission control to fail.
//
// The engine resolves it at most once per entity per request, before the
// write transaction opens, and reads the memoized answer again while
// applying — so it carries the same cost contract as the rest of Permissions
// (see the interface doc on execution context) and the same purity
// requirement as CanMutate.
ProtectedFields(ctx context.Context, p Principal, workspaceID, entity string) ([]string, error)
}
FieldPermissions is an optional Permissions extension covering per-caller field protection that depends on facts outside the workspace's rows. A schema states which callers may write a field with the access model's field guards (see the FieldGuard proto option); this says which further fields THIS caller may not write.
It only takes fields away. A field it returns is protected in addition to what the guards keep from the caller, so a policy cannot hand a caller a field a guard keeps from them.
A field it returns is enforced as a guarded field is: a PATCH whose mask reaches it is rejected with CodePermissionDenied, and a PUT keeps the stored value for it, or the zero value on a create. A client cannot predict this hook, so it learns of such a field as a REJECTED ack.
A Permissions that does not implement it protects only what the schema's guards and creator fields keep from the caller.
type HistoryFilterFunc ¶
type HistoryFilterFunc func( ctx context.Context, rec *syncplanev1.FieldHistory, src EntityMeta, ) (*syncplanev1.FieldHistory, bool, error)
HistoryFilterFunc admits, rejects or rewrites one history record before it is written. rec is the record the engine built and src describes the entity whose row changed. Return the record to write and true to keep it, false to drop it silently, or an error to FAIL THE WRITE that triggered it — a hook that cannot decide must not let the write through unrecorded.
An error means the hook could NOT DECIDE, so the write stays retryable: the batch carrying it fails with CodeInternal and nothing is acked, and a client resends once the hook can answer. Its text never reaches the client — it is logged instead, because a hook's own wording can name dependencies and rows the caller has no business seeing.
To refuse a record PERMANENTLY, return a Rejection built by Reject instead. That acks the mutation and the client drops it, which is what a hook failing deterministically on a record's SHAPE wants: resending the identical mutation would fail identically, so acking drains the queue rather than wedging it. A Rejection's code and message are the hook's own and do reach the client. The split is CanMutate's, for the same reason — a dependency having a bad minute must not cost the caller its write.
It runs inside the write transaction, immediately before the record is stored, so it sees the record's final shape (mask, prior value, actor, sequence) and its verdict commits or rolls back with the write.
It runs on every captured write, including one that FOLDS into a record an earlier write opened — an open session, or a second write to the same row at one sequence, which a batch mutation or a mutator body produces and which folds whatever the session settings say. rec is then the whole folded record rather than the increment: this hook's own earlier output, plus the fields the new write moved. A hook that redacts must be idempotent over its output.
Dropping a folded record leaves the stored one as the previous write left it, rather than deleting it. Dropping the FIRST record of a session leaves later writes nothing to fold into, so the next one opens a record of its own, whose prior describes the state after the dropped write and is indistinguishable from one covering the session from its start. Dropping on a record's contents therefore changes what the records around it say; dropping per entity does not.
It must be a PURE FUNCTION of its arguments — free of observable side effects — for the same reason Permissions.CanMutate must: the storage adapter MAY re-run the write closure and re-invoke this hook, so a hook that audit-logs or meters double-counts. Redaction, sampling and per-entity policy belong here; anything that has to happen once belongs after the write commits.
Rewriting is by value, not in place: return a record (typically the one handed in, mutated) and the engine writes exactly that. The record's IDENTITY is not rewritable — source_entity, source_key and seq are the fields its row key derives from, and changing any of them fails the write. Neither is row_created, and it fails the write the same way: redacting a creation record means dropping it. Redaction, dropping and rewriting anything else are what the hook is for.
Redacting a mask down to empty is allowed and leaves an update. The record still says a change happened, and later writes in the session fold in and record their own fields.
type Limits ¶
type Limits struct {
// Maximum encoded bytes of a single request message (Push/Pull/Query/
// Bootstrap), enforced by the Connect/HTTP layer before the body is
// buffered or unmarshaled — and applied to the decompressed size, so it
// also caps compression bombs. This is the coarse outer wall in front of
// every finer limit below (and of otherwise unbounded inputs that ride in
// the body: the subscription set, condition trees, and the opaque pull
// cursor); an over-limit request is rejected as resource_exhausted before
// any parsing. It must sit comfortably above your largest legitimate push
// (roughly MaxMutationsPerPush × MaxValueBytes) — raise it in tandem if you
// raise those. Default 16 MiB.
MaxRequestBytes int
// Maximum mutations per Push request, counted across ALL its per-workspace
// batches — it bounds the work one request asks for. Default 256.
MaxMutationsPerPush int
// Maximum workspaces one request may name: Push batches and Subscribe
// scopes. Each costs a write transaction or a live stream scan plus a
// notifier subscription, so this bounds what a single request can commit
// the server to. A client holding more workspaces than this must split its
// pushes and open a second stream. Default 64.
MaxWorkspacesPerRequest int
// Maximum serialized entity value (crud.value / custom.args) in bytes.
// Default 1 MiB.
MaxValueBytes int
// Maximum field-mask paths per PATCH. Default 64.
MaxFieldMaskPaths int
// Maximum row changes per Pull response; larger results paginate via
// has_more. Also clamps client-requested limits. Default 4096.
MaxPullChanges int
// Maximum live rows one Pull examines while delta-resyncing a scope change
// before it returns a partial page. A scope change compares the workspace's
// live rows under the old and the new visibility, and rows visible under
// both emit nothing, so this budget rather than MaxPullChanges decides how
// many round trips a small difference costs: a larger value settles a
// widened window over a large workspace in one or two pulls, a smaller one
// bounds how long a single Pull holds its read transaction.
//
// It also bounds candidate narrowing wherever a scope names its rows
// instead of visiting them — a resync, a bootstrap, and the seeds a
// following subscription walks from: how many rows any of them may name
// through secondary indexes and membership sets before it visits the
// entity row by row instead. A scope selecting more of an entity than this
// is no cheaper to reach by index, so lowering the limit trades snapshot,
// resync and follow speed on large scopes for a smaller working set —
// never a different set of rows.
//
// Values below MaxPullChanges are raised to it; a page that stops before
// it is full only adds round trips. Default 65536.
MaxResyncScan int
// Maximum rows per Query response. Also clamps client-requested limits.
// Default 1024.
MaxQueryRows int
// Maximum offset accepted by Query. Offset is the fallback for jumping to
// an arbitrary rank; sequential paging goes through after/before, which
// costs neither the working set nor the shifting page an offset does. A
// query retains the offset+limit rows that sort first, so the offset bounds
// that in-memory working set however the query is served — from an index or
// from a scan. Requests beyond this are rejected rather than clamped (a
// clamp would return the wrong page silently). Default 16384.
MaxQueryOffset int
// Maximum length in bytes of an after/before cursor Query accepts. A cursor
// is a row's position under the query's ordering, so its length follows the
// order-key values; the limit is what keeps a malformed one from costing
// work proportional to whatever a client sent. Default 4096.
MaxQueryCursorBytes int
// Maximum follow depth a Subscription.follow may request (rounds the path
// set is re-applied). A request above this is InvalidArgument. Default 4.
MaxFollowDepth int
// Maximum number of rows a single request's reference-following closure may
// contain. Overflow aborts the pull as resource_exhausted, keeping working
// sets bounded. Also bounds the Cursor.closure key-set. Default 10000.
MaxClosureSize int
// Maximum source rows a single reverse-follow hop may match (one parent's
// children). Overflow is resource_exhausted; protects against a popular
// parent blowing the working set on the index-less reverse scan. Default
// 1000.
MaxReverseFanOut int
// Maximum rows a single Subscription.window may hold. A larger limit is
// InvalidArgument rather than clamped: a silently narrower window would
// look like missing data to the app.
//
// Must stay well under MaxPullChanges: a window that swaps wholesale emits
// up to 2N changes (N values entering, N tombstones leaving) in ONE page,
// because the membership diff runs at a clean version boundary and has no
// paging state of its own. Default 1000, against MaxPullChanges' 4096.
MaxWindowSize int
// Maximum keys a single Subscription.key_set may name. A larger set is
// InvalidArgument rather than clamped, for the same reason a window is: a
// silently shorter set would look like missing data to the app.
//
// The set rides on every Pull and Subscribe request the client sends, so
// this bounds request size as much as it bounds the rows a scope pins.
// Default 1000.
MaxSubscriptionKeys int
// Maximum secondary-index entries one row may occupy across all of its
// entity's value indexes. Search postings do not count against it: the
// per-row term cap (query.SearchTermsPerRow) bounds them. This is the
// WRITE cost of indexing: every row write
// re-encodes and stores the whole set, so the count multiplies the price
// of every mutation to that entity. Exceeding it fails the write rather
// than silently dropping entries, which would leave an index that reads
// as complete and is not.
//
// An index over a repeated field stores one entry per ELEMENT, so this is
// also the ceiling on how long an indexed list may get — roughly
// (elements x indexes over that list) plus one per ordinary index. The
// default is set for lists in the hundreds, which is where a to-many
// reference stops being a reasonable shape anyway; a schema that indexes
// longer lists has to raise it deliberately, because the cost lands on
// every write of the row and not on the query that benefits. Default 1024.
MaxIndexEntriesPerRow int
// Maximum index entries one range scan may walk while its read filter
// rejects candidates. An index narrows the candidates; a permission filter
// or a residual predicate the index cannot express still rejects some of
// them, and in the worst case rejects nearly all — at which point the
// "index" walk has become a scan with extra steps. Overflow falls back to
// the plain scan rather than failing, because index use is an
// optimization and must never change an answer. Default 10000.
MaxIndexScanCandidates int
// DisableIndexes forces every read to take its scan fallback, as if no
// index were ready. Indexes are still MAINTAINED, so the setting can be
// flipped without a rebuild.
//
// It exists for the differential test: index use is a pure optimization,
// so the whole suite must produce identical results with it on and off,
// and any divergence is a bug in the encoding or the planner. It is also
// the operational escape hatch if one ever is.
DisableIndexes bool
// Maximum rooms one Watch stream may carry. Each costs a bus subscription,
// a join gate and — for an anchored room — a row read on every re-gate, so
// this bounds what one stream commits the server to. A client watching more
// rooms than this opens a second stream. Default 64.
MaxRoomsPerStream int
// Maximum bytes of one participant's presence state. It is the app's own
// payload, and it rides in every announcement of that record — so unlike a
// row, its cost is per interval rather than per write, and it has to fit
// whatever the presence bus can carry (a Postgres NOTIFY payload is capped
// at 8000 bytes, base64 included). Default 4 KiB.
MaxPresenceStateBytes int
// Maximum bytes of one broadcast message, under the same bus ceiling as
// MaxPresenceStateBytes. Default 4 KiB.
MaxBroadcastBytes int
// Maximum items in one Publish request. Items are independent, so this
// bounds the gate calls and bus publishes one round trip can ask for.
// Default 32.
MaxPublishItems int
// Maximum participants a room keeps. Beyond it the room keeps the lowest
// session ids, reports its snapshot truncated, and turns further sessions
// away — lowest rather than newest so two nodes serving the same over-full
// room show the same people.
//
// It is a rendering bound as much as a memory one: a roster nobody can read
// is not worth the announcement traffic that maintains it. Default 128.
MaxParticipantsPerRoom int
// DisableMembershipMaintenance forces every pull to resolve a window and a
// follow closure from scratch, as if the cursor said nothing about the
// previous one.
//
// It exists for the same differential test DisableIndexes does, and for the
// same reason: maintaining a membership set from what changed is a pure
// optimization over rebuilding it, so the two must produce identical pages
// however the workspace is driven, and any divergence is a bug in the
// maintenance rules rather than a tuning question.
DisableMembershipMaintenance bool
// Maximum matches() conditions one query predicate may carry. Each crosses
// into another entity and is answered by its own pass over that entity's
// rows before the query itself runs, so the count multiplies the price of
// the request while the predicate's own size says nothing about it.
//
// Conditions selecting the same target rows share one pass, so the limit
// counts what a predicate WRITES rather than what it costs. Default 8.
MaxRelConditions int
// Maximum access parent hops from a row up to a row without an access
// parent, in a schema that uses the access model. Registration refuses an
// entity with a longer chain of parent entities, through any case of a
// polymorphic access parent. In a recursive chain,
// such as a folder inside a folder, a write that would put a row deeper is
// refused, and a read stops walking at this depth: a row deeper than it
// is read as anchored at nothing above that point. A row with several
// access parents counts its longest path for a write, and a read reaches
// an anchor through any path of at most this many hops. Default 32.
MaxAccessDepth int
// Maximum distinct rows that the access parents of one row may name, in
// a schema that uses the access model. A write that changes a row's access
// parents to more rows than this fails with CodeInvalidArgument, on every
// write path. A row that holds more from before the limit was lowered
// keeps them until a write changes them. Default 64.
MaxAccessParents int
// Maximum size in bytes of one blob. BeginUpload of a larger blob fails
// with resource_exhausted. Default 4 GiB.
MaxBlobBytes int64
// Maximum facet axes one Query may carry. Each axis costs a bucket per
// distinct value and a lookup per matching row, and a request carrying any
// walks every match rather than the page. Default 8.
MaxQueryFacets int
// Maximum target rows one matches() condition may select. It is the size of
// the membership test the condition collapses to, which the server builds
// and holds for the request, so an unbounded one turns a small request into
// a large read. Exceeding it fails the query rather than truncating: a
// truncated key set would silently drop rows that match. Default 50000.
MaxRelKeys int
}
Limits bounds request payloads and response sizes. It bounds what one request may cost, never request rate or concurrent streams; those limits belong in the HTTP stack in front of the handlers, where they can attach to a connection, an address or a credential. Every field must be positive to take effect: zero means "unset", and a negative value is a misconfiguration, so both fall back to the documented default (the same rule WithChunkSize follows). Letting a negative through would not merely relax a bound, it would invert one — the storage contract reads a non-positive scan limit as UNLIMITED, so a negative MaxPullChanges would turn every Pull into a full-workspace scan that emits nothing and returns a cursor regressed to sequence 0, which a well-behaved client then loops on forever.
type Manager ¶
type Manager struct {
// contains filtered or unexported fields
}
Manager hosts multiple apps on one engine, mapping each app to its own *Server over its own partition of the root adapter's workspaces. App identity is purely a routing + storage-partition concern (it is NOT encoded in the proto package), so two apps may both define sync.dynamic.Todo without colliding — they live in distinct *Server instances over distinct data partitions.
The partition is a workspace-id prefix, "<appID>/", and it reaches every plane an app's server sits on: storage through prefixstore, the change notifier through the server itself, and the presence bus through its room registry. None of those knows what an app is, which is why one storage adapter, one notifier and one bus can be shared by every hosted app and still keep them apart. App ids are restricted (see naming.ValidateAppID) so that no two of them can produce the same prefixed id.
An app's own code — its permission hooks, its effects, its clients — deals in bare workspace ids throughout.
The public sync surface is routed by a leading "/<appID>" path segment (see SyncHandler); the trusted admin surface (AdminHandler) is mounted separately so it can bind to a private interface.
Authenticating a collection of apps ¶
Identity is normally shared across a collection and authorization is not. The two option seams follow that split:
- WithServerOptions carries what every app has in common — one Authenticator, limits, the notifier, the presence bus, the logger. The authenticator runs on the app's own handler, so a request is authenticated exactly once, after routing, and its Principal reaches that app's permission hooks.
- WithAppOptions carries what differs per app, which in practice means Permissions. A policy needs to know WHICH app it is answering for — each app has its own workspace space, so "workspace team" in one app is unrelated data from "workspace team" in another — and hooks are not handed an app id. Closing over the app id at construction is how a policy gets it.
A single policy shared across every app via WithServerOptions is therefore only correct when the apps genuinely share a membership model. Otherwise build one per app:
mgr, err := server.NewManager(ctx, root,
server.WithServerOptions(server.WithAuthenticator(auth)),
server.WithAppOptions(func(appID string) []server.Option {
return []server.Option{server.WithPermissions(policyFor(appID))}
}))
Nothing forces this: an app with no policy inherits AllowAll, which admits every caller into every workspace of that app (see AllowAll).
Several nodes ¶
Several Managers may share one root adapter. A registration on one of them stores the schema only when the stored schema is still the one it merged over, so a node that had not seen a newer schema merges over that one instead of writing its own over it. The other nodes serve the stored schema once they learn of it: at once when their apps share a notifier with the node that registered (see WithNotifier), and otherwise on the next catalog poll (see WithCatalogPollInterval). A node also serves apps that another node registered from the poll after their first registration.
func NewManager ¶
NewManager builds a Manager over a root adapter and reloads every persisted app schema, re-registering its entities BEFORE returning, so a restart leaves all previously-registered apps immediately syncable. A persisted schema that fails to re-register aborts startup (the stored bytes were valid when first accepted, so a failure signals real corruption or a binary downgrade) — and takes the apps reloaded before it down with it, because a caller that got an error has no Manager to Close.
The Manager owns the app servers it creates; close it (and then the root adapter) at shutdown. See Close.
root must implement storage.Catalog, which is where the registered schemas persist; an adapter without one can back a Server but not a Manager.
func (*Manager) AdminHandler ¶
AdminHandler returns the mount path and handler for the trusted AdminService (schema registration). Mount it on a separate, private listener — never on the public sync surface.
func (*Manager) App ¶
App returns the app's live *Server, or nil if the app is unknown (never registered or reloaded). It is the exported counterpart of lookup, for trusted introspection (the admin UI) that addresses an app by id.
func (*Manager) AppIDs ¶
AppIDs returns the ids of every live app server, sorted. An app becomes live once it is registered (or reloaded on boot); a never-registered app is not listed even if its schema is requested. Used by the admin UI to enumerate hosted apps.
func (*Manager) Close ¶
Close stops the background work of every hosted app — each *Server's GC pass, index backfill and notify-coalescing timers — and refuses to host new apps afterwards, so a registration racing shutdown cannot start a goroutine that outlives it. Every app is closed even if one fails; their errors come back joined.
It does NOT close the root adapter, matching Server.Close: the caller owns the handle, and one root backs every app here. Nor does it stop serving — handlers keep answering from the still-open store, just without the background passes — so Close belongs at process shutdown, after the listeners are down:
root, err := sqlitestore.Open(path) … defer root.Close() mgr, err := server.NewManager(ctx, root, …) … defer mgr.Close()
Close is idempotent.
func (*Manager) ListAppSchemas ¶
ListAppSchemas returns every persisted app schema (app id + revision + descriptor set), ordered by app id. It reads the adapter's catalog — the same call NewManager makes at boot — so the admin UI can list apps and their schema revision without re-deriving anything.
func (*Manager) Register ¶
func (m *Manager) Register(ctx context.Context, appID string, set []byte, opts ...RegisterOption) (ManagerRegisterResult, error)
Register validates and registers an app's descriptor set, then persists it for boot reload. Registration (which validates additive evolution and rejects conflicts) runs first, so a rejected set never reaches storage; an identical set is a no-op and is not re-persisted. It does NOT check the authorizer — that gate lives on the admin RPC, which calls this after admitting the caller. opts apply as they do to Server.RegisterDescriptorSet.
A set adds and replaces entities and keeps the others the app registered before. The app's schema, which the catalog stores, is the merge of every set it registered: the definitions of set, and every definition of the stored schema that set does not replace. A restart serves that schema, and the revision is the revision of that schema. Entities in the result are the entities set declares. Registrations of one app run one at a time.
An entity cannot be renamed or removed: a set that declares the message of a registered entity as another entity, or with no entity option, is refused.
The merge is over the schema the catalog stores, also when another node stored it, and set is checked against that schema. The app serves the merged schema only once the catalog stores it, so an error leaves the app on the stored schema, and a retry of the same set stores it. When other nodes store schemas of the app faster than Register can merge, it fails with an error that wraps storage.ErrCatalogConflict.
func (*Manager) SyncHandler ¶
SyncHandler returns the routed public handler. It strips the leading "/<appID>" path segment, looks up that app's *Server, and delegates to that server's own mux, which carries every Connect service it mounts at the full method path each expects ("/syncplane.v1.SyncService/...", "/syncplane.v1.PresenceService/..." and "/syncplane.v1.BlobService/..."). An unknown app is 404. App servers are created on demand by Register / boot reload, so a request for an unregistered app never auto-creates one.
type ManagerOption ¶
type ManagerOption func(*Manager)
ManagerOption configures a Manager.
func WithAppOptions ¶
func WithAppOptions(fn func(appID string) []Option) ManagerOption
WithAppOptions installs a per-app Option source: fn is called once per app, when that app's *Server is created (its first registration, or the boot reload of a persisted schema), and its Options are applied after the shared WithServerOptions ones — so a per-app Permissions overrides a shared one.
This is the seam for policies that must be bound to an app: hooks receive a principal and a workspace id but no app id, and each app has its own workspace space, so a policy that cannot tell the apps apart cannot decide membership for them. Closing over appID here gives it that context once, rather than per request.
fn must be safe for concurrent use — apps are created lazily, on whichever goroutine first routes to them — and should be cheap: it runs while the Manager's app map is locked, so a slow fn stalls other apps' first requests. Build the expensive parts (a membership client, a token cache) once outside and let fn hand out per-app views of them.
func WithCatalogPollInterval ¶ added in v0.2.0
func WithCatalogPollInterval(d time.Duration) ManagerOption
WithCatalogPollInterval sets how often the Manager reads the catalog for schemas that other nodes over the same root adapter stored. The default is 30 seconds. A value of 0 or less turns the poll off; the Manager then learns of another node's registration only through a shared notifier, and serves an app that another node registered first only after a restart.
A node that registers does not wait for the poll: it merges over the stored schema in either case.
func WithRegisterAuthorizer ¶
func WithRegisterAuthorizer(a RegisterAuthorizer) ManagerOption
WithRegisterAuthorizer installs the trust gate for the admin Register RPC. The default is DenyAll (fail closed).
func WithServerOptions ¶
func WithServerOptions(opts ...Option) ManagerOption
WithServerOptions sets the server Options applied to every app's *Server (authenticator, limits, notifier, heartbeat, ...). Per-app schema and storage partition are managed by the Manager and must not be set here.
Use it for what the collection shares. Anything that must differ per app — Permissions above all — belongs in WithAppOptions, which is applied after these and so wins on conflict.
type ManagerRegisterResult ¶
type ManagerRegisterResult struct {
Revision string
Status RegisterStatus
Entities []string
}
ManagerRegisterResult is the outcome of Manager.Register.
type MergeFunc ¶
MergeFunc combines the stored serialization of an opaque field with an incoming PATCH value (e.g. a CRDT merge). base and incoming are the raw field values: the bytes content for bytes fields, the marshaled message for message fields.
type MutationOrigin ¶ added in v0.6.0
type MutationOrigin struct {
// Client identifies the pushing client and its caller to this server. It
// is opaque: compare it, store it and pass it back, but do not build one.
Client string
// MutationID is the id the client pushed the mutation under.
MutationID uint64
// Mutator is the name of the custom mutation, "" for a CRUD or batch
// mutation.
Mutator string
// Targets are the rows the mutation named, in payload order: one for a
// CRUD mutation, one for each member of a batch, none for a custom
// mutation.
Targets []storage.RejectionTarget
}
MutationOrigin identifies the client mutation a CapturedWrite applied, so that a later rejection of it can reach that client (see ReplicaTx.RejectLate). A WriteCapture may store it and pass it back in a later transaction.
type MutatorAccess ¶ added in v0.2.0
type MutatorAccess struct {
Permission string
Entity string
KeyField string
Admitted bool
TrustedOnly bool
}
MutatorAccess states which callers may invoke a mutator in the access model: every caller admitted to the workspace, or the callers that hold a permission where the access names.
With Admitted set, every caller admitted to the workspace may invoke the mutator, and Permission, Entity and KeyField stay empty. With Entity and KeyField set, the caller must hold Permission at the row of Entity whose key the KeyField of the args holds: at the row itself, at the row its access parent points at, or at the workspace root. A row that does not exist refuses the invocation. With both empty, the caller must hold Permission at the workspace root.
With TrustedOnly set, only a Trusted caller may invoke the mutator, and the other fields stay empty. This is also what a mutator without a MutatorAccess gets, but registration logs a warning for such a mutator and not for one that sets TrustedOnly.
In a schema that uses the access model, an invocation of a mutator without a MutatorAccess is refused for every caller who is not Trusted. The check runs inside the write transaction before the body, and is refused with CodeAccessDenied. The rows the body writes are not checked unless it writes them through EntityTx.AsCaller; the body can also ask EntityTx.Can.
Registration fails, with the rest of the access model, when Admitted or TrustedOnly is set together with another field, Permission is granted by no role, Entity is not in the model, or KeyField is not a singular string field of the args. In a schema without the access model, it has no effect.
server.Mutator("complete_task", completeTask,
server.MutatorAccess{Permission: "edit_tasks", Entity: "task", KeyField: "task_id"})
server.Mutator("send_feedback", sendFeedback,
server.MutatorAccess{Admitted: true})
server.WithMutator("rebuild_index", nil, rebuildIndex,
server.MutatorAccess{TrustedOnly: true})
type MutatorFunc ¶
MutatorFunc is a named server-authoritative mutation. It runs inside the push write transaction; every row it writes is stamped with the mutation's sequence. Return Reject(...) for a business "no".
Any other error fails the whole batch as CodeMutationFailed: nothing in it is acked, and the client resends. Returning one for a verdict that cannot change — a validation failure, an unhandled case — therefore costs the client a retry loop that ends in the mutation being dropped to its dead-letter surface, so it reaches the app as a lost write rather than as the "no" it was. A cancelled push context fails the batch as CodeInternal instead, and so does any error after a storage call of the body failed: that error is taken to be the store's failure, which the client retries without a limit. An answer is not a failure here: a missing row, or an error the body's own Scan or Query callback returned.
args follows the registration, not the caller: a mutator registered with a prototype always receives a non-nil message of that type — zeroed when the invocation carried none — and one registered without a prototype always receives nil. That holds on every entry point (a client push, Invoke, InvokeIdempotent), so a body may type-assert its prototype unconditionally, or be declared through Mutator, which does the assertion.
type MutatorOption ¶ added in v0.2.0
type MutatorOption interface {
// contains filtered or unexported methods
}
MutatorOption adjusts one WithMutator declaration.
type Option ¶
Option configures a Server at construction. Two kinds travel through the same type: settings (WithPermissions, WithLimits, …), applied in the order given so a later one overrides an earlier one; and declarations (WithEntities, WithMutator, WithMerger), which only record intent and are installed by New in dependency order once the server exists. Declarations are therefore order-independent among themselves — WithMerger may name an entity a later WithEntities declares.
func Mutator ¶ added in v0.3.0
func Mutator[A proto.Message](name string, fn func(ctx context.Context, tx *EntityTx, args A) error, opts ...MutatorOption) Option
Mutator declares a custom mutation handler that takes arguments of type A, as WithMutator does with a prototype of A. fn receives a non-nil A on every entry point, zeroed when the invocation carried no arguments. A mutator that takes no arguments is declared through WithMutator with a nil prototype.
server.Mutator("complete_task",
func(ctx context.Context, tx *server.EntityTx, args *taskv1.CompleteTaskArgs) error {
…
},
server.MutatorAccess{Permission: "edit_tasks", Entity: "task", KeyField: "task_id"})
New fails when A is an interface type, and for every reason WithMutator's declaration fails.
func WithAuthenticator ¶
func WithAuthenticator(a Authenticator) Option
WithAuthenticator installs the authentication seam: a is run before every sync RPC and its Principal is put on the handler's ctx, where the Permissions hooks receive it.
With no authenticator (the default) nothing authenticates and every request reaches the hooks as the anonymous zero Principal — the embed-behind-your-own -auth posture the engine has always had. That is safe only when the sync surface is unreachable by untrusted traffic. Authenticating in your own HTTP middleware is equally supported; have it call WithPrincipal so the hooks see the identity.
Installing an authenticator does not by itself authorize anything: it establishes WHO is calling, and the Permissions policy decides what they may do. A server exposed to untrusted traffic needs both — the default AllowAll allows every caller, authenticated or not.
func WithBlobRetention ¶ added in v0.4.0
WithBlobRetention sets how long blob GC keeps a committed blob that no live row refers to, and a staged upload that has not completed. It takes effect only together with WithBlobStore and WithGC. A non-positive d keeps the default, 30 days.
A blob is deleted on the first GC pass after it has been unreferenced for d, so a row that refers to it again within d keeps it. The clock restarts when BeginUpload names the blob.
func WithBlobStore ¶ added in v0.4.0
WithBlobStore makes the server keep blobs in st and serve syncplane.v1.BlobService from it. Without it every BlobService call fails with unimplemented.
The server does not close st. A Manager that passes one store to every app it hosts keeps the apps apart: each app names its workspaces in st with its own prefix.
func WithCallerAccess ¶ added in v0.2.0
func WithCallerAccess(fn CallerAccessFunc) Option
WithCallerAccess sets what each caller is in the access model of each workspace: the subjects its grant rows may name, and the roles it holds at the workspace root. Use it for access that comes from outside the data, such as group membership or staff roles in an identity-provider claim:
server.WithCallerAccess(func(_ context.Context, p server.Principal, _ string) (server.CallerAccess, error) {
access := server.CallerAccess{Subjects: []string{p.Subject}}
if staff, _ := p.StringClaim("staff"); staff == "admin" {
access.RootRoles = []string{"org_admin"}
}
return access, nil
})
Without it, a caller's only subject is Principal.Subject, none for an anonymous caller, and the caller holds no role at the root. With it, fn is the only source: Principal.Subject is a subject only when fn returns it.
A root role that no entity declares grants nothing. With fn set, a registration that declares a role name the served schema does not declare needs AllowAccessChange, since fn may already return that name.
A deployment that accepts more than one issuer should return subjects that name the issuer, so that two issuers' callers with the same Subject do not share grants.
fn runs once per request, anonymous callers included, after the CanAccessWorkspace hook of the Permissions policy admits the caller and before any read transaction opens. A Trusted call does not run it. A long-lived stream runs it again on every heartbeat, which is how a change in what fn returns reaches an open stream. The server does not cache the result, so fn must cache a lookup that is too slow to run per request. fn must be safe for concurrent use.
An error from fn fails the request with code internal, or with the code of a *connect.Error that fn returns. It is never read as a denial. In a schema that does not use the access model, only the primary subject has an effect.
func WithChunkSize ¶
WithChunkSize sets the bootstrap chunk size in rows (default 256).
func WithClientRetention ¶
WithClientRetention makes each GC pass delete the watermark records of clients that have not pushed for d, bounding the clients table. It only takes effect together with WithGC. Zero, the default, keeps every record. A negative d makes New fail.
A deleted watermark forgets which mutation ids the client already had applied. The client re-enters through watermark adoption at whatever id it pushes next — and if that push is a resend of mutations whose response was lost, they apply a second time: a stale PUT or DELETE then overwrites what other clients wrote in the meantime, and a batch or custom mutator runs twice. The client's pending queue is durable, so the resend can arrive however long after the loss. Set d well past the longest time a client can stay away and still be expected to hold unpushed work, and prefer leaving it unset unless the clients table is a measured problem. See docs/explanation/limits-and-trade-offs.md.
func WithCursorStateStore ¶
func WithCursorStateStore(st cursorstate.Store) Option
WithCursorStateStore installs the store that keeps the membership tail of issued cursors — the subscription set and the windowed/closure key-sets — so a cursor on the wire is a fixed-size reference instead of restating everything the client holds. See the cursorstate package for the contract: entries are immutable, eviction is licensed, and a client whose entry was evicted is reset onto a fresh bootstrap.
Without this option the server asks its storage adapter for a store (cursorstate.Provider), so adapters that can back one give slim cursors with no configuration. Passing nil disables the indirection entirely: every cursor inlines its sets, which is also the fallback whenever a store write fails.
func WithEntities ¶
WithEntities declares syncable entities: message types carrying (syncplane.v1.entity) options. New registers them in the order given and returns the first that does not validate, so a whole schema costs one error check instead of N. Repeatable; entity names must be unique across all of them.
This is the compiled path — schemas known when the binary is built. A schema that arrives later goes through RegisterDescriptorSet or RegisterDynamicEntities on the live server instead.
func WithGC ¶
WithGC enables garbage collection. One pass prunes, per workspace and with the same retention, both tombstones (clients whose cursor predates a collected tombstone get reset=true on the next pull and re-bootstrap) and the rejection verdicts recorded for idle clients (a resend of a refused mutation is then answered with a bare ALREADY_APPLIED instead of the verdict). The same pass also carries the text delta log and the trusted-write idempotency ledger, each on its own retention (WithTextDeltaRetention, WithIdempotencyRetention), and effect consumers stranded below the horizon the pass just set — a consumer still keeping up is never below it, however long it idles. The same pass also expires field-history records (WithHistoryRetention), which it hard-deletes rather than tombstones because nothing syncs them. On the tombstone retention it also deletes the sequence lineage records that let a pull detect a store restored from backup: a cursor whose sequence is older than the retention is served without that check, unless it sits at the workspace's current sequence, whose record the pass keeps.
Idle clients' watermark records are kept whatever the retention: they are what makes a resend idempotent, and a client's pending queue outlives any offline window. WithClientRetention opts into deleting them.
Retention MUST comfortably exceed the longest expected client offline window, or clients spend their returns re-bootstrapping. Weeks is a sane order of magnitude; minutes is not.
interval > 0 runs a background pass each interval over the workspaces holding something these retentions make collectable, which on an idle deployment is none of them; interval <= 0 configures retention for manual CollectGarbage calls only. Call Close to stop the background goroutine.
Multi-node note: every node may run the pass — it is idempotent — and each workspace's collection runs under a per-workspace lease (see WithLeases), so nodes sharing a lease-providing store divide the sweep rather than repeat it.
func WithHeartbeat ¶
WithHeartbeat sets the Subscribe stream heartbeat interval (default 30s). Zero or negative keeps the default.
The heartbeat is also how often a Subscribe or Bootstrap stream re-checks workspace access, so this bounds how long a revoked member keeps receiving a workspace's rows. Shortening it tightens that window at the cost of one CanAccessWorkspace call per live workspace per tick, per stream.
func WithHistoryFilter ¶
func WithHistoryFilter(fn HistoryFilterFunc) Option
WithHistoryFilter installs the admission hook every history record passes through. See HistoryFilterFunc for what it may do and the purity it owes.
The filter is construction-time only, like a merger: it is a func, so unlike a schema it cannot be provisioned at runtime. New fails if fn is nil.
func WithHistoryRetention ¶
WithHistoryRetention overrides how long each GC pass keeps the field-history records written for entities carrying (syncplane.v1.entity).history. It only takes effect together with WithGC — without a pass, records are kept until their row is deleted whatever this says. Default 90 days.
Pass HistoryForever to turn time-based expiry off and tie a record's lifetime to its row's alone.
A record ages from its LAST write rather than from its recorded_at, so one a session folded later writes into survives up to a WithHistorySession window past what its timestamp says. Nothing folds under HistorySessionOff, where the two coincide.
Unlike the text delta log it is NOT clamped to WithGC's retention: history is app-visible data with a lifetime of its own, so a value either side of the tombstone window is valid.
The sweep HARD-DELETES, leaving no tombstone — nothing syncs these records, so nothing has a copy to be told they are gone. It is also the one collector that works in chunks, draining a long-accumulated log across transactions instead of inside the pass's own (see historyPurgeChunk).
func WithHistorySession ¶
WithHistorySession overrides how long one row's field-history record stays open to later writes by the same actor. Writes that land inside the window fold into it rather than appending: the record keeps saying what the fields held before the FIRST of them, and grows a span (see FieldHistory.seq and through_seq) instead of a row.
The window runs from when the record was opened, not from the last write, so a record never covers more than one window however long the editing runs.
What folding costs is the intermediate states: history answers "what did this hold before that editing session", not "replay the session". Pass HistorySessionOff to keep every write, weighing it against what per-write capture costs on an entity carrying a collaborative-text field. Default five minutes.
func WithIdempotencyRetention ¶
WithIdempotencyRetention overrides how long each GC pass keeps the idempotency keys claimed by MutateIdempotent/InvokeIdempotent. It only takes effect together with WithGC — without a pass, keys are kept forever, which is safe (a retry is never let through twice) but grows with API traffic.
This is the one retention where too short is a correctness problem, not just a cost one: a retry arriving after its key expired re-applies the write, with no signal that it did. So it is NOT clamped to WithGC's retention the way the text delta log is — set it above the longest retry window any caller uses (including an integration resuming after an outage), and remember that the bound is on the whole retry chain, not one hop. Default 24 hours.
func WithIndexBuild ¶
WithIndexBuild overrides how often the background pass looks for indexes to backfill, and the most rows one of its write transactions covers. A transaction may cover fewer: it also stops on an internal time budget, so that the write lock it holds is bounded in time rather than in rows.
Neither number changes what a read ANSWERS — an unbuilt index is simply not used — so this is purely about how fast a newly declared index starts paying off, against how long a build transaction holds a workspace's write lock. A non-positive interval disables the pass entirely, which leaves every index unready and every read on its scan fallback; that is a legitimate way to turn indexing off without changing a schema, and a trap otherwise.
Defaults: one minute, at most 500 rows per transaction.
func WithLeases ¶
WithLeases installs the lease.Locker the server and its background consumers dedup per-workspace work with: the GC and index sweeps skip a workspace whose lease another node holds, and an effects runtime built on this server leases each (consumer, workspace) drain the same way.
Without this option the server asks its storage adapter for a locker (lease.Provider) — both shipped adapters provide one — and falls back to a process-local locker, which dedups nothing across nodes. Leases are advisory: a locker error makes the guarded work proceed unleased, so the option changes how often idempotent work duplicates, never whether it happens.
func WithLimits ¶
WithLimits overrides request/response bounds. Fields that are not positive keep their defaults.
func WithLogger ¶
WithLogger sets the structured logger the engine's background work (the GC loop) writes to. Records are emitted with a "component" attribute so they can be filtered. The default is slog.Default(); pass a logger backed by a discard handler to silence the engine entirely.
func WithMerger ¶
WithMerger declares a merge hook for an opaque field of an entity declared on the same server. fieldPath is the dotted proto path ("doc", "outer.doc"); it must resolve to a singular bytes or message field marked (syncplane.v1.field_behavior).opaque.
The hook fires only for PATCH mutations whose mask touches the field while BOTH the stored row and the incoming value carry it — PUT (and EntityTx.Put) always replace whole rows, and one-sided PATCHes keep plain LWW replace/clear semantics.
Mergers are construction-time only: they are funcs, so unlike a schema they cannot be provisioned at runtime (see DynamicEntity, the CRUD-only dynamic tier).
func WithMeterProvider ¶
func WithMeterProvider(mp metric.MeterProvider) Option
WithMeterProvider sets the OpenTelemetry meter provider the engine records metrics on. The default is the global provider, no-op until an SDK is installed.
The instruments are listed in docs/reference/telemetry.md. Their names are a compatibility surface once dashboards are built on them, so they change like any other public API.
func WithMutator ¶
func WithMutator(name string, argsPrototype proto.Message, fn MutatorFunc, opts ...MutatorOption) Option
WithMutator declares a custom mutation handler. argsPrototype defines the expected google.protobuf.Any payload type; pass nil for a mutator that takes no arguments. Mutator declares one whose fn receives the arguments typed.
Mutators are construction-time only: they are funcs, so unlike a schema they cannot be provisioned at runtime (see DynamicEntity, the CRUD-only dynamic tier). That is also what keeps the mutator table lock-free on the push path — it never changes after New.
opts adjust the declaration; see MutatorAccess.
func WithNotifier ¶
WithNotifier replaces the in-process change-notification fan-out (e.g. NATS-backed).
A replacement should also implement pubsub.Activity, or SubscribeActivity stops answering and per-workspace background consumers fall back to sweeping on a timer to notice work another node's writes created.
One notifier may be shared by every app a Manager hosts: the server prefixes the ids it publishes and subscribes to with its own share of the workspace-id space, so two apps that both have a workspace "team" do not wake each other's clients.
func WithNotifyCoalescing ¶
WithNotifyCoalescing sets the per-workspace change-notification coalescing window (default 50ms). The first change in a quiet workspace notifies immediately; further changes within the window collapse into one trailing notification, capping the rate at which a workspace can wake its subscribers however write-heavy it gets. 0 disables coalescing. Applies on the send side of the notifier, so a shared notifier installed via WithNotifier also carries less traffic.
func WithPermissions ¶
func WithPermissions(p Permissions) Option
WithPermissions installs permission hooks (default: allow all).
func WithPresenceBus ¶
WithPresenceBus replaces the in-process fan-out for the ephemeral plane — rooms, presence and broadcast. The default is presence.NewLocal(), which reaches only this process, so a multi-node deployment that leaves it in place shows each client the participants its own node happens to be serving.
engine/presence/pgpresence is one over Postgres LISTEN/NOTIFY. One bus may be shared by every app a Manager hosts, on the same terms as a notifier: the room registry prefixes the topics it puts on the bus with the server's own share of the workspace-id space.
func WithRoomAnnounce ¶
WithRoomAnnounce sets how often a node re-announces the presence records of the sessions whose Watch streams it holds (default 5s), and with it how quickly a session that vanished without saying so disappears from everyone else's roster — three announce intervals.
It is the ephemeral plane's whole liveness mechanism, so it trades screen accuracy against bus traffic: the cost is one event per locally-held record per interval, and the benefit is a shorter ghost.
func WithSchemaRevision ¶
WithSchemaRevision advertises an app-defined schema/protocol revision to clients. It is an opaque token (a build hash, a monotonic schema number, whatever the app picks) echoed on every response that carries one: stream frames, push, pull, query, and bootstrap Begin. The server does not interpret it — clients configured with their own revision compare the two and react to a mismatch per their skew policy. Empty (the default) advertises nothing, so older clients and servers behave exactly as before. During a rolling deploy each node should advertise the revision of the code it is running, so a client pinned to one node sees a stable value.
func WithStrictAccess ¶ added in v0.2.0
func WithStrictAccess() Option
WithStrictAccess makes registration refuse an entity that declares no access option in a schema that uses the access model. Without it such an entity is outside the model: every caller the workspace gate admits reads and writes its rows, and registration logs a warning for each such entity when the schema declares a role. A schema that uses no access option at all is unaffected.
func WithTextCache ¶
WithTextCache sets how many bytes of encoded text state the server keeps decoded between writes, replacing DefaultTextCacheBytes. Zero disables the cache, which makes every write decode the stored document exactly as it did before the cache existed — a correct configuration, just a slower one.
The budget bounds ENCODED bytes; live heap is a multiple of that (see DefaultTextCacheBytes). Nothing about correctness depends on the value: an entry is only ever used when its recorded bytes match the ones being merged into, so a smaller cache costs decodes and a larger one costs memory.
func WithTextCompaction ¶
WithTextCompaction enables collaborative-text compaction. minPurged is how many tombstoned characters a document must give up before its row is rewritten; below that the reclaim does not pay for a pull of the whole field by every client. A value <= 0 leaves compaction off, which is the default.
It does nothing without WithGC: the sweep only touches rows the delta prune has already quietened, and that prune is a GC collector. A server with compaction on and GC off has no horizon to work below and rewrites nothing.
Compaction is not free of consequence, which is why it is opt-in: it is the one thing in the engine that can refuse a client's text write outright (see CodeTextStateStale), and the recovery costs that client the marks it had minted on top of state the server dropped. Enable it for workspaces whose documents are edited over months; leave it off if documents are short-lived.
Lowering minPurged re-sweeps every workspace from the beginning, since rows an earlier pass skipped may clear the lower bar. Raising it does not, because a row skipped under the old threshold is skipped under the higher one too.
func WithTextCompactionPacing ¶
WithTextCompactionPacing overrides how often the compaction sweep looks for workspaces with newly quiet rows, and how many rows one of its write transactions considers. It only takes effect together with WithTextCompaction.
Neither number changes what compaction RECLAIMS — a row that misses one pass is picked up by the next, since the window it belongs to stays unswept — so this is about how long a compaction transaction holds a workspace's write lock, and how promptly the reclaim happens. batch is a ceiling rather than a target: a transaction also ends once the rows it has taken exceed a fixed byte budget, so raising it past what the workspace's documents fill changes nothing. A non-positive interval disables the background pass, leaving compaction to manual CompactText calls; so does running GC on manual (WithGC with a non-positive interval), since only a GC pass moves the horizon this sweep works below.
Defaults: five minutes, 200 rows per transaction.
func WithTextDeltaRetention ¶
WithTextDeltaRetention overrides how long each GC pass keeps the collaborative-text delta log — the per-(row, field) fragments a pull folds to ship an edit instead of the whole document (see textdelta.go). It only takes effect together with WithGC, and never outlives that pass's retention.
The trade-off is pure wire size against storage: a span the log no longer covers is served as full state, which is correct, just larger. Shortening it costs bytes on the wire for clients that reconnect after a lull; lengthening it keeps one small row per text write around for that much longer. Default one hour.
func WithTracerProvider ¶
func WithTracerProvider(tp trace.TracerProvider) Option
WithTracerProvider sets the OpenTelemetry tracer provider the engine records spans on. The default is the global provider, which is no-op until the process installs an SDK — the same fallback shape as WithLogger and slog.Default().
Pass one explicitly rather than relying on the global when a test needs to assert against its own recorder, or when a host runs several engines that should report separately.
func WithUnknownMutatorForwarding ¶ added in v0.6.0
func WithUnknownMutatorForwarding() Option
WithUnknownMutatorForwarding makes a custom mutation whose name no WithMutator declares apply as a mutator that writes nothing, instead of being rejected with CodeInvalidArgument. It is for a server that forwards such mutations to another server through its WriteCapture.
Such a mutation is authorized by Permissions.CanMutate as any custom mutation is, and in a schema that uses the access model every caller admitted to the workspace may invoke it, as with MutatorAccess{Admitted: true}. Its args are not decoded. On a client push it is APPLIED: it advances the client's watermark and takes a sequence like any applied mutation. Invoke and InvokeIdempotent accept it too, with args of any type, and like any call that writes nothing they take no sequence. The WriteCapture receives it with CapturedWrite.Custom set and no Ops.
Because the mutation writes nothing here, a client that pushed it gets its ack before the rows it changes arrive from the server that runs it: the client drops its optimistic state for the mutation at once, and its rows can show the state without the mutation until those rows arrive.
func WithWriteCapture ¶ added in v0.6.0
func WithWriteCapture(c WriteCapture) Option
WithWriteCapture installs a WriteCapture. A server has at most one; a later WithWriteCapture replaces an earlier one.
func WithoutTextCompaction ¶ added in v0.6.0
WithoutTextCompaction keeps the rows of the named entities out of text compaction (see WithTextCompaction): the sweep and CompactText never rewrite them, whatever the threshold. Repeat the option to add entities. A name the server declares no entity for is ignored.
Use it for an entity whose rows mirror another server, as a replica's do: a rewrite the replication does not make leaves the replica's copy different from what the other server sent. The other server compacts its own rows, and the replica receives the result as an ordinary change. engine/upstream's Link.ServerOptions includes it for every bound entity.
type ParticipantFilter ¶
ParticipantFilter decides per participant whether a caller may see it. The argument is the server-stamped subject of the publishing session, empty for an unauthenticated one. A nil ParticipantFilter shows every participant.
It is resolved once when a topic is joined and applied to that topic's snapshot and to every later frame, so it must be a pure function of the subject — the same reasoning RowFilter is warmed once per stream under.
type Permissions ¶
type Permissions interface {
// CanAccessWorkspace decides whether the caller may touch this workspace at
// all. It is the tenant boundary: workspace_id arrives in the request and is
// otherwise self-asserted, so this hook is the only thing standing between an
// authenticated caller and any workspace id they care to name.
//
// The engine runs it for every workspace a request names — per batch on
// Push, per scope on Subscribe, and for the one workspace of Pull, Bootstrap
// and Query — before it opens a read snapshot, subscribes to the notifier,
// resolves FilterEpoch or writes a client watermark, so a denied request
// costs no storage work and leaves no trace in the workspace it was
// refused.
//
// Return nil to admit. Return DenyWorkspace(...) for a settled "no", which
// reaches the client as a permanent, actionable denial. Return any other
// error for a failure to DECIDE (the membership store is down); that
// surfaces as an infrastructure error the client retries, which is the
// outcome you want when the alternative is a client discarding good data
// over an outage.
//
// It runs on the hot path of every RPC, so keep it to a cached lookup —
// see the interface doc on execution context.
//
// This is workspace-level access. Row-level visibility WITHIN a workspace
// stays with ReadFilter; do not fold membership into per-row filters, which
// is how a single nil return leaks an entity across tenants.
CanAccessWorkspace(ctx context.Context, p Principal, workspaceID string) error
// CanMutate is called before a write is applied, once per Write. The engine
// flattens batches for you (see Write), so an implementation authorizing per
// CRUD never unwraps a batch itself. Return a Rejection (via Reject) for a
// business "no"; any other error aborts the RPC.
//
// It sees the same Write whether the write arrived over the wire or through
// the in-process API, which is what keeps an app's own handlers held to the
// policy its sync clients are. A mutator invocation authorizes ONCE as a
// Write{Custom} on its name and args; the rows its body writes are not
// authorized individually, on either path.
//
// It is not the only thing that can refuse a write. The engine enforces the
// schema's own rules first — in a schema that uses the access model, a
// write that can only be an operation no (syncplane.v1.entity).access rule
// admits — so a write this hook never sees has already been rejected. A policy therefore cannot widen what a schema
// forbids, only narrow it further. A write this hook admits must then pass
// the row check against the row it targets, which by default refuses a
// write to a row ReadFilter hides; see RowWritePermissions.
//
// Runs before the push write transaction opens, and between Apply's read and
// write transactions — but INSIDE the transaction on Server.Mutate. Keep it
// fast and side-effect free; see the interface doc for details.
CanMutate(ctx context.Context, p Principal, workspaceID string, w Write) error
// ReadFilter returns the row filter for an entity, or nil to allow all.
// Resolved before the read snapshot opens and memoized for the row scan, so
// keep it fast (see the interface doc).
//
// A filter hides row VALUES, not row existence. A subscribed client can
// still learn a denied row's entity, key and version: a deletion reaches
// every subscribed client as a tombstone, and a write that leaves a row
// denied may reach clients as one too — that tombstone is what revokes the
// row from a client that could read it before the write (see FilterEpoch).
// The server withholds it wherever the cursor proves the client never held
// the row — rows created past the cursor's position, non-members of a
// windowed or followed scope — but cannot prove that for older rows, so
// keys must not themselves be secrets: key rows by surrogate id and put
// the email, slug or invite code in a field the filter covers. See
// docs/explanation/limits-and-trade-offs.md.
//
// It gates the in-process reads too — Server.View and the reads an Apply
// closure makes — where a filtered row reads as absent rather than as a
// tombstone. Those callers can touch any entity, so they resolve every
// registered entity's filter up front rather than one per request.
//
// Unless RowWritePermissions supplies a write filter for the entity, it
// also gates writes: a PUT, PATCH or DELETE of a stored row it hides is
// refused with CodePermissionDenied, on the wire and in-process alike. On
// an entity that declares an access option the refusal is CodeAccessDenied,
// which is also the answer to a PATCH or DELETE of a row that does not
// exist.
//
// The returned filter is applied to rows of one request and must close over
// p rather than consult ctx: it runs during the row scan, after this hook
// returned.
ReadFilter(ctx context.Context, p Principal, workspaceID, entity string) (RowFilter, error)
// FilterEpoch returns the workspace's visibility epoch (0 if unused). It
// is stamped into cursors; a later mismatch forces clients to
// re-bootstrap, dropping rows that became invisible. Resolved before the
// read snapshot opens — keep it fast (see the interface doc). Pull calls
// it once per request, and an open Subscribe stream once per page it
// sends, live-tail pages included.
//
// Contract: row visibility normally propagates through row versions —
// editing a row re-evaluates its filter on the next pull and hides it
// with a tombstone if needed. ReadFilter predicates are pure functions
// of the row, so when a visibility INPUT changes outside a row edit
// (e.g. a membership table the filter consults), the app must either
// touch the affected rows or bump this epoch.
//
// An epoch bump alone forces every client into a full re-bootstrap on
// its next pull. Apps that also implement EpochReadFilters get a delta
// resync instead: only rows whose visibility actually changed ship.
FilterEpoch(ctx context.Context, p Principal, workspaceID string) (uint64, error)
}
Permissions hooks the server consults on every write (per Write) and every read (pull/bootstrap row filtering).
The caller's identity ¶
Every hook is handed the request's verified Principal explicitly, rather than leaving it to be fished out of ctx, so a policy cannot silently authorize as nobody. It is the zero (anonymous) Principal when no Authenticator is installed or when one admitted an unauthenticated request — a policy guarding untrusted traffic should lead with Principal.IsAnonymous.
The in-process API consults these hooks too. Server.Apply, Server.Mutate, Server.Invoke and Server.View authorize against the ctx principal, so an app handler that drives the engine directly is held to the same policy as a sync client — a write through Apply reaches CanMutate carrying the very CrudMutation the wire path would have carried. Code with no caller to authorize (a connector, a migration, a cron job) marks its ctx with Trusted, which skips these hooks entirely; see Trusted for why that is opt-in.
Partial implementations ¶
Embed AllowAll to implement only the hooks you care about — see its doc.
Execution context: these hooks run outside transactions, with one exception ¶
The server schedules every method here outside transaction scope: CanMutate runs before the push WRITE transaction opens (and, on Apply, between the read snapshot and the write transaction), and ReadFilter/FilterEpoch are resolved before the pull/query/bootstrap/View READ snapshot opens (their results memoized so the in-snapshot row scan only applies the pure predicate). A slow hook therefore does not hold the workspace write lock or pin a read snapshot — but it does stall the RPC it belongs to, so implementations must still be fast and should avoid blocking I/O. Do such work — token introspection, a membership lookup against another service — before the RPC (e.g. in middleware that stashes the result on ctx) and only consult the cached value here.
The exception is Server.Mutate, whose closure discovers its writes as it runs: there CanMutate is called from inside the write transaction, so a slow policy does hold the workspace write lock. That is the price of a serializable read-then-write under policy, it is confined to that one entry point, and Apply — which every app handler should prefer — does not pay it. A policy that cannot be fast should keep callers off Mutate.
CanMutate must also be a pure function of its arguments — free of observable side effects. It runs once per authorized write, but the engine relies on its verdict being reproducible: on the Mutate path the storage adapter may re-run the write closure and re-invoke the hook, and a side-effectful hook (audit logging, metering) would double-count. Such effects belong after the call commits, with knowledge of the committed result.
type Principal ¶
type Principal struct {
// Subject is the stable, issuer-scoped identity of the caller (a user id,
// a service account name). It is the field policies key on. Empty exactly
// when the caller is anonymous — an Authenticator that returns a Principal
// without a Subject is admitting an unauthenticated request.
Subject string
// Issuer names the authority that vouched for Subject: an OIDC issuer URL,
// an API-key realm, whatever the Authenticator uses to scope its subjects.
// Two principals from different issuers may share a Subject and are not the
// same caller, so a policy spanning issuers must compare both.
Issuer string
// Claims carries the verified attributes a policy may authorize on (roles,
// tenant, email, group membership). Values are whatever the Authenticator
// decoded — for JWT-shaped credentials, typically the JSON types
// (string, float64, bool, []any, map[string]any).
//
// Only put VERIFIED attributes here. The engine treats every claim as
// trustworthy because an Authenticator vouched for it; copying unverified
// request headers in makes them authorization inputs.
//
// Nil for principals that carry no attributes. Never written after the
// Authenticator returns.
Claims map[string]any
}
Principal is the verified identity of an RPC's caller — the engine's shared vocabulary for "who is calling". An Authenticator produces one per request (see authn.go), the engine stashes it on the request ctx, and every Permissions hook receives it explicitly so a policy can never accidentally authorize as nobody.
It is deliberately small and transport-agnostic: the engine never interprets a Principal beyond checking Subject for emptiness, so apps are free to carry whatever their policies authorize on. It is passed by value and must be treated as immutable — hooks run concurrently across in-flight RPCs and must not write to Claims.
A zero Principal is the anonymous caller: no authenticator is installed, or one deliberately admitted an unauthenticated request. Policies decide what anonymous may do; the engine's own default (AllowAll) allows everything, so a server exposed to untrusted traffic must install both an Authenticator and a Permissions policy that rejects the zero Principal.
func PrincipalFrom ¶
PrincipalFrom returns the ctx's verified principal and whether one was set.
Permission hooks do not need this — they are handed the principal as an argument precisely so they cannot forget it. Use it in code that only has a ctx: mutators, post-commit hooks, change-feed consumers.
The false case means no authentication ran for this ctx, which is NOT the same as an authenticated-but-anonymous caller (a Principal an Authenticator deliberately returned with no Subject). Code that only cares whether it has an identity should ignore the bool and call IsAnonymous on the result, which is correct in both cases.
func (Principal) Claim ¶
Claim returns the named claim and whether it was present. Safe on a nil Claims map.
func (Principal) IsAnonymous ¶
IsAnonymous reports whether the caller was not authenticated. It is the check a deny-by-default policy leads with.
func (Principal) StringClaim ¶
StringClaim returns the named claim when it is present AND a string. A claim of another type reports false rather than a coerced value, so a policy comparing against it cannot be fooled by a credential that typed the claim unexpectedly.
type Reader ¶ added in v0.3.0
type Reader interface {
// contains filtered or unexported methods
}
Reader is a transaction handle the typed reads accept: *EntityTx, *ViewTx or *ApplyTx. No other type implements it.
A typed read applies the same read rules as the handle's own methods — the caller's read filter and field guards on a ViewTx, an ApplyTx, an AsCaller view and a Server.Mutate for a caller who is not Trusted — and is valid only inside the closure or mutator body that received the handle.
type Reference ¶
type Reference struct {
// Target is the referenced entity's message descriptor.
Target protoreflect.MessageDescriptor
// KeyFields are the target's key fields, declared on Target.
KeyFields []protoreflect.FieldDescriptor
// Value is the entity-typed field of a reference message holding the
// target stub; nil when the field's type is the target entity itself.
Value protoreflect.FieldDescriptor
// Workspace is a reference message's workspace field, or nil when every
// stored value resolves in the holder's own workspace.
Workspace protoreflect.FieldDescriptor
}
Reference is the stored shape of one typed reference field, for callers outside the engine that read or build stored reference values. See (syncplane.v1.reference) for the two shapes it describes.
func RefOf ¶
func RefOf(fd protoreflect.FieldDescriptor) *Reference
RefOf describes fd as a typed reference to one entity, or returns nil when it is not one — including a polymorphic reference message, whose target is a oneof of entities and so has no single shape to describe.
func (*Reference) KeyPath ¶
func (r *Reference) KeyPath(kf protoreflect.FieldDescriptor) []string
KeyPath returns the proto field names from a stored reference value to one key field of the target — [key] on an entity-typed reference, [value, key] on a reference message — the segments a query path spells the key in.
func (*Reference) MutableStub ¶
func (r *Reference) MutableStub(value protoreflect.Message) protoreflect.Message
MutableStub returns the target stub inside a stored reference value being built, creating the embedded message of a reference message when absent.
func (*Reference) Stub ¶
func (r *Reference) Stub(value protoreflect.Message) (protoreflect.Message, bool)
Stub returns the target stub inside one stored reference value: the value itself, or the entity message a reference message embeds. Reports false for a reference message holding no stub.
func (*Reference) WorkspaceOf ¶
func (r *Reference) WorkspaceOf(value protoreflect.Message) string
WorkspaceOf returns the workspace a stored reference value names, or "" when it names none or the reference has no workspace field.
type RegisterAuthorizer ¶
type RegisterAuthorizer interface {
CanRegister(ctx context.Context, info RegisterInfo) error
}
RegisterAuthorizer gates runtime schema registration on the admin service. CanRegister returns nil to admit the call and a non-nil error to deny it (mapped to permission_denied on the wire). It is deny-by-default: a Manager with no authorizer configured uses DenyAll, so the endpoint is safe by construction — registration is a trusted, server-side operation, never something the public sync surface exposes.
func TokenAuthorizer ¶
func TokenAuthorizer(token string) RegisterAuthorizer
TokenAuthorizer admits a registration iff the request carries "Authorization: Bearer <token>" matching token, compared in constant time. It is the simplest trusted-caller story: share one secret with the Node backend that owns the schema. An empty token denies everything (fail closed).
type RegisterInfo ¶
RegisterInfo is the context an authorizer sees for a registration attempt: the target app and the request headers (where a bearer token rides).
type RegisterOption ¶ added in v0.2.0
type RegisterOption func(*registerConfig)
RegisterOption adjusts one call to RegisterDescriptorSet, RegisterEntity, RegisterDynamicEntity or Manager.Register.
func AllowAccessChange ¶ added in v0.2.0
func AllowAccessChange() RegisterOption
AllowAccessChange lets a registration change the access model of an entity that is already registered: its access or grant options, or the names of the enum values its grant role field matches. Every client resyncs the rows the change affects.
It also lets a registration declare the first role of a schema that served callers without one, or remove the last. That decides whether the workspace gate refuses a caller that holds no permission, so callers without a grant row lose or gain access to every workspace.
type RegisterResult ¶
type RegisterResult struct {
// Entities are the wire names registered (or already registered) by this
// descriptor set, sorted.
Entities []string
// Revision is the stable schema revision derived from the canonical
// descriptor-set bytes — the value clients see as SchemaRevision and the
// Manager persists for idempotent re-registration.
Revision string
// Changed reports whether the catalog actually moved (false on an identical
// re-registration).
Changed bool
}
RegisterResult reports the outcome of ingesting a FileDescriptorSet.
type RegisterStatus ¶
type RegisterStatus int
RegisterStatus reports how a registration changed the app's schema.
const ( // RegisterUnchanged: the submitted schema was identical; a no-op. RegisterUnchanged RegisterStatus = iota // RegisterCreated: a new app was registered. RegisterCreated // RegisterUpdated: an existing app's schema was additively evolved. RegisterUpdated )
func (RegisterStatus) String ¶
func (s RegisterStatus) String() string
String renders the status for logs and diagnostics.
type Rejection ¶
Rejection is a business-level "no" to a mutation. It becomes a MUTATION_STATUS_REJECTED result (an ack the client drops the mutation on), never an RPC error.
func AsRejection ¶
AsRejection extracts a Rejection from an error chain.
type ReplicaTx ¶ added in v0.6.0
type ReplicaTx struct {
// contains filtered or unexported fields
}
ReplicaTx is the transaction a Replicate call's fn writes through. It is valid only during fn and is not safe for concurrent use.
A Put or Delete that returns an error writes nothing.
func (*ReplicaTx) Delete ¶ added in v0.6.0
Delete writes a tombstone for the row of entity with the given key. Deleting a row that is absent or already deleted does nothing.
It returns an error when entity is not registered, and a Rejection (see AsRejection) for a key the naming rules refuse.
func (*ReplicaTx) Get ¶ added in v0.6.0
Get returns the stored row for entity and key as it stands in this transaction, including the transaction's own writes. found is false for a row that was never written or whose tombstone was collected; a tombstone is found, with Deleted set.
func (*ReplicaTx) Put ¶ added in v0.6.0
Put stores value as the row of entity with the given key. Writing the bytes the live row already holds does nothing.
It returns an error when entity is not registered, when value does not decode as the entity's message, or when its key fields do not derive key. It returns a Rejection (see AsRejection) for a key the naming rules refuse, and for a row this server cannot store: a keyed list that holds one key twice, an invalid grant row, an access chain past Limits.MaxAccessDepth or Limits.MaxAccessParents, or more index entries than the Limits allow.
func (*ReplicaTx) RejectLate ¶ added in v0.6.0
func (r *ReplicaTx) RejectLate(origin MutationOrigin, code, message string) error
RejectLate records that the mutation origin names, which this server acknowledged as applied, was rejected after the acknowledgement. The client that pushed it receives the rejection as a LateRejection on the first Pull or Subscribe page whose position reaches the transaction's sequence, under the same caller only. The rows the mutation wrote are not changed: revert them with Put and Delete in the same transaction.
The record takes the transaction's sequence, and allocates it when the transaction has not written yet, so the call wakes the client's stream like a row write does. A second record for the same mutation replaces the first. The record is kept and expired with the client's other rejection records: a client that pulls after they expired, or bootstraps, does not receive it. The size bound on those records does not drop it. A message longer than 1 KiB is stored and delivered cut to 1 KiB.
It returns an error when origin has no Client or no MutationID, or when code is empty.
func (*ReplicaTx) Seq ¶ added in v0.6.0
Seq returns the sequence the transaction's writes take, or 0 before the first write.
func (*ReplicaTx) Tx ¶ added in v0.6.0
Tx returns the storage transaction, for state the caller keeps beside the rows, such as consumer shadows (see storage.WriteTx.PutConsumerShadow). What is written through it commits or rolls back with the call. A row written through it skips every structure the server derives from rows; write rows with Put and Delete.
type RoomDenial ¶
type RoomDenial struct {
// Message explains the denial. It reaches the client, so keep it free of
// detail the caller has not earned.
Message string
}
RoomDenial is a PERMANENT "no" from CanJoinRoom: this caller may not be in this room, and retrying will not change that. It drops the topic from the caller's Watch stream with reason ACCESS_REVOKED, so a client stops showing the room instead of reconnecting forever.
It is distinct from WorkspaceDenial because it is narrower: the caller keeps the workspace and everything else in it, and loses one room.
func AsRoomDenial ¶
func AsRoomDenial(err error) (*RoomDenial, bool)
AsRoomDenial extracts a RoomDenial from an error chain.
func (*RoomDenial) Error ¶
func (d *RoomDenial) Error() string
type RoomPermissions ¶
type RoomPermissions interface {
// CanJoinRoom admits or refuses one topic. Return DenyRoom for a settled
// no; any other error drops the topic as retryable, so an outage never
// reads as a revocation.
CanJoinRoom(ctx context.Context, p Principal, workspaceID string, topic presence.Topic) error
// VisibleParticipants returns the filter applied to this caller's view of
// the room, or nil to show everyone.
VisibleParticipants(ctx context.Context, p Principal, workspaceID string, topic presence.Topic) (ParticipantFilter, error)
}
RoomPermissions is an optional Permissions extension covering the ephemeral plane. A Permissions that does not implement it admits every caller who cleared the room's own gate — workspace access, and the anchor row's read filter for an anchored topic — and shows them every participant.
Reach for it when those two are not the whole answer. Being able to READ a document is not the same as being allowed to know who else is looking at it: an app where a reviewer browses anonymously, or where an admin's attention is not something the author should see, needs the roster filtered even though every one of those callers may read the row the room is anchored to.
Both hooks run on the join gate, and CanJoinRoom runs again on the stream's heartbeat, so a settled denial takes effect within one heartbeat interval rather than whenever the client next reconnects. Neither runs per event.
Embed AllowAllRooms to implement one hook and inherit the other.
type Row ¶ added in v0.3.0
Row is a decoded row together with what the engine recorded about it, as ScanRows and QueryRows yield it.
type RowFilter ¶
RowFilter decides per row whether a client may read it. The message is the decoded entity row. A nil RowFilter allows all rows.
func FilterRows ¶ added in v0.3.0
FilterRows returns a RowFilter that passes each row to fn as a T. It refuses a row of another message type.
func (p *policy) ReadFilter(ctx context.Context, pr server.Principal, ws, entity string) (server.RowFilter, error) {
if entity != "issue" {
return nil, nil
}
return server.FilterRows(func(_ string, issue *issuev1.Issue) bool {
return issue.GetOwner() == pr.Subject
}), nil
}
On an entity registered from a descriptor set, each row reaches the filter as a dynamic message and is copied into a new T first, at the cost of one marshal and one unmarshal per row.
type RowMeta ¶
type RowMeta struct {
// Version is the workspace sequence of the mutation that last wrote the row.
// Hand it back through WithExpectedVersion (or Patch's expected argument) to
// make the follow-up write a compare-and-swap.
Version uint64
// Actor attributes that write — the caller's subject for a client push or an
// in-process write, the label a write made under Trusted/TrustedAs gave
// itself, or both when a bypass ran inside a caller's request. The zero Actor
// means the write was unattributed, which is every write on a server with no
// Authenticator installed.
Actor storage.Actor
}
RowMeta is what the engine recorded about a stored row, returned alongside the decoded message by the GetMeta reads. It is the engine's own bookkeeping, never anything the writer put in the message.
Both fields are replaced by every write, so RowMeta answers "who last touched this row, at which sequence" and never "who touched it, in order".
type RowWriteFilter ¶ added in v0.2.0
RowWriteFilter decides whether one write may change an existing row. stored is the row the write replaces, patches or deletes, decoded as it stands inside the write transaction, and w.Crud is always set. Return nil to admit the write, or a Rejection (via Reject) to refuse it; any other error aborts the RPC.
It runs while the workspace write lock is held and may run again when the storage adapter retries the transaction, so it must be fast and a pure function of its arguments and of what it closed over when WriteFilter returned it. It must not retain or modify stored.
type RowWritePermissions ¶ added in v0.2.0
type RowWritePermissions interface {
// WriteFilter returns the check for writes to existing rows of the named
// entity, or nil to check them with the entity's ReadFilter.
//
// The engine resolves it at most once per entity per request, before the
// write transaction opens — except on Server.Mutate, which discovers its
// writes inside the transaction (see the Permissions doc on execution
// context). It carries the cost contract of ReadFilter, and the returned
// filter must close over p rather than consult ctx.
WriteFilter(ctx context.Context, p Principal, workspaceID, entity string) (RowWriteFilter, error)
}
RowWritePermissions is an optional Permissions extension for write rules that depend on the row a write targets, such as "only the owner may delete a task". CanMutate sees only the write, so it cannot state such a rule.
Every write that is not Trusted and that targets a live row is checked against the stored row before it is applied: a PUT that replaces the row, a PATCH, and a DELETE. A create, which is a write to a key with no live row, is not checked and is left to CanMutate, which sees the new value. The rows a custom mutator's body writes are not checked either; the verdict on the invocation covers them.
The check for an entity is the RowWriteFilter that WriteFilter returns. When it returns nil, or the Permissions does not implement this interface, the check is the entity's ReadFilter: a caller may change a row exactly when they may read it, and a write to a row the ReadFilter hides is refused with CodePermissionDenied. An entity with neither filter is not checked and costs no extra read.
A stored row that does not decode cannot be checked, so a write to it is refused with CodePermissionDenied whenever the entity has a check; a Trusted write repairs it. A refused write does not disclose the row's version.
On an entity that declares an access option, these two refusals use CodeAccessDenied. The access model refuses a PATCH or DELETE of a row that does not exist with that code, so the answer does not tell a hidden row from a missing key. A WriteFilter that refuses rows the caller cannot read keeps the same property only when it refuses them with CodeAccessDenied.
func (p *policy) WriteFilter(
_ context.Context, who server.Principal, _, entity string,
) (server.RowWriteFilter, error) {
if entity != "task" {
return nil, nil // writable exactly when readable
}
member := p.engagementsOf(who) // cached lookup, resolved once per request
return func(w server.Write, stored proto.Message) error {
task := stored.(*taskv1.Task)
if !member[task.GetEngagementId()] {
return server.Reject(server.CodePermissionDenied, "no access to this task")
}
if w.Crud.GetOp() == syncplanev1.CrudOp_CRUD_OP_DELETE && task.GetOwner() != who.Subject {
return server.Reject(server.CodePermissionDenied, "only the owner may delete this task")
}
return nil
}, nil
}
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server is one app's sync engine: it implements syncplanev1connect.SyncServiceHandler over a storage.Adapter. Build one with New, declaring its schema and behaviour as options (WithEntities, WithMutator, WithMerger, WithPermissions); serve it with HTTPHandler, or Handler to mount it on a mux of your own. Schemas that arrive after construction go through RegisterDescriptorSet or RegisterDynamicEntities.
A Server is safe for concurrent use once New returns. Everything a request reads is either immutable (the mutator table) or swapped atomically (the entity catalog, so runtime registration can land under live traffic).
func New ¶
New builds a sync engine over store. Everything the options declare — entities, mutators, mergers — is installed before it returns, so a misdeclared schema surfaces as one error here, and nothing (the GC loop included) starts unless the whole declaration is good.
New does NOT take ownership of store. Close stops the engine's background work; closing the adapter stays the caller's job, because it may outlive the server and a Manager shares one root adapter across every app it hosts. The usual bring-up is therefore two defers:
store, err := sqlitestore.Open(path)
…
defer store.Close()
srv, err := server.New(store, server.WithEntities(&todov1.Todo{}))
…
defer srv.Close()
func (*Server) AdvanceConsumer ¶
func (s *Server) AdvanceConsumer(ctx context.Context, workspaceID, consumer string, up ConsumerUpdate) error
AdvanceConsumer commits a consumer's new feed position together with the shadow writes derived from the page it covers, in ONE transaction.
The atomicity is the point, not an optimization. An effect has no reconcile pass, so the only recovery from a crash mid-page is redelivery — and redelivery only re-fires the handler if the shadows still describe the state the consumer acted on last time. A shadow that advanced without its position makes the redelivered change compare equal to it, and the trigger is lost silently. Committing both together makes every crash a duplicate instead, which is what the at-least-once contract already promises.
Callers therefore run handlers FIRST and call this after, never the reverse. It opens a write transaction, so it must not be called from inside a mutator; a context threaded from one fails fast rather than deadlocking.
It returns ErrCursorForeign and records nothing when up.Cursor names a history the store does not hold: a nonzero Epoch or Lineage that the store does not report, or a Seq above the current sequence. That is the case when the workspace was deleted and restored, or the store swapped or restored, after Changes returned the cursor. A cursor with zero Epoch and Lineage is checked by its Seq alone.
It returns ErrConsumerMoved and records nothing when up.From is set and the stored position differs from it.
func (*Server) Apply ¶
Apply is the in-process write path: fn reads from a consistent snapshot and records the writes it wants, and the engine authorizes them and applies them as one atomic mutation. It is what an app's own API handlers, agents and background jobs should be written against.
It behaves like a client push, deliberately. The recorded writes go through the same EntityTx that a mutation off the wire does, so per-field LWW, keyed-list and collaborative-text merges, compare-and-swap and the delta log all mean here exactly what they mean to a sync client — and the CrudMutation handed to CanMutate is the one a client would have sent, so a policy cannot tell the two paths apart.
err := srv.Apply(ctx, ws, func(tx *server.ApplyTx) error {
var issue issuev1.Issue
found, version, err := tx.Get(&issue, key)
if err != nil || !found {
return server.Reject(server.CodeConflict, "no such issue")
}
issue.Status = "done"
return tx.Patch(&issue, []string{"status"}, &version)
})
Three phases, and what runs where ¶
read snapshot fn runs: reads are live, writes are recorded. No write lock. (no tx) CanAccessWorkspace, then CanMutate per recorded write. write tx the recorded writes are applied at one sequence.
Reads apply the caller's read rules as View's do, and clear each field a field guard hides from the caller. A Put of such a row keeps the stored value of each field the caller may not read.
No permission hook ever runs inside a transaction on this path, and none of your code runs while the workspace's write lock is held. A policy that needs to do I/O can therefore afford to, and a slow handler does not serialize every other writer to the workspace the way Mutate's does.
fn runs exactly once ¶
The read snapshot runs fn at most once (storage adapters never retry a read transaction), and the write transaction replays the recorded writes without re-entering your code — so unlike Mutate, there is no retried-closure contract here. Capture what you like; an object you build inside fn is still the object that was written.
What you give up relative to Mutate ¶
- Reads see the snapshot, not your own recorded writes. Get on a key you have already written returns an error rather than a stale row; scans and queries silently do not include recorded writes.
- Reads and writes are not one serializable unit. The snapshot can be stale by the time the writes apply, exactly as a client's optimistic state can be. Per-field LWW is what resolves that, and Patch's expected version is the opt-out when a concurrent edit must be noticed rather than merged.
- Writes are buffered in memory, so a bulk import belongs in chunks (or in Mutate, which streams).
Permissions ¶
Authorized against the ctx principal; a ctx with no principal authorizes as anonymous, which a deny-by-default policy refuses. System work with no caller to authorize marks its ctx with Trusted. A write to an existing row also passes the row check (see RowWritePermissions) when the write transaction applies it. A rejection, from a hook or from the row check, is returned as an error and nothing is applied — recovered with AsRejection, or AsWorkspaceDenial for a settled workspace denial.
A call that records no writes opens no write transaction at all: it consumes no sequence, notifies nobody, and leaves a workspace that did not exist unregistered.
fn runs inside the read snapshot, so it must not start another transaction — no nested Apply, Mutate or View. Record the writes and let this call apply them.
func (*Server) ApplyIdempotent ¶
func (s *Server) ApplyIdempotent( ctx context.Context, workspaceID, key string, fn func(tx *ApplyTx) ([]byte, error), ) (WriteOutcome, error)
ApplyIdempotent is Apply guarded by a caller-supplied idempotency key: the first call for a key runs fn and records what it did, and every later call with the same key skips fn and replays that record. It is the write path for an HTTP handler behind a retrying client, or an at-least-once effects handler reacting to the change feed.
The key semantics are MutateIdempotent's exactly — per workspace and per caller, claimed in the same transaction as the writes, not recorded for a failed call, collected on WithIdempotencyRetention. See MutateIdempotent for the full contract.
The bytes fn returns are the recorded response, replayed verbatim on every later call with the same key:
out, err := srv.ApplyIdempotent(ctx, ws, r.Header.Get("Idempotency-Key"),
func(tx *server.ApplyTx) ([]byte, error) {
if err := tx.Put(&issue); err != nil {
return nil, err
}
return json.Marshal(response{ID: issue.GetId()})
})
if err != nil { … }
w.Write(out.Result) // the first attempt's response, however often it retries
func (*Server) BeginUpload ¶ added in v0.4.0
func (s *Server) BeginUpload( ctx context.Context, req *connect.Request[syncplanev1.BeginUploadRequest], ) (*connect.Response[syncplanev1.BeginUploadResponse], error)
BeginUpload starts or resumes the upload of one blob; see syncplanev1connect.BlobServiceHandler for the wire contract.
When the server's Permissions implements BlobPermissions, BeginUpload asks CanUploadBlob after the request is found valid, also for a blob the server already stores. A ctx marked with Trusted skips the workspace gate and that hook.
func (*Server) BlobHandler ¶ added in v0.4.0
BlobHandler returns the mount path and HTTP handler for the blob service, syncplanev1connect.BlobServiceHandler. Without WithBlobStore every call to it fails with unimplemented.
It shares the sync service's interceptor chain. Its request-size bound is Limits.MaxRequestBytes, raised where needed to fit one chunk of blob.ChunkSize bytes.
func (*Server) Bootstrap ¶
func (s *Server) Bootstrap(ctx context.Context, req *connect.Request[syncplanev1.BootstrapRequest], stream *connect.ServerStream[syncplanev1.BootstrapResponse]) (err error)
Bootstrap streams a full workspace snapshot: Begin, Chunk*, End. The snapshot is paged: the Begin cursor comes from one short read tx, then each page of rows is read in its own short read tx, so a large workspace never pins a database snapshot — and never holds back whatever reclamation that blocks in the store — for the duration of the stream.
Paging means the stream is NOT one consistent snapshot — and that is fine. Rows only ever gain versions, snapshots never ship tombstones, and the client follows Bootstrap with a Pull from the Begin cursor: anything written after Begin was issued is re-delivered (or tombstoned) by that pull, overwriting whatever mixture of pages the bootstrap saw. A row deleted mid-bootstrap either vanishes from a later page (then the pull's tombstone is a no-op) or ships in an earlier page (then the pull's tombstone removes it). A row created after Begin never ships on a page; that pull delivers it.
Rows go out entity by entity, in the order Begin announces — priority entities, then the subscription set, then the rest (see bootstrapEntities). A cold client applies chunks as they arrive, so that order is what it paints first; the announced list is also how it tells an entity still queued from one that shipped no rows at all.
A request carrying `resume` continues an interrupted snapshot instead of starting a new one: entities that already shipped in full are skipped, the one that was mid-scan restarts after its last delivered key, and the Begin cursor is re-issued unchanged so the healing pull still covers the whole span. Begin announces the full entity order either way — by the end of a resumed stream every entity on it is complete in the client's staging, whichever attempt delivered it. See bootstrapresume.go.
Begin carries an estimated row count per entity (row_estimates), the entity's live rows as of Begin, when the store's ReadTx implements storage.RowCounter and the snapshot ships every live row of every announced entity. A read filter, the access model or a narrowing subscription that hides rows from the snapshot means no estimate (see rowEmitter.rowEstimates).
Access is re-checked while the snapshot streams: once a heartbeat interval (WithHeartbeat) has passed since the workspace gate last admitted the caller, the gate runs again before the next page, and a refusal ends the stream with the gate's error. Rows sent before that stay sent.
Every page reads the workspace incarnation the Begin cursor names. When the workspace is deleted and restored while the snapshot streams, the stream ends with CodeAborted, and a retry starts a new snapshot.
With subscriptions, only subscribed entities are visited and only rows matching their predicates ship; read-filtered rows are skipped the same way, and a windowed subscription ships exactly its window's members.
How an entity is visited is decided per entity, and the two ways produce the same rows in the same order:
- CANDIDATES, when the entity's visible rows are named by rules the server can enumerate — a predicate an index serves or one pinning the whole row key, a window's membership, a follow closure. The snapshot then reads those rows and nothing else, so a partial scope costs what it ships (see bootstrapCandidates).
- a SCAN of the entity, for everything else: full sync, a scope covering the whole entity, a predicate neither an index nor a pinned key reaches, or a candidate set too large to be worth narrowing.
The resume position means the same thing on both — the last key shipped for the entity, in key order — so an attempt that narrowed candidates and one that scanned can follow each other without skipping or repeating a row.
The Begin cursor records the subscription set and filter epoch so a later change of either is detected by pull, which then delta-resyncs the visible-set difference (or resets when it cannot); it also records the window and closure key-sets, so the first pull can diff against what the snapshot actually shipped.
func (*Server) BuildIndexes ¶
BuildIndexes brings every index of every registered entity up to date for one workspace, and marks each ready. Indexes already ready under their current spec are skipped, so a repeat pass over an unchanged workspace costs one state read per index.
A pass that leaves every index ready records the catalog's build mark on the workspace, which is what lets the next background pass skip it without reading any of that state (see storage.Adapter.ListStaleIndexWorkspaceIDs). Nothing is recorded when an index ends the pass unready — a concurrent re-registration is the way that happens — so the workspace stays selected until a pass finishes under one catalog.
An entity whose indexes cannot be built stays unready, and queries on its indexes scan. A stored row past an index limit is the lasting cause (see storage.MaxIndexEntryBytes). The other entities still build, and the returned error joins one error for each entity that did not.
It is safe to call at any time: the build is idempotent, and readiness is only claimed once the whole entity has been walked. Callers do not normally need it — the background loop covers every workspace — but a test or a migration that wants an index usable immediately can force the pass.
Do not call it from inside a mutator: it opens write transactions, which would deadlock against the one the mutator already holds.
func (*Server) Changes ¶
func (s *Server) Changes(ctx context.Context, workspaceID string, after Cursor, limit int, fn func(Change) error) (next Cursor, more bool, err error)
Changes drains committed row changes after the cursor, in (seq, entity, key) order, invoking fn for at most limit rows (limit <= 0 uses the MaxPullChanges limit). It returns the advanced cursor and whether more changes were left unread. Engine-internal rows count toward the limit without reaching fn, so a page can hold fewer changes than limit, or none, while more is true: keep paging until more is false.
The feed is the engine's outbox: a consumer that persists the returned cursor only after acting on the page gets at-least-once delivery of every change, in order, across crashes — dedupe by (entity, key, seq). A consumer that reacts by writing back should do so through MutateIdempotent keyed on the change, since redelivery is the design and not the exception. Only the latest state of a row is observable, not every intermediate write (coalescing by row, like pull). The feed is trusted server-side API: read filters and subscription scoping do not apply. A stored row of a registered entity that does not decode is logged and left out, and the cursor moves past it; a later write that replaces the row is delivered as usual.
When the cursor cannot be resumed — below the tombstone horizon, above the current sequence, from another store lineage, or from a history a restore from backup discarded — Changes returns ErrCursorTooOld along with a cursor at the workspace's current sequence: resync against current state first, then resume from that cursor. In every case but the horizon the error is ErrCursorForeign.
func (*Server) Close ¶
Close stops background work: the GC goroutine, the text compaction loop, the index backfill, the room registry's announce sweep, and the notify-coalescing timers. It waits for a running GC or compaction pass to end. It is idempotent and does NOT close what the caller owns — not the storage adapter, not a notifier installed with WithNotifier, not a bus installed with WithPresenceBus. Stopping the coalescing timers is what keeps a shared notifier from receiving a trailing publish after the process announced it was done writing; closing the registry likewise stops it announcing presence for sessions this process is no longer serving.
func (*Server) CollectGarbage ¶
CollectGarbage runs one manual collection pass (tombstones, idle clients' verdicts and, with WithClientRetention, their watermarks) for a single workspace using the retention configured via WithGC. With WithBlobStore it also collects the workspace's blobs (see WithBlobRetention). The pass runs in one write transaction, plus one transaction per further chunk of expired field history (see historyPurgeChunk); it is stateless and safe to re-run, and an interrupted drain resumes on the next pass.
Do not call it from inside a mutator: it opens a write transaction, which would deadlock against the one the mutator already holds. When the context is threaded from the mutator the call fails fast with an error instead.
func (*Server) CompactText ¶
CompactText runs one workspace's text-compaction sweep to completion, returning how many rows it rewrote. It sweeps from wherever the last pass stopped up to the workspace's current field-delta horizon, in write transactions of at most the configured batch (see WithTextCompactionPacing), and reports 0 without touching the store when compaction is off.
It is safe to call at any time: each batch commits its rewrites and its mark together, so an interrupted sweep resumes where it stopped rather than redoing the workspace, and a rewrite that happens twice costs a sequence and nothing else. Callers do not normally need it — the background pass covers every workspace — but a test or a maintenance script that wants the reclaim now can force it.
Do not call it from inside a mutator: it opens write transactions, which would deadlock against the one the mutator already holds.
func (*Server) ConsumerPendingWorkspaces ¶
func (s *Server) ConsumerPendingWorkspaces(ctx context.Context, consumer, after string, limit int) ([]string, error)
ConsumerPendingWorkspaces returns up to limit workspaces where the named consumer has changes it has not acted on, ordered by id and starting strictly after `after` — pass "" to start, then the last id of a page to continue.
It answers "where is my work" for a background consumer in one query, which is what keeps that question independent of how many workspaces exist: the alternative is a read transaction per workspace, almost all of which report nothing to do. A workspace the consumer has never acted on is pending, so a newly registered consumer discovers everything it has to catch up on here.
The answer is optimistic and a snapshot: a listed workspace may hold nothing but changes the consumer filters out, and one written during the call may only appear on the next. It is never short, though — a workspace whose position was behind when the call ran is always listed — because for a consumer that finds work this way, an omission is an effect that never fires.
func (*Server) ConsumerPosition ¶
func (s *Server) ConsumerPosition(ctx context.Context, workspaceID, consumer string) (Cursor, bool, error)
ConsumerPosition returns where a named effect consumer has reached in the workspace's change feed, and whether it has ever recorded a position. A consumer with none reads as (zero cursor, false, nil) — a first run, which for a workspace that has collected tombstones means the first Changes call will ask for a resync (see ErrCursorTooOld).
func (*Server) ConsumerPositions ¶
func (s *Server) ConsumerPositions(ctx context.Context, workspaceID string) ([]storage.ConsumerPosition, error)
ConsumerPositions returns every effect consumer's position in the workspace, ordered by name, for reporting how far each has fallen behind CurrentSeq.
func (*Server) ConsumerShadow ¶
func (s *Server) ConsumerShadow(ctx context.Context, workspaceID, consumer, entity, key string) ([]byte, error)
ConsumerShadow returns the snapshot a consumer recorded for one row, or nil if it holds none — which is both "never seen" and "keeps no shadow of it".
func (*Server) CurrentSeq ¶
CurrentSeq returns the workspace's current sequence — the head of its change feed, and 0 for a workspace that has never been written. A feed consumer's distance from it is its lag, which is what tells a stalled consumer apart from one with nothing to do.
func (*Server) DeleteWorkspace ¶ added in v0.4.0
DeleteWorkspace removes every piece of state the workspace holds: rows and tombstones, client watermarks and rejection verdicts, the collaborative-text delta log and compaction floors, index entries, idempotency records, effect consumer positions and shadows, and the workspace's sequence and store epoch. It does this in one storage transaction, after any write in flight commits. With WithBlobStore it then deletes the workspace's blobs and staged uploads. When that fails, it returns an error and the next blob GC pass of WithGC deletes them. A RestoreWorkspace that lands before the blobs are gone stops the deletion: the blobs the restored workspace uploads stay, and blob GC treats the blobs left from before as unreferenced.
The id then stays refused until RestoreWorkspace:
- A sync client's next request gets the permanent workspace denial (permission_denied with CodeWorkspaceAccessRevoked), and the client stops syncing the workspace. An open Subscribe stream drops the workspace with a reset, and the client's next bootstrap gets the denial.
- Apply, Mutate, Invoke and View return an error that matches ErrWorkspaceDeleted. See ErrWorkspaceDeleted for Trusted calls.
- WorkspaceIDs does not list it, and no background pass visits it.
Deleting a workspace that holds no state still refuses its id. Deleting a deleted workspace changes nothing. Neither is an error.
It runs no permission hook: expose it only to callers the application has authorized itself. It must not be called from inside a mutator or another write transaction, and returns an error when ctx shows that it is.
State kept outside the storage adapter stays: a cursor-state store set with WithCursorStateStore keeps its entries until it evicts them, and presence rooms keep their ephemeral sessions until the sessions end.
func (*Server) Entities ¶
func (s *Server) Entities() []EntityMeta
Entities returns metadata for every registered entity, sorted by name.
func (*Server) Entity ¶
func (s *Server) Entity(name string) (EntityMeta, bool)
Entity returns metadata for the entity with the given wire name, and whether it is registered.
func (*Server) EntityKey ¶
EntityKey derives the wire entity name and row key from a registered entity message — the same derivation push and EntityTx use, exposed so out-of-process integrations (connectors, outbox consumers) can address rows without reimplementing the key-field escaping rules.
func (*Server) GetChunk ¶ added in v0.4.0
func (s *Server) GetChunk( ctx context.Context, req *connect.Request[syncplanev1.GetChunkRequest], ) (*connect.Response[syncplanev1.GetChunkResponse], error)
GetChunk returns one chunk of a complete blob; see syncplanev1connect.BlobServiceHandler for the wire contract. It fails with not_found for a blob the caller cannot read, by the rule StatBlobs states, in the same way as for a blob the server does not have.
It fails with invalid_argument for a malformed digest. A ctx marked with Trusted reads every blob a live row names.
func (*Server) HTTPHandler ¶
HTTPHandler returns every service already mounted at its own path, for the common case where this server is the only thing the listener serves:
http.ListenAndServe(addr, srv.HTTPHandler())
Connect routes by full method path, so a service cannot be served at an arbitrary root — mounting is not optional, only who does it. Use Handlers instead to mount them on a mux that also carries the app's own routes.
func (*Server) Handler ¶
Handler returns the mount path and HTTP handler for the sync service. HTTP/1.1 suffices (unary + server-streaming only). WithReadMaxBytes is the front door for MaxRequestBytes: it bounds every request body (and its decompressed size) before the body is buffered or unmarshaled, so the documented per-request limits no longer sit behind an unbounded read.
The returned handler gzips streaming responses for clients that ask for it with Accept-Encoding, which is how a browser asks — see compress.go for why Connect's own compression does not cover them.
A server mounted this way serves the sync plane and nothing else. Use Handlers to mount every service it offers, rooms included.
Example ¶
ExampleServer_Handler mounts the sync service alongside an app's own routes. HTTPHandler is the shortcut for when it is the only thing on the listener.
package main
import (
"fmt"
"log"
"net/http"
"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"
)
func main() {
srv, err := server.New(newExampleStore(), server.WithEntities(&todov1.Todo{}))
if err != nil {
log.Fatal(err)
}
defer srv.Close()
mux := http.NewServeMux()
path, handler := srv.Handler()
mux.Handle(path, handler)
mux.HandleFunc("/healthz", func(w http.ResponseWriter, _ *http.Request) {
fmt.Fprintln(w, "ok")
})
fmt.Println(path)
}
// newExampleStore opens a throwaway store for the examples that only need a
// server to exist.
func newExampleStore() *sqlitestore.Store {
dir, err := os.MkdirTemp("", "syncplane-example-*")
if err != nil {
log.Fatal(err)
}
store, err := sqlitestore.Open(filepath.Join(dir, "app.db"))
if err != nil {
log.Fatal(err)
}
return store
}
Output: /syncplane.v1.SyncService/
func (*Server) Handlers ¶
Handlers returns every Connect service this server mounts, keyed by mount path. Mount all of them on a mux that also carries the app's own routes:
for path, h := range srv.Handlers() {
mux.Handle(path, h)
}
Ranging over this rather than naming the services one at a time is what keeps a deployment from silently missing one the engine gains later.
func (*Server) Invoke ¶
func (s *Server) Invoke(ctx context.Context, workspaceID, mutatorName string, args proto.Message) error
Invoke runs a registered mutator by name through Mutate, reusing client-triggered mutator logic for server-side triggers. args must match the registered prototype's message type, or be nil for the prototype's zero value; a mutator registered without a prototype takes nil and rejects anything else. The body sees what a push would have handed it (see MutatorFunc).
Permissions ¶
The workspace gate runs, then CanMutate is called ONCE with a Write{Custom} naming the mutator and its args — the rows the mutator body writes are not authorized individually. That is exactly what a custom mutation gets on the push path, and deliberately so: a mutator is server-authoritative logic, and the decision a policy makes is whether this caller may invoke this verb. Do not register a mutator as a way to launder writes a policy would refuse.
In a schema that uses the access model, the invocation is also checked against the mutator's MutatorAccess inside the write transaction, before the body runs, and refused when the mutator declares none.
Mark the ctx with Trusted for system triggers that have no caller.
It inherits Mutate's lack of idempotency: a trigger that may fire twice wants InvokeIdempotent.
func (*Server) InvokeIdempotent ¶
func (s *Server) InvokeIdempotent( ctx context.Context, workspaceID, key, mutatorName string, args proto.Message, ) (WriteOutcome, error)
InvokeIdempotent runs a registered mutator by name through MutateIdempotent, so a trigger that may fire twice — a redelivered webhook, a re-read change feed page — applies the mutator once. args follows Invoke's contract: the registered prototype's message type, or nil for its zero value (and nil only, for a mutator registered without a prototype).
Mutators have no result channel (they run on the client push path too, where nothing could receive one), so the recorded outcome carries only "applied, at this sequence". Callers that need a payload to replay should use MutateIdempotent directly.
func (*Server) Leases ¶
Leases returns the lease.Locker this server dedups per-workspace background work with — the one WithLeases installed, or the resolved default. Never nil. Background consumers built on the server (an effects runtime, an application worker reacting to this server's workspaces) should lease their per-workspace work here so every process sharing the store dedups in one space; the lease package documents role naming and what a lease does and does not guarantee.
func (*Server) Mutate ¶
Mutate runs fn inside a write transaction against the workspace and notifies connected clients if fn wrote anything.
Prefer Apply. Mutate holds the workspace's write lock for the whole of fn, so any work fn does serializes every other writer to that workspace — and an adapter may hold something wider than one workspace, as the shipped SQLite store does; and because fn's writes are only discovered as it runs, the permission hook has to run inside the transaction (see below). Apply has neither property. What Mutate offers that Apply does not is a genuinely serializable read-then-write and writes that stream rather than buffer, which is what bulk imports and scan-driven work need.
Permissions ¶
Each Put/Patch/Delete is authorized with CanMutate against the ctx principal, carrying the same CrudMutation a client push would have — so a policy cannot tell the two apart — and a write to an existing row then passes the row check (see RowWritePermissions). The workspace gate (CanAccessWorkspace) runs first, before the transaction opens. A ctx with no principal authorizes as anonymous, which a deny-by-default policy refuses.
Reads through the tx read as the caller's client would, as through EntityTx.AsCaller: a row the caller may not read reads as absent, each field a field guard hides from the caller reads as its zero value, and a Query whose predicate or order names such a field fails with code permission_denied. The first read, and the first after a write, calls ReadFilter once for each registered entity inside the transaction.
System work that has no caller to authorize — connectors, migrations, cron — marks its ctx with Trusted, which skips both hooks and reads every row unfiltered. See Trusted for why the bypass is opt-in.
This is the ONE place the engine consults a permission hook while holding a lock, and it is confined here because nothing else can know fn's writes in advance. The Permissions contract already requires CanMutate to be fast, free of blocking I/O and side-effect free, which is what keeps that survivable; a policy that does I/O should use Apply, where the hook runs between transactions.
Differences from a client push:
- No client_id/mutation_id: client watermarks are untouched and there is no idempotency — calling Mutate twice applies twice. Callers that retry (an HTTP handler, an at-least-once effects handler) want MutateIdempotent, which guards the same closure with a key.
- A mutator invoked through Invoke has its rows authorized by the verdict on the invocation, not per row — exactly as on push.
All writes through the tx share ONE workspace sequence, allocated lazily on the first Put/Delete — a call that only reads consumes no sequence, notifies nobody, and leaves a workspace that did not exist unregistered (see the storage.Adapter WithWriteTx contract), so probing an arbitrary workspace id is free of lasting effects.
fn may be invoked multiple times (the storage adapter may retry the transaction): reset any captured state at the top of fn and keep side effects out of it until Mutate returns nil. Returning an error (including Reject, which AsRejection recovers on the caller's side) rolls the transaction back and surfaces the error.
Do not call Mutate (or Invoke/CollectGarbage) from inside a mutator or another write closure: the nested transaction waits for the write lock the enclosing one already holds, so it deadlocks. When the re-entry threads the mutator's context such calls fail fast with an error instead.
func (*Server) MutateIdempotent ¶
func (s *Server) MutateIdempotent( ctx context.Context, workspaceID, key string, fn func(tx *EntityTx) ([]byte, error), ) (WriteOutcome, error)
MutateIdempotent is Mutate guarded by a caller-supplied idempotency key: the first call for a key runs fn and records what it did, and every later call with the same key skips fn entirely and returns that record. It is the write path for callers that retry — an HTTP handler behind a load balancer, an at-least-once effects handler reacting to the change feed (which re-sees a page after a crash by design), any integration with its own backoff.
The key's scope is the workspace, matching the partitioning of sequences, write exclusion and client watermarks, and the caller. Each principal has its own key space, so a key one principal claimed is a new key for another: that call runs fn under its own authorization, and never gets the first caller's Result. Trusted callers share one key space, apart from every principal's. Two trusted sources must not share keys by accident, so derive keys from something the caller owns — the feed cursor position being handled, the upstream event id — and prefix them per source when several sources write to one workspace.
The check and the write commit together. The ledger read, fn's writes and the record all happen in ONE transaction under the workspace's write exclusion, so there is no window in which a concurrent retry sees "not applied" while the first call is mid-write, and no way to record an outcome the store rolled back:
out, err := srv.MutateIdempotent(ctx, ws, r.Header.Get("Idempotency-Key"),
func(tx *server.EntityTx) ([]byte, error) {
if err := tx.Put(&issue); err != nil {
return nil, err
}
return json.Marshal(response{ID: issue.GetId()})
})
if err != nil { ... }
w.Write(out.Result) // the first attempt's response, however often it is retried
The bytes fn returns are opaque to the engine — marshal whatever the caller needs to reproduce its own answer, or return nil to record only "applied, at this sequence". They are bounded by the server's MaxValueBytes limit, since they are stored like any other value.
Failure is NOT recorded. An error from fn (including Reject) rolls the whole transaction back, key included, so the write stays retryable — a retry after a rejection is a fresh attempt, not a replay of the rejection. Only committed outcomes are replayable.
Two differences from Mutate worth knowing:
- A successful call always claims the key, even when fn wrote nothing, so the "nothing to do" outcome is replayable too. Claiming registers the workspace, so unlike Mutate this is not free to call against an arbitrary workspace id.
- Keys are garbage-collected on the retention configured by WithIdempotencyRetention (which needs WithGC to run at all). A retry that arrives after its key expired applies again — set the retention above the longest retry window your callers use.
Everything else matches Mutate: each write fn makes is authorized for the ctx principal (CanMutate, the schema's write rules and the row check) unless ctx is Trusted, reads apply the principal's read rules unless ctx is Trusted, all writes share one lazily allocated sequence, clients are notified on commit, and fn may run more than once if the adapter retries the transaction, so keep side effects out of it until the call returns. A replay runs no hook: the record is the outcome of a call the same principal made.
func (*Server) PendingWorkspaces ¶ added in v0.3.0
PendingWorkspaces yields every workspace where the named consumer has changes it has not acted on, in id order. It pages through ConsumerPendingWorkspaces and keeps its guarantees: a workspace whose position was behind when its page was read is always yielded, and a listed workspace may hold only changes the consumer filters out. Each page is its own snapshot, so a workspace written during the iteration may or may not be yielded.
An error ends the sequence: PendingWorkspaces yields it with an empty id and stops. Each page is one store query, run when the loop reaches it.
func (*Server) PresenceHandler ¶
PresenceHandler returns the mount path and HTTP handler for the presence service — the ephemeral plane, see engine/presence.
It shares the sync service's interceptor chain and request-size bound, and deliberately does NOT gzip its stream: room frames are small and latency-sensitive, and a gzip writer would cost a few hundred KB of deflate state for every watching client.
func (*Server) Publish ¶
func (s *Server) Publish( ctx context.Context, req *connect.Request[syncplanev1.PublishRequest], ) (*connect.Response[syncplanev1.PublishResponse], error)
Publish is the ephemeral plane's write side: state, broadcasts and departures, in one unary round trip.
It is unary because only RECEIVING a room needs a stream — and because the browser ConnectRPC subset has no client-streaming to make it anything else. A client that watches nothing may still publish, and a client whose stream is held by another tab publishes directly rather than through it.
Identity ¶
Every item is stamped with the caller's own principal. Nothing in the payload names the publisher, so presence cannot be used to impersonate. The session_id is self-asserted like a client id. When this node holds Watch streams for the session, the caller must have opened one of them.
Authorization ¶
Each item's topic passes the same gate a join does, so a room cannot be written to by someone who could not watch it. A topic this session is already watching on this node skips it: the gate ran when the topic was joined and the stream's heartbeat keeps re-running it, so charging a storage read to every cursor movement would buy nothing.
Items are independent. There is no atomicity across them and none is implied; a failure is reported for the request as a whole, and what was already handed to the bus stays handed over.
The response carries the announce interval, which is what a publisher holding no Watch stream needs: nothing re-announces its records, so they lapse three intervals after its last publish unless it re-publishes them itself.
func (*Server) Pull ¶
func (s *Server) Pull(ctx context.Context, req *connect.Request[syncplanev1.PullRequest]) (res *connect.Response[syncplanev1.PullResponse], err error)
func (*Server) Push ¶
func (s *Server) Push(ctx context.Context, req *connect.Request[syncplanev1.PushRequest]) (*connect.Response[syncplanev1.PushResponse], error)
Push applies one batch of mutations per workspace, each in its own write transaction. Within a batch a business rejection rolls back every row the rejected mutation wrote (and its sequence) while the rest of the batch — and the watermark bump for the rejected mutation — still commits.
Per-client watermark rules: mutation_id <= watermark is ALREADY_APPLIED, or REJECTED again if that id's verdict is still on record (which is what keeps a lost push response from turning a rejection into a silent drop); mutation_id == watermark+1 applies (or REJECTS — both bump the watermark, a rejection is an ack); a gap fails that workspace's batch so the client can resend it in order.
Batches are independent. There is no cross-workspace atomicity — the storage adapter serializes writes per workspace and nothing spans two partitions — so a failure scoped to one workspace is reported in its WorkspaceResults rather than as an RPC error. That is what keeps one revoked or wedged workspace from blocking every other workspace a client holds. RPC errors stay reserved for failures of the request itself: malformed, over limits, unauthenticated.
func (*Server) PutChunk ¶ added in v0.4.0
func (s *Server) PutChunk( ctx context.Context, req *connect.Request[syncplanev1.PutChunkRequest], ) (*connect.Response[syncplanev1.PutChunkResponse], error)
PutChunk stores one chunk of a blob whose upload BeginUpload started; see syncplanev1connect.BlobServiceHandler for the wire contract. The call that stores the last missing chunk commits the blob and pokes the workspace's subscribers. When no upload is staged, it reports a committed blob as complete only when the chunk matches it, and otherwise fails as for a digest the server does not have.
A ctx marked with Trusted skips the workspace gate.
func (*Server) Query ¶
func (s *Server) Query(ctx context.Context, req *connect.Request[syncplanev1.QueryRequest]) (res *connect.Response[syncplanev1.QueryResponse], err error)
Query runs a one-shot predicate query against current server state — the push-down path for data outside the synced subset. Read filters always apply. Results are value snapshots ordered by order_by (missing values last, ties broken by the next key and finally the row key ascending, in UTF-16 code-unit order — exactly the client evaluator's compareRows).
func (*Server) ReadState ¶ added in v0.6.0
func (s *Server) ReadState(ctx context.Context, workspaceID string, fn func(tx storage.ReadTx) error) error
ReadState runs fn in a read-only snapshot of the workspace's storage, for a link that keeps state beside the rows (see ReplicaTx.Tx). It is trusted: no permission hook runs and no read rule applies. fn runs at most once and must not start a write. An error fn returns is returned.
func (*Server) ReferencedBlobs ¶ added in v0.6.0
func (s *Server) ReferencedBlobs(ctx context.Context, workspaceID string, want []blob.Digest, entity func(name string) bool) (map[blob.Digest]bool, error)
ReferencedBlobs returns the digests of want that a live row of the workspace names in a syncplane.v1.BlobRef field: the rule blob GC keeps a blob by. A digest that no such row names is absent from the map.
The check applies no access rule and counts the rows of server-only entities. When entity is not nil, only the rows of the entities it accepts count. It runs in one read transaction; each entity costs one index probe per digest, or a read of every row of the entity when no index can serve the probe. It returns an error for an invalid workspace id.
func (*Server) RegisterDescriptorSet ¶
func (s *Server) RegisterDescriptorSet(set []byte, opts ...RegisterOption) ([]string, error)
RegisterDescriptorSet ingests a serialized google.protobuf.FileDescriptorSet — the wire form client/src/schema/builder.ts's defineSchema(...).toBinary() produces — and registers every message in it that carries (syncplane.v1.entity) options as a syncable entity, serving full CRUD through the same machinery as a compiled RegisterEntity. Messages without the option are skipped (mirroring the TS entitiesFromDescriptorSet). It is the Go counterpart of the client's "the server ships its schema" round-trip.
The set must be self-contained: the TS builder bundles google/protobuf/descriptor.proto and syncplane/v1/options.proto ahead of the synthesized entity files, so the whole schema resolves from these bytes with no codegen.
Each entity is checked as RegisterEntity checks it, so a reserved name or an option field this server does not know refuses the whole set.
The set replaces the descriptors the server serves, but EntityTx, ViewTx, ApplyTx and EntityKey still take a compiled message of the same full name: they convert it through its wire bytes, as a client's value arrives. A field the set does not declare is kept as an unknown field.
Re-registration is idempotent and additive (see registerDescriptorSet): an identical set is a no-op, appended fields/new entities upsert, and a conflicting change (a removed, renumbered or retyped field, or changed key_fields) is rejected without partially applying.
A change to the access model of an entity that is already registered — its access or grant options, or the enum values its grant role field matches — is rejected the same way unless opts include AllowAccessChange. So is a set that declares the first role of a schema that served callers without one, or removes the last role.
func (*Server) RegisterDynamicEntities ¶
func (s *Server) RegisterDynamicEntities(specs ...DynamicEntity) error
RegisterDynamicEntities builds several entities into one file (so intra-set references resolve) and registers each as a syncable entity, in order, as RegisterEntity without options does. It stops at the first entity that fails and keeps the ones registered before it. To declare the first role of a schema that serves callers, use RegisterDescriptorSet with AllowAccessChange.
func (*Server) RegisterDynamicEntity ¶
func (s *Server) RegisterDynamicEntity(spec DynamicEntity, opts ...RegisterOption) error
RegisterDynamicEntity builds spec into a dynamicpb message type and registers it as a syncable entity, serving full CRUD through the existing sync machinery. It is the runtime-schema counterpart of RegisterEntity, and takes the same opts. Use RegisterDynamicEntities when entities reference one another, so they share a single file and the references resolve.
func (*Server) RegisterEntity ¶
func (s *Server) RegisterEntity(msg proto.Message, opts ...RegisterOption) error
RegisterEntity registers a message type carrying syncplane.v1.entity options as a syncable entity. It returns an error for an entity whose name is already registered, whose name starts with the reserved prefix "syncplane_", or whose entity options or field behaviors carry a field this server does not know, such as a write policy that the access model replaced.
The access model is judged once the schema is complete, so RegisterEntity accepts an entity that leaves the model incomplete because it names an entity, or a permission whose role, no registered entity declares yet; until a later call completes it, every request fails with failed_precondition. It returns an error for an entity that breaks any other rule of the model, and the server keeps serving the schema it served before. An entity that declares the first role of a schema that served callers without one is refused unless opts include AllowAccessChange: it makes the workspace gate refuse every caller that holds no permission. The entities New registers, and those of a server that has none yet, need no flag.
func (*Server) Replicate ¶ added in v0.6.0
func (s *Server) Replicate(ctx context.Context, workspaceID string, fn func(tx *ReplicaTx) error) error
Replicate runs fn in a write transaction whose writes store rows exactly as given, for a link that keeps this server's workspace converged with another server. fn's writes are trusted and are not changed: no permission hook runs, no compare-and-swap applies, a collaborative-text field is replaced rather than unioned, and a field the caller may not write or a creator field keeps the value written. Every structure the server derives from rows is kept as after any other write: indexes, search, the text delta log, history, the access model, and the change feed with its notifications to clients.
All writes of one call take one workspace sequence, allocated on the first write; a call that writes nothing takes none and notifies nobody. Its rows are attributed to Actor{System: name} for a ctx marked with TrustedAs(ctx, name), and to Actor{System: "upstream"} otherwise. Replicate writes are never passed to the WriteCapture.
fn may run more than once (the storage adapter may retry the transaction), so keep side effects out of it until Replicate returns nil. An error fn returns rolls the transaction back and is returned. Do not call Replicate, or any other write call, from inside fn: it deadlocks.
func (*Server) ResetConsumer ¶
ResetConsumer drops a consumer's position and every shadow it holds in the workspace, so its next pass is a first run.
This is what a consumer does after falling below the tombstone horizon: the changes its shadows describe have been collected, so the shadows record a past that nothing arriving now can be compared against. Keeping them would report field changes against a state the row left long ago.
func (*Server) RestoreWorkspace ¶ added in v0.4.0
RestoreWorkspace lifts the refusal DeleteWorkspace put on the id. It restores no data: the next write starts a new, empty workspace under the id, with a new store epoch, so a client that still holds a cursor of the deleted workspace re-bootstraps instead of resuming. Restoring a workspace that is not deleted is not an error.
No write queued against the deleted workspace applies to the new one when its push names the cursor it was queued against (WorkspaceBatch.basis): the push fails with CodeWorkspaceReplaced, and the client drops the queue. A push without a basis is judged by its mutation ids alone. The watermarks went with the deleted workspace, so the server adopts the push's first id, and the queue applies to the new workspace, including writes the deleted one had already applied.
It runs no permission hook, and must not be called from inside a mutator or another write transaction, exactly as DeleteWorkspace.
func (*Server) SchemaRevision ¶
SchemaRevision returns the schema revision the server currently advertises to clients — the WithSchemaRevision token on the compiled path, or the hash derived from the last registered descriptor set on the runtime path. Empty when nothing has been advertised.
func (*Server) StatBlobs ¶ added in v0.4.0
func (s *Server) StatBlobs( ctx context.Context, req *connect.Request[syncplanev1.StatBlobsRequest], ) (*connect.Response[syncplanev1.StatBlobsResponse], error)
StatBlobs reports the state of blobs; see syncplanev1connect.BlobServiceHandler for the wire contract. A digest the caller cannot read reports BLOB_STATE_MISSING: the caller reads a blob when it reads a live row that names the digest in a syncplane.v1.BlobRef field, with the fields a guard hides from it cleared, as View would return the row.
It fails with invalid_argument for a malformed digest, and for a request that names more than 256 digests. A ctx marked with Trusted reads every blob a live row names.
func (*Server) Subscribe ¶
func (s *Server) Subscribe(ctx context.Context, req *connect.Request[syncplanev1.SubscribeRequest], stream *connect.ServerStream[syncplanev1.SubscribeResponse]) error
Subscribe is the payload-carrying change stream: "a Pull that never closes", multiplexed over a set of workspaces.
For each scope it catches the client up from that scope's cursor, marks the backlog drained with a caught_up frame, then pushes changed rows down the stream as the workspace changes — so an already-subscribed client applies them directly and skips a follow-up Pull RTT. Every frame names the workspace it concerns; only the heartbeat is stream-level.
Multiplexing is the point: a client in ten workspaces holds ONE stream, not ten. Browsers cap concurrent connections per host, and a long-lived stream is what spends that budget, so tying stream count to workspace count is what makes a multi-workspace client unworkable. Each scope still does its own scan against its own partition — there is no cross-workspace transaction and no shared sequence — so the multiplexing is purely a transport concern.
Failure is scoped too. A workspace whose cursor is unusable, whose access has been revoked, or whose scan fails is DROPPED from the stream with a typed reason; every other scope keeps streaming. Ending the whole stream because one partition had a bad day would take the other nine down with it.
Access is re-checked while the stream runs, not only at open: every heartbeat re-runs the workspace gate for each live scope, and a catch-up re-runs it before a page once a heartbeat interval has passed since the last run, so being removed from a project drops that scope within one heartbeat interval instead of whenever the client next reconnects. Authentication is NOT re-run — a credential that expires mid-stream still rides to the end of the stream (see authn.go).
Row visibility follows the filter epoch page by page, as it does for Pull. A scope reads FilterEpoch again before each page it sends, and when the epoch moved, or the scope opened with a cursor issued for another subscription set or epoch, it runs the same delta resync a Pull would (or drops the scope with RESET where Pull would reset).
Each stream is its own goroutine doing its own scans, so a slow client blocks only its own Send, never another client. With the default in-process notifier the live tail only reaches clients connected to THIS process; multi-node realtime needs a shared content-free WithNotifier (clients still converge via the per-tab pull/poll floor either way — the stream is latency, not correctness).
func (*Server) SubscribeActivity ¶
SubscribeActivity returns a channel of ids of workspaces that have committed a write — INCLUDING workspaces the caller has never heard of — and a cancel func; the channel closes after cancel. ok is false when the installed notifier cannot report it, which leaves a periodic sweep as the only way to notice work.
It is the wake-up a consumer that runs background work across many workspaces subscribes to. SubscribeChanges needs the workspace id up front, so covering a whole store through it means one subscription per workspace and no way to hear about a workspace created later; this carries every workspace over one subscription, and keeps carrying each of them — an id arrives every time its workspace is notified, not once.
Like every notifier signal it is best-effort and, with the default notifier, in-process: a consumer that misses one finds the work on its next sweep, later. Treat it as latency, not as an enumeration.
func (*Server) SubscribeChanges ¶
SubscribeChanges returns a channel that signals after writes commit in the workspace (the same wakeup the Subscribe streams ride on) and a cancel func; the channel closes after cancel. Signals are content-free, coalesced, and in-process only — they cut latency, they do not carry guarantees. Consumers drain via Changes on their own schedule regardless.
func (*Server) View ¶
View runs fn inside a read-only snapshot of the workspace: it takes no write lock, notifies nobody, and never consumes a sequence. It is the read half of the in-process API — what an app's own GET handlers and background jobs read through.
Permissions ¶
The workspace gate (CanAccessWorkspace) runs before the snapshot opens, and every row the closure reads is passed through the entity's ReadFilter — the same filter, resolved by the same machinery, that decides what a sync client may pull. A filtered-out row reads as absent: Get reports not-found, scans and queries skip it. Each field a field guard hides from the caller reads as its zero value in the rows the closure receives, and a query whose predicate or order names such a field fails with code permission_denied. Authorization is against the ctx principal, so a ctx with no principal reads as anonymous.
Both hooks are resolved BEFORE the snapshot opens, so neither can pin it. Because the closure may touch any entity, every registered entity's filter is resolved up front — see readGate for what that costs.
System reads with no caller to authorize — the admin UI on its private listener, a connector, a migration — mark the ctx with Trusted, which skips both hooks and returns every live row.
Unlike a write transaction the read closure runs AT MOST ONCE (storage adapters never retry a read tx), so fn may stream results out as it reads. Returning an error surfaces it; the snapshot is consistent for the call's duration.
func (*Server) Watch ¶
func (s *Server) Watch( ctx context.Context, req *connect.Request[syncplanev1.WatchRequest], stream *connect.ServerStream[syncplanev1.WatchResponse], ) error
Watch is the ephemeral plane's read side: a stream of one session's rooms.
For each topic it runs the join gate, sends the roster it knows, and then forwards participant updates, departures and broadcasts as they arrive — whichever node published them. The topic set is fixed for the life of the stream, which is what lets every gate resolve once at open instead of per frame; a client that navigates somewhere else closes the stream and reopens it, and pays a snapshot rather than a catch-up for doing so.
Failure is scoped to a topic. A room whose gate refuses, whose anchor row went away, or whose app hook failed is DROPPED with a typed reason while every other topic keeps streaming; an error is returned only when the STREAM cannot continue. That is the same split Subscribe makes, for the same reason.
Access is re-checked while the stream runs. Every heartbeat re-runs the gate for each live topic — including re-reading an anchored row, memoized across this node's streams so a document everyone has open costs one read per interval rather than one per watcher — so losing access to a document drops its room within one heartbeat instead of whenever the client reconnects. Authentication is NOT re-run; a credential that expires mid-stream rides to the end of the stream, exactly as on Subscribe.
Nothing here is durable. A frame the server could not hand over is gone, and the plane heals by re-announcement rather than by replay — see engine/presence for the contract.
func (*Server) WatchBlobs ¶ added in v0.4.0
func (s *Server) WatchBlobs( ctx context.Context, req *connect.Request[syncplanev1.WatchBlobsRequest], stream *connect.ServerStream[syncplanev1.WatchBlobsResponse], ) error
WatchBlobs streams the state of blobs; see syncplanev1connect.BlobServiceHandler for the wire contract. Every message reports what StatBlobs would report at that moment, by the same read rule.
It checks again each time the workspace is notified, which a commit and a completed upload both do, and sends an empty message at the heartbeat interval (WithHeartbeat). At each heartbeat it runs the workspace gate again, and ends the stream with the gate's error when the caller is no longer admitted. It holds no transaction between checks. A ctx marked with Trusted skips the gate.
func (*Server) WorkspaceIDs ¶
WorkspaceIDs lists the workspaces that hold persisted state, delegating to the storage adapter. Used by background consumers (connectors, outbox drainers) to discover work. A workspace only ever named by reads — a pull or a query against an id nobody has written — is not in the list. The list may be boundedly stale (an adapter may answer it from a read replica): a just-written workspace appears on a later call, so poll rather than assume one call is exhaustive.
It leaves out the workspaces whose id starts with ReservedWorkspacePrefix.
type ViewTx ¶
type ViewTx struct {
// contains filtered or unexported fields
}
ViewTx is the read-only entity facade View runs against. Entity identity comes from the message type passed in, exactly like EntityTx; it surfaces the stored row version so an editor can round-trip it for compare-and-swap.
func (*ViewTx) Get ¶
Get loads the row with the given key into dst and reports whether a live row was found and the sequence (version) it was last written at. A missing or deleted row returns (false, 0, nil).
func (*ViewTx) GetMeta ¶
GetMeta is Get, reporting the row's whole RowMeta instead of its version alone — the read that answers "who last wrote this". A missing or deleted row returns (false, RowMeta{}, nil).
func (*ViewTx) Query ¶
func (v *ViewTx) Query(prototype proto.Message, spec query.Spec, fn func(msg proto.Message, version uint64) error) error
Query iterates the live rows of the entity identified by prototype that match spec, in spec's order, decoding each into a fresh message and passing it with its version — so a result can be handed straight back to a compare-and-swap write. It is the "find everything matching X" read that list and search endpoints are built from.
The predicate is the engine's own, compiled by the query package, so it means here exactly what it means to a sync client and to the Query RPC. Build it with the constructors rather than by hand:
tx.Query(&todov1.Todo{}, query.Spec{
Where: query.And(query.Eq("done", false), query.Contains("title", "milk")),
OrderBy: []*syncplanev1.OrderKey{query.Desc("created_at_ms")},
Limit: 20,
}, func(msg proto.Message, version uint64) error { … })
The caller's read filter applies (a Trusted view sees every live row), so the page counts only rows this caller may see. A spec whose predicate or order names a field that a field guard hides from the caller on some row, on this entity or on an entity a rel condition reaches, fails with code permission_denied: which rows match, and their order, would tell the caller about values it does not read. No engine limit caps the result, though, so unlike the RPC a spec with no Limit returns — and holds in memory — every match.
Page with Spec.After/Before rather than Offset: a cursor names a position in the ordering, so the page is unaffected by rows inserted ahead of it and an index-served ordered query seeks straight to it. A cursor from a different entity or ordering fails with query.ErrCursorShape.
A declared secondary index serves the query when one covers its predicate and ordering, making it O(matches). With none — or while an index is still building — every live row of the entity is read and decoded, so the query is O(entity) however selective the predicate is. Fine for a background job; think twice in a hot handler over a large entity.
fn runs inside the read snapshot, so it must not start another transaction. An error from fn stops the iteration and surfaces.
func (*ViewTx) ScanPage ¶
func (v *ViewTx) ScanPage(prototype proto.Message, afterKey string, limit int, fn func(msg proto.Message, version uint64) error) (lastKey string, more bool, err error)
ScanPage iterates up to limit live rows of the entity identified by prototype with key > afterKey, in key order, decoding each into a fresh message and passing it with its version. It returns the key of the last row visited and whether more rows follow; pass lastKey back as afterKey to continue. limit must be positive.
type WorkspaceDenial ¶
type WorkspaceDenial struct {
// Message explains the denial. It reaches the client, so keep it free of
// detail the caller has not earned — "not a member of this workspace" is
// better than naming who is.
Message string
// contains filtered or unexported fields
}
WorkspaceDenial is a PERMANENT "no" from CanAccessWorkspace: this caller may not access this workspace, and retrying will not change that. It becomes an RPC error with Connect code permission_denied carrying CodeWorkspaceAccessRevoked, so a client can tell "I was removed from this project" from "the membership service is having a bad day" and act on it — stop syncing the workspace instead of backing off forever.
It is deliberately distinct from Rejection: a Rejection is an ack for one mutation (the client drops it and moves on), while this denies the entire request, including reads.
func AsWorkspaceDenial ¶
func AsWorkspaceDenial(err error) (*WorkspaceDenial, bool)
AsWorkspaceDenial extracts a WorkspaceDenial from an error chain.
func (*WorkspaceDenial) Error ¶
func (d *WorkspaceDenial) Error() string
func (*WorkspaceDenial) Unwrap ¶ added in v0.4.0
func (d *WorkspaceDenial) Unwrap() error
Unwrap returns the error the engine denied the workspace for, such as ErrWorkspaceDeleted. It is nil for a denial DenyWorkspace built.
type Write ¶
type Write struct {
// ClientId is the client-asserted origin of the envelope this Write came
// from. It is an idempotency handle, NOT an identity: it is whatever the
// client sent, unverified. Authorize against the Principal CanMutate is
// handed instead; never derive authorization from ClientId.
ClientId string
// MutationId is the envelope's per-client id. Writes flattened from one
// batch share it.
MutationId uint64
// Crud is set for a CRUD write, including each sub-mutation of a batch.
Crud *syncplanev1.CrudMutation
// Custom is set for a custom-mutator invocation. A policy may authorize on
// its Name/Args but not on the individual rows it writes — those happen
// inside the registered mutator, after this hook.
Custom *syncplanev1.CustomMutation
}
Write is a single authorizable unit handed to Permissions.CanMutate. The engine flattens every mutation envelope into Writes before authorizing, so a policy always sees exactly one write and can never forget to unwrap a batch:
- a CRUD mutation → one Write with Crud set
- a custom mutation → one Write with Custom set
- a batch → one Write per sub-mutation, each with Crud set, all sharing the envelope's ClientId/MutationId
Exactly one of Crud or Custom is non-nil. Rejecting any Write flattened from a batch rejects (and rolls back) the entire batch.
type WriteCapture ¶ added in v0.6.0
type WriteCapture func(ctx context.Context, w *CapturedWrite) error
WriteCapture observes every mutation the server applies, inside the write transaction, after the mutation's writes and before it commits. It is how a replication link records local writes atomically with the rows they wrote.
It is called once for each mutation a client push applies, and once for each Apply, ApplyIdempotent, Mutate, MutateIdempotent, Invoke and InvokeIdempotent call that writes a row or invokes a mutator. It is not called for a mutation that is rejected or fails before it, for a replayed idempotent call, or for writes made through Replicate.
A Rejection it returns (see Reject) rejects the mutation: nothing the mutation wrote commits, a push reports the mutation REJECTED with the Rejection's code, and every other entry point returns the error. Any other error fails the write as a storage error does: a push fails the workspace's batch with CodeInternal.
It runs while the workspace's write lock is held, and it can run more than once for one mutation when the transaction is run again. Only what it writes through CapturedWrite.Tx is kept from a run that does not commit, so any other effect must tolerate a repeat. ctx is the context of the call that wrote; a write call made with it fails rather than deadlocks.
type WriteOption ¶
type WriteOption func(*writeOpts)
WriteOption customizes EntityTx.Put and EntityTx.Patch.
func WithExpectedVersion ¶
func WithExpectedVersion(version uint64) WriteOption
WithExpectedVersion makes a Put a compare-and-swap: the stored row's version must equal version or the write is rejected as a conflict (CodeConflict, an *Rejection AsRejection recovers). An absent or deleted row reads as version 0, so WithExpectedVersion(0) means "only if the row does not exist".
Beyond conflict detection it is how a write states its intent to an entity whose access rules admit creates and updates apart: version 0 is provably a create and a non-zero version provably an update, so a write the rules do not admit as that operation is refused before the write transaction opens. An unguarded PUT is a create or an update depending on the stored row.
Ignored by Patch, which takes its expected version as an argument.
func WithTextPeer ¶
func WithTextPeer(peer string) WriteOption
WithTextPeer names the text writer identity WithTextString operations are minted under. Two writers that can run concurrently must never share a peer; a stable per-writer name like the connector's `connector:<writerID>` convention is the model. Reuse across calls is safe when every write of the peer to a row goes through a server that stores that row: Put/Patch read the stored row inside the serialized write transaction (see ApplyTextStrings) and mint past the ids it holds. A server that holds only part of another server's rows (a replica synced with subscriptions) does not see the ids the peer minted in a row it does not hold, so it can mint them again.
func WithTextString ¶
func WithTextString(field, value string) WriteOption
WithTextString sets a collaborative-text field from a plain string instead of encoded document bytes: the string is diffed against the stored document under the WithTextPeer identity, so the write merges with concurrent edits instead of replacing them. field is the dotted proto path — for a document inside a keyed list or map element, the instance path with the element key ("notes.<key>.body"), and the written message must carry that element. Repeat the option for multiple fields. An empty string deletes all visible text. On Patch the field is added to the mask automatically.
Requires WithTextPeer in the same call — the engine never invents a writer identity, because peer uniqueness is the caller's contract (see text.ID).
type WriteOutcome ¶
type WriteOutcome struct {
// Applied is true when this call ran the closure and committed it, false
// when it replayed a record an earlier call left behind.
Applied bool
// Seq is the workspace sequence the write took, or 0 if it wrote nothing.
Seq uint64
// Result is the payload the closure recorded (nil if none). Replayed
// verbatim on every retry of the key.
Result []byte
}
WriteOutcome reports what an idempotent trusted write did.
The distinction that matters is Applied: false means the key had already been claimed, the closure did NOT run, and Seq/Result are the ORIGINAL write's — which is what lets a retried API request answer with the first attempt's response instead of an opaque "already applied".
Source Files
¶
- access.go
- accesschain.go
- accessmoves.go
- accessresolve.go
- accesssync.go
- accesswrite.go
- actor.go
- admin.go
- apply.go
- authn.go
- authorizer.go
- blobgc.go
- blobref.go
- blobservice.go
- blobwatch.go
- bootstrap.go
- bootstrapresume.go
- candidates.go
- canonical.go
- capture.go
- closure.go
- codes.go
- compact.go
- compress.go
- consumers.go
- dynamic.go
- emit.go
- errors.go
- facet.go
- failuretx.go
- feed.go
- fieldpolicy.go
- fieldread.go
- gc.go
- group.go
- history.go
- idempotent.go
- index.go
- indexbuild.go
- late.go
- lease.go
- logging.go
- manager.go
- mutate.go
- mutator.go
- permissions.go
- poison.go
- principal.go
- pull.go
- push.go
- query.go
- readroute.go
- reentrancy.go
- register.go
- relquery.go
- replicate.go
- resync.go
- roomgate.go
- rooms.go
- rooms_publish.go
- server.go
- subhash.go
- subscribe.go
- telemetry.go
- textcache.go
- textdelta.go
- textfloor.go
- textwrite.go
- trusted.go
- typed.go
- view.go
- watermark.go
- window.go
- workspaceaccess.go
- workspacedelete.go
- writegate.go