lww

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Oct 29, 2026 License: MIT Imports: 8 Imported by: 0

Documentation

Overview

Package lww merges PATCH mutations into row snapshots using field masks.

Because the server linearizes mutations per workspace, applying masks in sequence order IS per-field last-writer-wins — no per-field timestamps exist anywhere. Fields marked opaque (syncplane.v1.field_behavior) are always replaced whole, never descended into; this is the escape hatch for embedding CRDT blobs later.

A oneof is ONE field here, named in a mask by the group rather than by a member, and replaced whole (no sub-paths, even into a message member). The group has to be the unit: protobuf lets only one member hold a value, so a member-granular mask can say "a is set" but cannot say what "a is unset" means for its siblings, and the two answers ("b survives" / "the group is empty") are both defensible. Naming the group asks the question the data can answer. The cost is that a message inside a oneof merges atomically, which is also why nothing below a oneof may be keyed or text (registration refuses those — see engine/server). A reference may be a oneof member: a stored stub is replaced whole anyway, and a oneof of references is how a POLYMORPHIC reference — one row pointing at one of several entities — is declared (see RefsOf).

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CheckReferenceMessage

func CheckReferenceMessage(md protoreflect.MessageDescriptor) error

CheckReferenceMessage validates the shape of a message declaring (syncplane.v1.reference): not itself an entity; its target named by exactly one singular entity-typed field, or by a oneof whose members are all singular entity-typed fields; at most one singular string field marked (syncplane.v1.field_behavior).workspace, outside any oneof; and no other fields. A message that declares nothing passes unless one of its fields is marked workspace, which only a reference message may carry.

func DecodeMapKey

DecodeMapKey decodes an ESCAPED mask segment into a typed map key per the field's key kind. Exported for the query package, which addresses a map entry by key and must parse the non-string kinds exactly as the merge does — two spellings of the same int64 key would otherwise reach two different entries.

func DuplicateItemKey added in v0.3.0

func DuplicateItemKey(msg protoreflect.Message) (string, bool)

DuplicateItemKey finds a keyed message list in msg that holds one key on more than one element. It returns the instance path of the second such element, in mask form ("members.u1"), and true; or "" and false when every keyed list holds each key once.

Merge addresses an element by its key, so a key held twice cannot be merged: a mask that removes the key leaves a copy behind. Only lists a mask path can reach are checked. The walk does not enter an opaque or text field, a reference message, a oneof member, or an element of a message list without key fields, because Merge replaces each of these whole. A list of references is not checked: it may name one row twice.

func EncodeItemKey

func EncodeItemKey(msg protoreflect.Message, keyFields []protoreflect.FieldDescriptor) string

EncodeItemKey renders a keyed-list element's identity as the mask segment a path addressing it carries. Exported for instance-path construction (see Merger.FnAt): a consumer enumerating a row's elements must render each key exactly as the merge decodes it, or the two would address different elements.

func EncodeMapKeySegment

func EncodeMapKeySegment(fd protoreflect.FieldDescriptor, mk protoreflect.MapKey) string

EncodeMapKeySegment renders a map key as the mask segment a path addressing its entry carries — the inverse of DecodeMapKey. Exported for instance-path construction, like EncodeItemKey.

func EqualField

EqualField reports whether one field holds the same value in two messages of the same type. Comparison follows proto.Equal for every field shape: scalar, message, repeated and map, with an absent field never equal to a present one.

func EqualUnit

func EqualUnit(a, b protoreflect.Message, seg string) bool

EqualUnit reports whether the mask unit named by seg holds the same value in both messages. A unit is what ONE top-level mask segment may name — a field, or a oneof group (see mergePath) — so a caller narrowing a mask to the parts that moved splits at the same granularity the merge applies at.

An unrecognized name reports false — a mask naming it could not be applied either, and "it differs" is the conservative answer for a caller deciding whether to act on the unit.

func HoldsKeyedList added in v0.3.0

func HoldsKeyedList(md protoreflect.MessageDescriptor) bool

HoldsKeyedList reports whether a message of type md can hold a keyed list that DuplicateItemKey checks. When it reports false, DuplicateItemKey never finds a duplicate in such a message.

func IsRef

IsRef reports whether fd is a first-class typed reference (see RefsOf), to one entity or to one of several.

func IsRefMessageField

func IsRefMessageField(fd protoreflect.FieldDescriptor) bool

IsRefMessageField reports whether fd is a reference whose stored shape is a reference message — the shape whose workspace and key are one merge unit: a singular field is replaced whole on every write, a repeated one merges per element with the whole element as the identity (see Ref.ItemKey).

func IsReferenceMessage

func IsReferenceMessage(md protoreflect.MessageDescriptor) bool

IsReferenceMessage reports whether md declares (syncplane.v1.reference), well-formed or not.

func IsText

IsText reports whether a field carries (syncplane.v1.field_behavior).text — a bytes field holding an encoded engine/text document.

func KeyFieldsFor

KeyFieldsFor exposes keyFieldsFor: the identity fields of a keyed message list, or nil when the list has none (and so merges whole).

func Merge

func Merge(dst, src proto.Message, paths []string) error

Merge copies the fields named by mask paths from src onto dst. Both must be the same message type. Paths use FieldMask semantics ("settings.color"), plus this package's extensions: keyed collection items ("tags.red") and oneof groups ("choice", never "choice_text"). A path that names a missing field is an error (the client sent a mask for a schema the server does not know).

func MergeWithMergers

func MergeWithMergers(dst, src proto.Message, paths []string, m Mergers) error

MergeWithMergers is Merge with per-field hooks: when a mask path lands on (or descends into) an opaque field that has a registered merger AND both sides carry a value, the merger combines them instead of replacing. One-sided cases keep plain LWW semantics: src-only replaces, dst-only is cleared by the zero-valued src — unless the merger sets MergeAbsentBase, in which case an src-only value still runs through it against an empty base. A dst-only value is always a clear: the mask says the writer means the field to be empty, and no merger can undo that.

func OneofOf

OneofOf returns the oneof a field is a member of, or nil. Synthetic oneofs are not oneofs for any purpose here: proto3 `optional` compiles to one, and such a field is an ordinary field with explicit presence. Every check that asks "is this a oneof member" must go through this, or it silently reclassifies every optional field in the schema.

func RefItemKey

RefItemKey renders one stored value of a repeated reference message field as the mask segment that addresses it (see Ref.ItemKey), whichever case the value holds. A value of a polymorphic reference message that holds no case renders its workspace, an empty case and no key. Panics when fd is not a reference message field.

func RefKeyFields

RefKeyFields returns the key fields of the entity a reference field targets (see RefOf), or nil when fd is not a reference to one entity. The fields are the TARGET's: on a reference message they sit under Ref.Value, not on the stored value itself — address them through Ref.KeyPath.

func ReplacedWhole added in v0.3.0

func ReplacedWhole(fd protoreflect.FieldDescriptor) bool

ReplacedWhole reports whether Merge replaces fd whole even when a mask path names a sub-path into it. That is true for an opaque or text field, and for a singular reference message, whose workspace and key never split across a masked write. A repeated reference message merges per element instead, with the whole element as the identity.

func SplitPath

func SplitPath(path string) []string

SplitPath splits a mask path into the segments mergePath would walk. Segments keep their escape sequences intact, exactly as the merge sees them: a field name never carries one, and an item key is decoded by whoever consumes it. A path that ends in the separator gives no empty last segment, though the merge reads it as the empty key of a collection: "attrs." splits as "attrs", which names more of the row than the merge writes, never less.

Exported for callers that need to reason about where a mask POINTS without applying it — index maintenance skips a row rewrite when no mask path can reach an index component (server.entityInfo.maskTouchesIndexes), and that comparison is only sound if it segments a path the same way the merge does.

func UnescapeSegment

func UnescapeSegment(s string) string

UnescapeSegment reverses the escaping SplitPath leaves intact: a backslash before any byte protects it, so `a\.b` is one segment holding "a.b".

Exported for the query builders, which take a whole dotted path as one string and therefore have to undo the escaping the wire form does not need — a wire path is already a list of segments (query.Path).

Types

type MergeFunc

type MergeFunc func(base, incoming []byte) ([]byte, error)

MergeFunc combines the stored serialization of an opaque field with an incoming one (CRDT-style). Both slices are the field's raw value: the bytes content for bytes fields, the marshaled message for message fields.

type Merger

type Merger struct {
	Fn MergeFunc
	// FnAt, when non-nil, is called instead of Fn and additionally receives the
	// instance path of the value being merged: the mask form of the position,
	// with the item keys the descent crossed ("items.<key>.body"), whereas the
	// Mergers map is keyed by the schema path with keys stripped ("items.body").
	// One registered merger therefore serves every element of a keyed list or
	// map, and FnAt is how it can keep per-element state.
	FnAt func(instancePath string, base, incoming []byte) ([]byte, error)
	// MergeAbsentBase runs Fn even when the stored row does not carry the
	// field, passing an empty base. Only safe for a merger whose empty state is
	// a real value rather than "no value" — the convergent-text merger, where
	// an empty document is the identity of the union, and where the incoming
	// side may be a delta-state fragment that has to be decoded rather than
	// stored raw. App-registered mergers keep the both-sides gate, so a
	// one-sided PATCH there stays plain LWW replace.
	MergeAbsentBase bool
}

Merger is one field's merge hook plus the gate it runs under.

type Mergers

type Mergers map[string]Merger

Mergers maps dotted opaque-field paths (e.g. "doc", "outer.doc") to merge hooks. A nil map replaces opaque fields whole (the default).

type Ref

type Ref struct {
	// Field is the reference field itself, singular or repeated.
	Field protoreflect.FieldDescriptor
	// 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 that holds the
	// target stub; nil for an entity-typed reference.
	Value protoreflect.FieldDescriptor
	// Workspace is the reference message's workspace field, or nil when every
	// stored value resolves in the holder's own workspace.
	Workspace protoreflect.FieldDescriptor
	// Group is the holder's oneof Field is a member of, or nil.
	Group protoreflect.OneofDescriptor
}

Ref describes one typed reference to ONE entity: the entity it points at, and where inside the stored value the target's key and workspace sit.

Two stored shapes make a reference. An ENTITY-TYPED field — a singular or repeated message field whose (element) message carries (syncplane.v1.entity) — stores a stub of the target itself, projected down to its key fields; Value is nil and the stub is the field value. A REFERENCE MESSAGE field — one whose (element) message carries (syncplane.v1.reference) — stores a wrapper holding the entity stub in Value and, when the message declares one, the target's workspace in Workspace. Consumers address the key through KeyPath and the stub through Stub, so the two shapes differ in nothing else.

A POLYMORPHIC reference — one stored value that points at one of several entities — is a oneof of references, and each member is its own Ref, a CASE of it. The oneof sits either on the holder (Group is set, and Field is the member) or inside a reference message (Value is a member of the message's oneof, and Field is the message field every case shares). A case holds a value only while it is the active one, which every accessor here already reports: Field is absent, or Stub finds nothing.

func RefOf

func RefOf(fd protoreflect.FieldDescriptor) *Ref

RefOf classifies fd as a typed reference to one entity, or returns nil when it is not one: a non-message field, a map, a message that is neither an entity nor a well-formed reference message, or a reference message whose target is a oneof of entities — a polymorphic reference has no single target, and RefsOf reports its cases. A reference message that breaks its rules (see CheckReferenceMessage) is not a reference either — registration reports it, and everything else sees an ordinary sub-message.

func RefsOf

func RefsOf(fd protoreflect.FieldDescriptor) []*Ref

RefsOf classifies fd as a typed reference and reports every case it can hold: nil when fd is not a reference, one Ref for a reference to one entity, and one per entity-typed member of the oneof for a reference message whose target is a oneof. A member of a oneof on the holder is classified on its own, with Group set; the other members of that oneof are its sibling cases.

func (*Ref) Addressable

func (r *Ref) Addressable(name string) bool

Addressable reports whether a path may continue from the reference field into the field named: a key field of an entity-typed stub, or the value and workspace fields of a reference message — the key fields then sit under Value, which is itself an entity-typed reference.

func (*Ref) AddressableNames

func (r *Ref) AddressableNames() []string

AddressableNames lists the fields Addressable admits, for error messages.

func (*Ref) CaseJSONName

func (r *Ref) CaseJSONName() string

CaseJSONName is CaseName in the accessor form a client spells it in.

func (*Ref) CaseName

func (r *Ref) CaseName() string

CaseName is the proto name of the field that decides this case — Field for a member of the holder's oneof, Value for a member of a reference message's oneof — or "" for a reference to one entity.

func (*Ref) InnerCase

func (r *Ref) InnerCase() bool

InnerCase reports whether the case is decided inside the stored value — the reference message's oneof — rather than by which holder field is set. Such cases share Field, and are told apart by Value.

func (*Ref) ItemKey

func (r *Ref) ItemKey(value protoreflect.Message) string

ItemKey renders one stored value of a repeated reference message as the mask segment that addresses it, so a PATCH can add or remove an element on its own: the element's workspace and its key, escaped and joined the way a composite keyed-list identity is (see EncodeItemKey). The workspace part is always present, empty when the value names none, so a value with an empty workspace and one naming the holder's own are two elements even though they resolve to the same row. A reference without a workspace field renders the key alone, exactly as an element of a repeated entity-typed reference.

A case of a polymorphic reference message puts its name between the workspace and the key, so two cases naming the same key are two elements; the workspace part is present whenever the message declares one, and the case part whenever the message's target is a oneof.

Callers render every element through this, and the merge decodes with it; a segment produced any other way addresses no element. An element of a polymorphic reference message is rendered by RefItemKey, which picks the case the value holds.

func (*Ref) KeyPath

KeyPath returns the field steps from a stored reference value to one key field of the target: [kf] for an entity-typed reference, [Value, kf] for a reference message.

func (*Ref) KeyPathNames

func (r *Ref) KeyPathNames(kf protoreflect.FieldDescriptor) []string

KeyPathNames is KeyPath as proto field names — the segments a query or index path spells the key in.

func (*Ref) Polymorphic

func (r *Ref) Polymorphic() bool

Polymorphic reports whether this reference is one case of several: its Field is a member of a oneof on the holder, or its Value a member of the oneof inside a reference message.

func (*Ref) Qualified

func (r *Ref) Qualified() bool

Qualified reports whether stored values may name a workspace other than the holder's: the reference message declares a workspace field.

func (*Ref) ResolvesIn

func (r *Ref) ResolvesIn(value protoreflect.Message, workspace string) bool

ResolvesIn reports whether a stored reference value points into workspace, the holder's own: it names that workspace, or names none.

func (*Ref) Stub

func (r *Ref) Stub(value protoreflect.Message) (protoreflect.Message, bool)

Stub returns the target stub inside one stored reference value: the value itself for an entity-typed reference, the embedded entity message for a reference message. Reports false for a reference message that holds no stub, which points at nothing.

func (*Ref) WorkspaceOf

func (r *Ref) WorkspaceOf(value protoreflect.Message) string

WorkspaceOf returns the workspace one stored reference value names, or "" when the reference has no workspace field or the value leaves it empty — both mean the holder's own workspace.

Jump to

Keyboard shortcuts

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