encoding

package
v1.54.0 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: MIT Imports: 17 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package encoding implements the V1 wire format yrs and JS Yjs use for state vectors, delete sets, and document updates.

Per docs/yrs-port-notes/update-v1.md the V1 wire format has three load-bearing pieces:

  • StateVector: varuint count followed by (clientID, clock) pairs.
  • IdSet (the wire DeleteSet): per-client (id, range count, ranges of (start, length)) — half-open ranges, written as length not end.
  • Update: per-client block runs followed by an embedded IdSet.

This package owns StateVector and IdSet end-to-end. Update encode and decode arrive in subsequent commits; they will compose StateVector and IdSet here.

All primitive byte operations route through internal/lib0, which is already verified byte-equivalent with JS lib0 across 40 fixtures.

Determinism: encoding sorts clients ascending by clientID before emission. yrs's StateVector and IdSet iterate HashMap / BTreeMap (BTreeMap = ascending; HashMap = arbitrary). JS Yjs iterates JS Map in insertion order. To produce reproducible bytes that round-trip across runs and runtimes we always sort here. Decoders accept any order — the wire is unambiguous.

Index

Constants

View Source
const (
	AnyTagBinary    uint8 = 116
	AnyTagArray     uint8 = 117
	AnyTagObject    uint8 = 118
	AnyTagString    uint8 = 119
	AnyTagTrue      uint8 = 120
	AnyTagFalse     uint8 = 121
	AnyTagBigInt    uint8 = 122
	AnyTagFloat64   uint8 = 123
	AnyTagFloat32   uint8 = 124
	AnyTagInteger   uint8 = 125
	AnyTagNull      uint8 = 126
	AnyTagUndefined uint8 = 127
)

lib0 Any TLV type tags. Tag bytes are written as a single uint8 followed by the variant-specific payload. Constants reproduced verbatim from lib0/encoding.js writeAny (and confirmed against docs/yrs-port-notes/update-v1.md content table).

View Source
const MaxClock = uint64(1)<<53 - 1

MaxClock is the largest clock this decoder accepts from the wire.

It is Number.MAX_SAFE_INTEGER, because the reference implementation keeps clocks in JavaScript numbers and cannot represent anything above it: a yjs peer handed a larger value throws "Integer out of Range" (measured against yjs 13.6.32). Accepting what the reference refuses buys nothing and lets a sender push a client's clock space somewhere no honest peer can follow.

This is a fidelity bound, not a safety guarantee. A clock range BELOW it is still enough for a room member to silence another client or tombstone their content - yjs behaves identically, measured both ways - because the Yjs update format does not authenticate deletes. See the package documentation on what that means for untrusted transports.

View Source
const V2StructFloor = 1 << 20

V2StructFloor is the number of structs a V2 update may hold whatever its length. V2 run-length encodes the info, client, clock, length and type columns, so structs without bytes of their own (GC, deleted content, empty nested types) cost almost nothing and a valid update holds more structs than bytes: yjs writes a million deleted characters prepended one at a time in 42 bytes. Decoding a struct costs about 900 bytes, so an update may hold max(its length, V2StructFloor) structs: a million is what the largest V1 message ygo's server takes (4 MiB, two bytes or more a struct) already decodes to, and past it a V2 update needs a byte a struct, as V1 does. A wire-supplied count with no bound drove an unbounded decode: a fuzzer OOM-killed the process from 69 bytes.

Variables

View Source
var ErrAnyTooDeep = fmt.Errorf("encoding: Any value nested deeper than %d levels", anyval.MaxNesting)

ErrAnyTooDeep is returned for an Any value whose arrays and objects nest deeper than anyval.MaxNesting (10000) levels: the bound encoding/json applies to JSON text, and past what a yjs peer reads (lib0 readAny overflows the JavaScript stack after about 4,700 levels in Node 26). Without it, an update of a few megabytes nesting arrays several hundred thousand levels deep overflowed the goroutine stack, a crash no caller can recover from.

View Source
var ErrUnknownTypeRef = errors.New("encoding: unknown shared type ref")

ErrUnknownTypeRef is returned for a shared type ref past the seven yjs reads (array, map, text, XML element, fragment, hook and text): yjs's readContentType throws there.

View Source
var ErrUnsupportedAnyTag = errors.New("encoding: unsupported Any tag")

ErrUnsupportedAnyTag is returned when DecodeAny encounters a type tag that cannot be mapped to a Go value.

View Source
var ErrUpdateTooDense = errors.New("encoding: V2 update expands past max(its length, 1048576) structs or cached-key bytes")

ErrUpdateTooDense is returned for a V2 update that expands past what its length pays for: more structs than max(its length, V2StructFloor), or a cached key read again for more bytes than that (yjs's encoder does not write cached keys; its decoder reads them). The structs are counted before they are decoded, client by client.

Functions

func ApplyStoredUpdate added in v1.26.0

func ApplyStoredUpdate(d *doc.Doc, raw []byte) error

ApplyStoredUpdate is ApplyUpdate for bytes ygo itself stored, decoded with DecodeStoredUpdate.

func ApplyUpdate

func ApplyUpdate(d *doc.Doc, raw []byte) error

ApplyUpdate is the top-level convenience entry point. It opens a write transaction on d, decodes raw, integrates the result, and returns. Equivalent to:

upd, _, err := DecodeUpdate(raw)
if err != nil { return err }
txn := d.WriteTxn()
txn.Local = false
defer txn.Commit()
return upd.Apply(txn)

Returns the decode error verbatim when raw is malformed. The pending buffer absorbs any missing-dependency items silently; inspect with GetPending afterwards if the caller cares.

func ApplyUpdateV2

func ApplyUpdateV2(d *doc.Doc, raw []byte) error

ApplyUpdateV2 is the top-level convenience entry point for V2 wire bytes. Opens a write transaction on d, decodes raw, applies, returns. Pending-buffer semantics identical to ApplyUpdate (V1): items missing causal dependencies queue silently and drain on subsequent ApplyUpdate / ApplyUpdateV2 calls.

V1 and V2 wire formats are NOT interchangeable. Calling ApplyUpdateV2 on V1 bytes (or vice versa) is undefined behaviour.

func ApplyUpdateV2WithOrigin added in v1.22.0

func ApplyUpdateV2WithOrigin(d *doc.Doc, raw []byte, origin any) error

ApplyUpdateV2WithOrigin is ApplyUpdateV2 with origin as the transaction's Origin.

func ApplyUpdateWithOrigin added in v1.22.0

func ApplyUpdateWithOrigin(d *doc.Doc, raw []byte, origin any) error

ApplyUpdateWithOrigin is ApplyUpdate with origin as the transaction's Origin, which observers, update handlers and UndoManager origin filters see (yjs applyUpdate's transactionOrigin).

func ConvertUpdateBytes added in v1.53.0

func ConvertUpdateBytes(update []byte, fromV2, toV2 bool, floor int) ([]byte, error)

ConvertUpdateBytes is yjs convertUpdateFormat with the identity transformer: every struct of update in wire order, Skips and empty structs included, written in the other format (a section wherever the client changes), then the delete set as read (clients descending). Bytes after the delete set are ignored. A V2 output holding more structs than its length pays for is checked to decode within floor.

func DecodeAny

func DecodeAny(buf []byte) (any, []byte, error)

DecodeAny reads one lib0-Any-encoded value from buf and returns the value plus the unconsumed tail.

Tag → Go type mapping:

binary (116)    → []byte (slice is copied; never aliases buf)
array (117)     → []any (recursive)
object (118)    → map[string]any (recursive)
string (119)    → string
true (120)      → true
false (121)     → false
bigint (122)    → block.BigInt (8 bytes BE signed, lib0's writeBigInt64)
float64 (123)   → float64
float32 (124)   → float64 (widened; downstream callers rarely care
                   about the source-width distinction)
integer (125)   → int64, or float64 negative zero for a zero with the
                   sign bit, which lib0 reads as -0
null (126)      → nil
undefined (127) → block.Undefined

Unknown tags return ErrUnsupportedAnyTag, and arrays and objects nested deeper than anyval.MaxNesting levels ErrAnyTooDeep.

func DecodeContent

func DecodeContent(buf []byte, refNum uint8) (block.Content, []byte, error)

DecodeContent reads a Content payload from buf given the content ref-number (the low nibble of the info byte). Returns the parsed Content plus the unconsumed tail.

Mirrors yrs/src/block.rs ItemContent::decode dispatch.

func DecodeContentV2

func DecodeContentV2(dec *DecoderV2, refNum uint8) (block.Content, error)

DecodeContentV2 reads a Content payload from V2 column streams given the content ref-number (low nibble of info byte). Mirror of EncodeContentV2.

func DecodeStateVector

func DecodeStateVector(buf []byte) (store.StateVector, []byte, error)

DecodeStateVector parses a V1 wire-encoded StateVector from buf and returns the StateVector plus the unconsumed tail.

Mirrors yrs StateVector::decode (state_vector.rs ~line 100).

func DiffUpdateBytes added in v1.50.0

func DiffUpdateBytes(update []byte, sv store.StateVector, v2 bool, floor int) ([]byte, error)

DiffUpdateBytes is yjs diffUpdate (v2 false) or diffUpdateV2: update's structs from sv on, without integrating them, and its delete set as read. For each client's run of structs (until the client changes, across the sections of one client next to each other): a Skip where the run starts is passed, the structs ending at or before sv[client] are dropped, the first past it is written from sv[client] (an item cut there is written as yjs's Item.write with an offset writes it: its key bit kept), and every struct after it of that client, Skips included.

func EncodeAny

func EncodeAny(buf []byte, v any) []byte

EncodeAny appends the lib0 Any TLV encoding of v to buf.

Supported variants:

  • nil → null (tag 126)
  • bool → true/false (tags 120/121)
  • string → string (tag 119, varstring payload)
  • int / int32 / int64 with |v| <= 2^31-1 → integer (tag 125, varint payload), lib0's BITS31 test
  • any other integer → float32 (tag 124) when float32 holds it exactly, else float64 (tag 123), as lib0 classifies the same number
  • float32 → float32 (tag 124, 4-byte BE payload)
  • float64 → float32 (tag 124) when it is not an integer and float32 holds it exactly (0.5, 2.5, ±Inf), else float64 (tag 123, 8-byte BE payload). lib0 also writes an integral double such as 3.0 as a varint; ygo keeps it a float64 so it decodes back as a float64. That integral case is the one number class whose bytes differ.
  • negative zero (float64 or float32) → 7d40, the varint with the sign bit and no magnitude that lib0 writes for -0
  • block.Undefined → undefined (tag 127)
  • block.BigInt → bigint (tag 122, 8 bytes big-endian signed, lib0's writeBigInt64)
  • []byte → binary (tag 116, varuint length + bytes)
  • []any → array (tag 117, varuint count + each element recursively)
  • map[string]any → object (tag 118, varuint count + each (varstring key + Any value)). A Go map has no order, so the keys go out as JavaScript would enumerate them after decoding: array-index keys first in ascending order, then the others sorted (anyval.SortedJSOrder). Deterministic across runs.

Mirrors lib0/encoding.js writeAny.

func EncodeContent

func EncodeContent(buf []byte, c block.Content) []byte

EncodeContent appends the wire-format payload of c to buf. Caller has already emitted the info byte; this writes only the content field that follows.

Mirrors yrs/src/block.rs:1844-1872 ItemContent::encode.

Supported in this commit: KindAny, KindString, KindBinary, KindDeleted, KindType, KindFormat, KindEmbed. Skipped: KindDoc, KindMove, KindJSON. All deferred kinds panic on encode rather than emit silently-wrong bytes.

func EncodeContentV2

func EncodeContentV2(enc *EncoderV2, c block.Content)

EncodeContentV2 writes a Content payload via the V2 column API. Mirrors EncodeContent (V1) but routes per the per-ContentKind wire layout documented in yjs/src/structs/Content*.js.

func EncodeDiff

func EncodeDiff(d *doc.Doc, txn *doc.Transaction, remoteSV store.StateVector) []byte

EncodeDiff returns the V1 wire bytes for the blocks the local doc has that the remote doc (per remoteSV) does not. A nil remoteSV is treated as the empty SV — emit everything.

Mirrors yjs writeStateAsUpdate: the structs from writeClientsStructs (each client from the remote's clock, the first struct cut at that clock) and the delete set of the whole store.

func EncodeDiffV2

func EncodeDiffV2(d *doc.Doc, txn *doc.Transaction, remoteSV store.StateVector) []byte

EncodeDiffV2 returns V2 wire bytes for the blocks the local doc has that the remote (per remoteSV) does not: the V2 form of EncodeDiff, each client from the remote's clock with the first struct cut at that clock, then the whole store's delete set.

func EncodeDiffV2WithPending added in v1.42.0

func EncodeDiffV2WithPending(d *doc.Doc, txn *doc.Transaction, sv store.StateVector) []byte

EncodeDiffV2WithPending is the V2 twin of EncodeDiffWithPending.

func EncodeDiffWithPending added in v1.42.0

func EncodeDiffWithPending(d *doc.Doc, txn *doc.Transaction, sv store.StateVector) []byte

EncodeDiffWithPending is EncodeDiff plus the pending buffer from sv on, in the caller's transaction: the bytes of yjs encodeStateAsUpdate(doc, sv), the store part and the queue merged as yjs merges them (buildMergePlan). Where the store itself is laid out differently from yjs's (docs/tech-debt.md), so is this.

func EncodeDocOpts added in v1.22.0

func EncodeDocOpts(buf []byte, opts map[string]any) []byte

EncodeDocOpts appends a subdocument's options as the lib0 Any object yjs writes for them. yjs builds that object in a fixed order, gc, autoLoad, meta (ContentDoc's constructor), where EncodeAny sorts keys, so with two or more options the bytes would differ. Keys yjs never writes follow, sorted.

func EncodeSnapshot added in v0.10.0

func EncodeSnapshot(s Snapshot) []byte

EncodeSnapshot returns the V1 wire encoding of s: the delete set followed by the state vector. Byte-compatible with yjs `encodeSnapshot` (DSEncoderV1).

func EncodeSnapshotAsUpdateV1 added in v0.10.0

func EncodeSnapshotAsUpdateV1(bs *store.BlockStore, snap Snapshot) []byte

EncodeSnapshotAsUpdateV1 builds a V1 update that contains, for each client, only the cells with clock strictly below the snapshot's clock for that client, plus the snapshot's delete set. Applying this update to a fresh document reconstructs the exact state captured by the snapshot.

Call SplitAtSnapshotBoundaries first so no cell straddles a snapshot boundary. The wire shape matches EncodeDiff (per-client runs in descending client order, then the delete set).

func EncodeSnapshotAsUpdateV2 added in v1.44.0

func EncodeSnapshotAsUpdateV2(bs *store.BlockStore, snap Snapshot) []byte

EncodeSnapshotAsUpdateV2 is EncodeSnapshotAsUpdateV1 in V2, as yjs createDocFromSnapshot writes it (UpdateEncoderV2): V2 carries what V1 cannot, such as a format value or an embed that is undefined itself.

func EncodeStateAsUpdate

func EncodeStateAsUpdate(d *doc.Doc) []byte

EncodeStateAsUpdate returns the V1 wire bytes for the doc's full state — equivalent to encoding against an empty remote state vector. The caller may pass an existing transaction for read access; if nil a fresh ReadTxn is acquired and released.

It leaves the pending buffer out: the store's state alone, as a transaction's update and a snapshot hold it. ygo.EncodeStateAsUpdate includes it (EncodeStateAsUpdateWithPending), as yjs does.

func EncodeStateAsUpdateV2

func EncodeStateAsUpdateV2(d *doc.Doc) []byte

EncodeStateAsUpdateV2 returns V2 wire bytes for the doc's full state. Mirrors EncodeStateAsUpdate. Caller-side dispatch: V1 vs V2 is the caller's choice (no autodetect on the wire side).

func EncodeStateAsUpdateV2WithPending added in v1.19.0

func EncodeStateAsUpdateV2WithPending(d *doc.Doc) []byte

EncodeStateAsUpdateV2WithPending is the V2 twin. The formats differ in how a Skip carries its length - V2 puts it in the rest stream rather than the len column, an anomaly inherited from yjs and already honoured by the decoder - so the two emitters cannot share a writer, only the plan.

func EncodeStateAsUpdateWithPending added in v1.19.0

func EncodeStateAsUpdateWithPending(d *doc.Doc) []byte

EncodeStateAsUpdateWithPending is EncodeStateAsUpdate plus the pending buffer, in V1 wire format. See the file comment for why the two differ.

func EncodeStateVector

func EncodeStateVector(sv store.StateVector, buf []byte) []byte

EncodeStateVector appends the V1 wire encoding of sv to buf and returns the extended slice. Wire layout:

varuint clientCount
clientCount × (varuint clientID, varuint clock)

Clients are sorted ascending by clientID for deterministic output. JS Yjs / yrs accept any order on decode; the canonical sort keeps our round-trip byte-equality tests stable.

Mirrors yrs StateVector::encode (state_vector.rs ~line 80).

func EncodeStateVectorFromUpdate added in v1.13.0

func EncodeStateVectorFromUpdate(update []byte) ([]byte, error)

EncodeStateVectorFromUpdate is StateVectorFromUpdateBytes for a V1 update (yjs encodeStateVectorFromUpdate).

func EncodeTransactionUpdate added in v1.22.0

func EncodeTransactionUpdate(t *doc.TransactionMut) []byte

EncodeTransactionUpdate returns the V1 update for one committed transaction, or nil when the transaction created no structs and deleted nothing. Mirrors yjs writeUpdateMessageFromTransaction, the bytes of doc.on('update'): every struct from the transaction's start state on (the first of each client cut at that clock, as in EncodeDiff) and the delete set of what this transaction deleted, not the whole store's.

Call it after Commit's squash and garbage collection, as Doc's update handlers do, so the bytes describe the final layout.

func EncodeTransactionUpdateV2 added in v1.22.0

func EncodeTransactionUpdateV2(t *doc.TransactionMut) []byte

EncodeTransactionUpdateV2 is EncodeTransactionUpdate in V2, the bytes of doc.on('updateV2').

func EqualSnapshots added in v0.10.0

func EqualSnapshots(a, b Snapshot) bool

EqualSnapshots reports whether two snapshots carry the same delete set and state vector. Mirrors yjs equalSnapshots.

func HasPending

func HasPending(t *doc.Transaction) bool

HasPending reports whether the doc has any queued items awaiting dependencies.

func LooksLikeUpdateV2 added in v1.45.0

func LooksLikeUpdateV2(buf []byte) bool

LooksLikeUpdateV2 reports whether buf decodes as a V2 update holding no more structs or cached-key bytes than it has bytes: a diagnosis that costs no more than reading buf as V1 would (ValidateUpdate asks it of bytes it refused), where DecodeUpdateV2 may expand a short input to a million structs.

func MergeUpdateBytes added in v1.50.0

func MergeUpdateBytes(updates [][]byte, v2 bool, floor int) ([]byte, error)

MergeUpdateBytes is yjs mergeUpdates (v2 false) or mergeUpdatesV2 of two updates or more: their structs merged without integrating them (mergeStreams), their delete sets merged. V2 inputs are decoded one after another, each within its own budget, and together may hold at most max(their bytes, floor) structs, else ErrUpdateTooDense before the next is read; an output holding more structs than max(its length, floor) must decode, as a receiver would check it.

func MissingSV

func MissingSV(t *doc.Transaction) store.StateVector

MissingSV returns the state-vector of clocks the doc needs to receive in order to drain its pending buffer. Sync-protocol servers send this back to peers as a re-fetch request.

Returns an empty SV when the pending buffer is empty.

func PendingFingerprint added in v1.54.0

func PendingFingerprint(t interface{ PendingState() any }) []byte

PendingFingerprint identifies what the pending buffer holds: the IDs and lengths of its queued blocks, client by client, and its queued delete ranges. It is empty when nothing is pending; two buffers holding the same blocks and ranges give the same bytes. t is a transaction of either kind.

func SplitAtSnapshotBoundaries added in v0.10.0

func SplitAtSnapshotBoundaries(bs *store.BlockStore, snap Snapshot)

SplitAtSnapshotBoundaries forces a clean cell boundary at each client's snapshot clock, so EncodeSnapshotAsUpdateV1 can emit exactly the clocks [0, snapshotClock) without including content created after the snapshot. Mirrors yjs's getItemCleanStart pass in createDocFromSnapshot. Mutates the store (splitting is semantically transparent), so the caller must hold a write transaction.

func StateStructBound added in v1.45.0

func StateStructBound(d *doc.Doc) int

StateStructBound is an upper bound on the structs EncodeStateAsUpdateV2WithPending writes for d: a struct per cell of the store, and per queued block one for it and one for a Skip before it.

func StateVectorFromUpdateBytes added in v1.53.0

func StateVectorFromUpdateBytes(update []byte, v2 bool, floor int) ([]byte, error)

StateVectorFromUpdateBytes is yjs encodeStateVectorFromUpdate (v2 false) or encodeStateVectorFromUpdateV2, which write the same bytes: for each run of one client in wire order, the clock it reaches counting from 0 until a Skip, written as (client, clock) when the client changes and the clock is not 0, clients in the order met (a client in two runs twice), the count first. As in yjs, the first struct's clock is taken before it is checked for a Skip, and no gap between sections of one client is checked.

func TxnHeldStructs added in v1.45.0

func TxnHeldStructs(txn *doc.TransactionMut) int

TxnHeldStructs is the number of structs the transaction's document holds: the store's cells and the queued blocks. Both are kept as they change, so asking costs nothing whatever the number of clients.

func UpdateAddsNothing added in v1.37.0

func UpdateAddsNothing(d *doc.Doc, update []byte) (bool, error)

UpdateAddsNothing reports whether applying a V1 update to d would change nothing: every block lies within d's state vector and every deletion is already in d's delete set. It is yjs snapshotContainsUpdate against the document's current snapshot, which a Hocuspocus server uses to answer a read-only client's SyncStep2 with SyncStatus 1 when it carries nothing new.

Types

type Block

type Block struct {
	Kind BlockKind

	Item *block.Item // WireBlockItem
	ID   block.ID    // WireBlockGC, WireBlockSkip
	Len  uint64      // WireBlockGC, WireBlockSkip
	// contains filtered or unexported fields
}

Block is one block-shaped record inside an Update. For WireBlockItem the Item field carries the parsed *block.Item with Origin / RightOrigin set but Left / Right nil (Repair fixes those at apply time). For WireBlockGC and WireBlockSkip only ID and Len matter.

type BlockKind

type BlockKind uint8

BlockKind discriminates the three on-the-wire block variants: regular Item, GC tombstone range, Skip range.

const (
	WireBlockItem BlockKind = 0
	WireBlockGC   BlockKind = 1
	WireBlockSkip BlockKind = 2
)

type DecoderV2

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

DecoderV2 is the column-oriented update decoder matching yjs UpdateDecoderV2 (testdata/gen/node_modules/yjs/src/utils/ UpdateDecoder.js:96-180). The constructor reads all 9 column decoders upfront from the wire (each as a length-prefixed varbuffer); per-field Read* methods then pull one value from the appropriate column per block iteration.

Top-level update headers (block-count, start-clock, client-count) come from the raw rest stream via ReadVarUint — only per-block field reads pull from columns.

Pattern: construct with NewDecoderV2, call Read* in the SAME order the encoder called Write*. Wire format has no length self-check; any iteration-order mismatch silently corrupts.

func NewDecoderV2

func NewDecoderV2(buf []byte) (*DecoderV2, error)

NewDecoderV2 wraps buf as a V2 decoder. Reads the feature flag + 9 column lengths upfront so subsequent Read* calls are O(1) per value.

func (*DecoderV2) AdvanceRest

func (d *DecoderV2) AdvanceRest(n int)

AdvanceRest moves the rest cursor forward by n bytes. Content decoders call this after consuming bytes via ReadRestBytes.

func (*DecoderV2) ReadAny

func (d *DecoderV2) ReadAny() (block.Any, error)

ReadAny consumes the next lib0 Any TLV from the rest stream.

func (*DecoderV2) ReadAnyOrdered added in v1.41.0

func (d *DecoderV2) ReadAnyOrdered() (block.Any, *block.KeyOrder, error)

ReadAnyOrdered is ReadAny that also returns the key order of the objects in the value (decodeAnyOrdered).

func (*DecoderV2) ReadClient

func (d *DecoderV2) ReadClient() (uint64, error)

ReadClient returns the next client ID from the shared client column.

func (*DecoderV2) ReadInfo

func (d *DecoderV2) ReadInfo() (uint8, error)

ReadInfo returns the next info byte from the info RLE column.

func (*DecoderV2) ReadJSON

func (d *DecoderV2) ReadJSON() (block.Any, error)

ReadJSON reads a format value or an embed: a lib0 Any in the rest stream, as yjs UpdateDecoderV2.readJSON reads it, with numbers mapped to the types the V1 path yields so callers see the same Go types whichever wire format delivered the document. See json_any.go.

A value that is undefined itself reads as block.Undefined{}, as yjs keeps it (lib0 tag 127): the text code gives a format marker with that value yjs's meaning at each place it reads one. V1 writes JSON, which has no undefined, and yjs cannot write such a document in V1.

func (*DecoderV2) ReadJSONOrdered added in v1.41.0

func (d *DecoderV2) ReadJSONOrdered() (block.Any, *block.KeyOrder, error)

ReadJSONOrdered is ReadJSON that also returns the key order of the objects in the value. jsonValueFromAny only rewrites numbers, so the order still fits the value it returns.

func (*DecoderV2) ReadKey

func (d *DecoderV2) ReadKey() (string, error)

ReadKey resolves a map-key reference. Unlike the encoder side, the decoder DOES populate a key table — see port-note gotcha 5 for the asymmetry. First read of a given keyClock value reads a string from the string column AND caches it; subsequent reads of the same keyClock return the cached string.

func (*DecoderV2) ReadLeftID

func (d *DecoderV2) ReadLeftID() (block.ID, error)

ReadLeftID pulls one (client, clock) pair from the shared client column + left-clock column.

func (*DecoderV2) ReadLen

func (d *DecoderV2) ReadLen() (uint64, error)

ReadLen returns the next length value from the length column.

func (*DecoderV2) ReadParentInfo

func (d *DecoderV2) ReadParentInfo() (bool, error)

ReadParentInfo returns true if the parent is referenced by root-name, false if by item ID. Maps the 0/1 byte from the parent-info RLE column.

func (*DecoderV2) ReadRestBytes

func (d *DecoderV2) ReadRestBytes() []byte

ReadRestBytes returns the unconsumed rest stream — used by content decoders that need raw access.

func (*DecoderV2) ReadRightID

func (d *DecoderV2) ReadRightID() (block.ID, error)

ReadRightID pulls from the shared client + right-clock columns.

func (*DecoderV2) ReadString

func (d *DecoderV2) ReadString() (string, error)

ReadString returns the next string from the string column.

func (*DecoderV2) ReadTypeRef

func (d *DecoderV2) ReadTypeRef() (uint64, error)

ReadTypeRef returns the next type ref from the type-ref RLE column, as read (DecodeContentV2 checks it).

func (*DecoderV2) ReadVarBuf

func (d *DecoderV2) ReadVarBuf() ([]byte, error)

ReadVarBuf consumes the next varbuffer from the rest stream.

func (*DecoderV2) ReadVarUint

func (d *DecoderV2) ReadVarUint() (uint64, error)

ReadVarUint returns the next varuint from the raw rest stream. Used for top-level structure headers.

type EncoderV2

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

EncoderV2 is the column-oriented update encoder matching yjs UpdateEncoderV2 (testdata/gen/node_modules/yjs/src/utils/ UpdateEncoder.js:115-220) and yrs EncoderV2. Block-write methods route field writes to 9 per-column buffers + 1 raw rest stream; Bytes() concatenates them with length prefixes behind a 0x00 feature flag byte.

Wire layout — see docs/yrs-port-notes/update-v2.md §1. Column order is wire-load-bearing; DO NOT reorder.

Top-level update headers (per-client block-count, start-clock, outer client-count) go to the rest stream via WriteVarUint — only per-block field writes get column-routed. See port note §4 gotcha "Top-level block-run structure stays the same as V1".

Pattern: construct with NewEncoderV2, call the per-field Write* methods + WriteVarUint for headers, then call Bytes() exactly once at the end to flush all columns and assemble the wire bytes. EncoderV2 is single-use; do not call Bytes() twice.

func NewEncoderV2

func NewEncoderV2() *EncoderV2

NewEncoderV2 returns a fresh EncoderV2 with all column buffers initialized.

func (*EncoderV2) Bytes

func (e *EncoderV2) Bytes() []byte

Bytes flushes every column and assembles the final V2 wire bytes per port-note §1. Must be called exactly once; do not call any Write* method afterwards.

Layout:

[0x00 feature flag]
[varuint len | keyClockBytes]
[varuint len | clientBytes]
[varuint len | leftClockBytes]
[varuint len | rightClockBytes]
[varuint len | infoBytes]
[varuint len | stringBytes]
[varuint len | parentInfoBytes]
[varuint len | typeRefBytes]
[varuint len | lenBytes]
[restBytes]                  (NO length prefix; reader takes the remainder)

func (*EncoderV2) WriteAny

func (e *EncoderV2) WriteAny(v block.Any)

WriteAny routes a lib0 Any TLV value to the rest stream. Used by ContentAny / ContentEmbed when V2 hits them — note V2 keeps Any in rest (no column for it).

func (*EncoderV2) WriteAnyOrdered added in v1.41.0

func (e *EncoderV2) WriteAnyOrdered(v block.Any, o *block.KeyOrder)

WriteAnyOrdered is WriteAny with the key order a decoded value keeps.

func (*EncoderV2) WriteClient

func (e *EncoderV2) WriteClient(client uint64)

WriteClient routes a standalone client ID (e.g. per-client block-run header) to the shared client column.

func (*EncoderV2) WriteInfo

func (e *EncoderV2) WriteInfo(info uint8)

WriteInfo routes an info byte to the per-byte RLE column.

func (*EncoderV2) WriteJSON

func (e *EncoderV2) WriteJSON(v block.Any)

WriteJSON writes a format value or an embed. In V2 that is a lib0 Any in the rest stream, NOT the JSON varstring V1 uses - yjs UpdateEncoderV2.writeJSON calls writeAny. This method used to reuse the V1 layout on the assumption that V2 "doesn't column-encode JSON payloads either", which is true and beside the point: the payload format differs, and the result was unreadable by yjs. See json_any.go.

func (*EncoderV2) WriteJSONOrdered added in v1.41.0

func (e *EncoderV2) WriteJSONOrdered(v block.Any, o *block.KeyOrder)

WriteJSONOrdered is WriteJSON with the key order a decoded value keeps. jsonValueForAny keeps the shape of a plain value, so the order still fits it; a value stored as JSON carries its own.

func (*EncoderV2) WriteKey

func (e *EncoderV2) WriteKey(key string)

WriteKey emits a map-key reference. Mirrors yjs's "bug" per port-note gotcha 5: the encoder-side key table is NEVER populated, so every WriteKey writes a fresh string into the string column and increments the keyClock counter. The decoder side DOES build a key table — asymmetric but wire-compatible.

func (*EncoderV2) WriteLeftID

func (e *EncoderV2) WriteLeftID(id block.ID)

WriteLeftID routes the (client, clock) pair to the shared client column + the left-clock column. Mirrors UpdateEncoderV2.writeLeftID (UpdateEncoder.js:156-159).

func (*EncoderV2) WriteLen

func (e *EncoderV2) WriteLen(l uint64)

WriteLen routes a run-length (GC range, ContentDeleted, content element count) to the length column.

func (*EncoderV2) WriteParentInfo

func (e *EncoderV2) WriteParentInfo(isRootName bool)

WriteParentInfo routes the "parent is name vs item-ID" boolean tag to the parent-info RLE column.

func (*EncoderV2) WriteRestBytes

func (e *EncoderV2) WriteRestBytes(b []byte)

WriteRestBytes appends raw bytes directly to the rest stream. Used by Content encoders (ContentAny, ContentBinary, etc.) that produce arbitrary byte payloads.

func (*EncoderV2) WriteRightID

func (e *EncoderV2) WriteRightID(id block.ID)

WriteRightID routes to the shared client column + the right-clock column.

func (*EncoderV2) WriteString

func (e *EncoderV2) WriteString(s string)

WriteString routes a string to the string column. Used for parent root-type names and ContentString payloads.

func (*EncoderV2) WriteTypeRef

func (e *EncoderV2) WriteTypeRef(ref uint8)

WriteTypeRef routes a TypeRef tag (Array=0, Map=1, Text=2, ...) to the type-ref RLE column. Used inside ContentType payloads.

func (*EncoderV2) WriteVarBuf

func (e *EncoderV2) WriteVarBuf(b []byte)

WriteVarBuf routes a length-prefixed byte array to the rest stream. Used by ContentBinary.

func (*EncoderV2) WriteVarUint

func (e *EncoderV2) WriteVarUint(n uint64)

WriteVarUint routes a generic varuint to the raw rest stream. Used for top-level structure headers: outer client count, per-client block count, start clock.

type IdSet

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

IdSet is a per-client set of half-open clock ranges. Used as the V1 wire DeleteSet. Insert auto-merges overlapping or adjacent ranges so the per-client list stays sorted and non-overlapping at all times.

Mirrors yrs IdSet (id_set.rs:121-135), simplified — yrs has a generic IdMapInner<V> with a () value type for the wire DeleteSet case; we just store []Range directly.

func DecodeIdSet

func DecodeIdSet(buf []byte) (*IdSet, []byte, error)

DecodeIdSet parses a V1 wire-encoded IdSet from buf and returns the IdSet plus the unconsumed tail.

func NewIdSet

func NewIdSet() *IdSet

NewIdSet returns an empty IdSet.

func (*IdSet) ClientCount

func (s *IdSet) ClientCount() int

ClientCount returns the number of distinct clients with at least one range in the set.

func (*IdSet) ClientRanges added in v1.24.0

func (s *IdSet) ClientRanges(client uint64) []Range

ClientRanges returns client's ranges, sorted and merged. The slice aliases internal state and must not be retained or mutated.

func (*IdSet) ClientsInOrder added in v1.24.0

func (s *IdSet) ClientsInOrder() []uint64

ClientsInOrder returns the clients in the order they were first added (for a decoded set, the order they were written in). The slice is new.

func (*IdSet) Contains

func (s *IdSet) Contains(client, clock uint64) bool

Contains reports whether the (client, clock) pair is covered by some range in the set.

func (*IdSet) Encode

func (s *IdSet) Encode(buf []byte) []byte

Encode appends the V1 wire encoding of s to buf and returns the extended slice. Wire layout:

varuint clientCount
clientCount × (
    varuint clientID
    varuint rangeCount
    rangeCount × (varuint start, varuint length)
)

Clients are emitted in DESCENDING order, matching the V1 delete-set wire form yjs produces (writeDeleteSet sorts "(a, b) => b[0] - a[0]"). Ranges within a client are already sorted by Insert. Note this differs from Iterate, which is ascending for general-purpose deterministic traversal; the wire form specifically tracks yjs, our byte-compatibility reference, not yrs (whose BTreeMap emits ascending). Single-client sets encode identically either way, which is why the difference stayed latent until multi-client snapshots.

func (*IdSet) Insert

func (s *IdSet) Insert(client, start, length uint64)

Insert adds the half-open range [start, start+length) for client. Overlapping or adjacent existing ranges are merged.

Mirrors yrs IdRanges::insert (id_set.rs:34-90 area).

func (*IdSet) Iterate

func (s *IdSet) Iterate(fn func(client uint64, ranges []Range))

Iterate calls fn once per client, in ascending client ID order. The ranges slice handed to fn must NOT be retained or mutated; it aliases internal state.

type Pending

type Pending struct {
	// Blocks groups queued wire-level Block records by clientID.
	// Per-client entries are kept in clock-ascending order to
	// preserve causal-prefix ordering — yrs relies on this when
	// dropping a contiguous prefix that has become satisfied.
	Blocks map[uint64][]Block

	// DeleteSet stores ranges whose target IDs are not yet present
	// in the local store. yrs calls this `pending_ds`. Each Apply
	// re-scans these ranges; those whose target now exists get
	// applied.
	DeleteSet *IdSet

	// Missing is yjs's pendingStructs.missing: for each client the
	// queued blocks wait on, the clock past which the store has to get
	// before a retry can integrate anything (integrateStack). It decides
	// whether the queue is retried; MissingSV, what to ask a peer for, is
	// computed separately.
	Missing map[uint64]uint64
	// contains filtered or unexported fields
}

Pending buffers items and delete-set entries that arrived before their causal dependencies (Origin / RightOrigin / Parent-by-ID referring to clocks the local BlockStore has not yet seen).

yrs's equivalent state lives in `Store::pending` (`store.rs` field `pending: Option<PendingUpdate>`) plus `pending_ds` (`Option<DeleteSet>`). We collapse both into a single Pending struct attached to the Doc via the opaque `pendingState any` slot.

Lifecycle (yjs readUpdateV2): Update.Apply integrates the incoming update's blocks by dependency stack (integrateStack), queues what is left, applies the update's delete set and then the queued one, and, when the store has passed a clock in Missing, integrates the queued blocks once more and applies the queued delete set again. Items that integrate leave the queue; the leftover stays for the next ApplyUpdate call.

Concurrency: Pending is mutated only under the doc's write lock (acquired by the surrounding TransactionMut). No internal mutex.

func GetPending

func GetPending(t *doc.Transaction) *Pending

GetPending returns the doc's current pending buffer, or nil if no pending state is installed (queue is empty). Caller MUST hold at least a read transaction on d.

The returned pointer is the live buffer — mutate at your peril. Use Pending.MissingSV and Pending.BlockCount for safe inspection.

func NewPending

func NewPending() *Pending

NewPending returns an empty buffer.

func (*Pending) BlockCount

func (p *Pending) BlockCount() int

func (*Pending) IsEmpty

func (p *Pending) IsEmpty() bool

IsEmpty reports whether the buffer holds zero queued items.

func (*Pending) MissingSV

func (p *Pending) MissingSV(bs *store.BlockStore) store.StateVector

MissingSV returns the state vector to ask a peer with: for every client the queue waits on, the clock the local store has for it, so a peer's EncodeDiff against the vector sends everything from there on. The clients are those of a queued block with a hole before it in its own sequence, those a queued block refers to (Origin, RightOrigin, Parent-by-ID) without the store having the target, and those with a queued delete range.

It names what the store has, not the clock of the missing target: a vector naming the target's clock + 1, as this did before, tells the peer the target itself is known, and the diff leaves it out. A first-in-a-root item has no reference to walk, so its own hole is the only way to name it; a queue holding only deletes still needs the clients they delete from.

Returns an empty map when nothing is missing.

type Range

type Range struct {
	Start  uint64
	Length uint64
}

Range is a half-open clock interval [Start, Start+Length). The wire form encodes (Start, Length), not (Start, End). yrs's in-memory Range<u32> is half-open; the wire form is unambiguous.

Per docs/yrs-port-notes/update-v1.md gotcha 2.

func (Range) End

func (r Range) End() uint64

End returns the (exclusive) upper bound of the range.

type Snapshot added in v0.10.0

type Snapshot struct {
	DS *IdSet
	SV store.StateVector
}

Snapshot is a point-in-time marker of a document's history: the set of deleted ID ranges (DS) plus the per-client clock heads (SV) as of the snapshot moment. Replaying the document up to SV, with DS applied as the deletions-so-far, reconstructs exactly the state the document had when the snapshot was taken.

Mirrors yjs Snapshot (src/utils/Snapshot.js): a {ds, sv} pair. The wire form is writeDeleteSet(ds) followed by writeStateVector(sv).

func CreateSnapshot added in v0.10.0

func CreateSnapshot(bs *store.BlockStore) Snapshot

CreateSnapshot captures the current delete set and state vector of the store. Mirrors yjs's `snapshot(doc)`.

For snapshots to be useful for time-travel the doc should be created with GC disabled, otherwise deleted content the snapshot references may have been collected. The capture itself does not require it.

func DecodeSnapshot added in v0.10.0

func DecodeSnapshot(buf []byte) (Snapshot, error)

DecodeSnapshot parses a V1 snapshot produced by EncodeSnapshot or yjs `encodeSnapshot`.

type Update

type Update struct {
	Blocks    map[uint64][]Block
	DeleteSet *IdSet
}

Update is the parsed-but-not-yet-applied form of a V1 wire update. Blocks groups records by client; per-client lists are stored in emission order (clock-ascending within a client).

func DecodeOwnUpdate added in v1.53.0

func DecodeOwnUpdate(buf []byte) (*Update, []byte, error)

DecodeOwnUpdate is DecodeUpdate for bytes ygo just encoded from its own document: strings are read strictly, shared type refs as DecodeStoredUpdate reads them.

func DecodeOwnUpdateV2 added in v1.44.0

func DecodeOwnUpdateV2(buf []byte) (*Update, error)

DecodeOwnUpdateV2 is DecodeUpdateV2 for bytes ygo itself just encoded (a snapshot restored through V2), whose counts are exact: no bound on the number of clients or structs.

func DecodeStoredUpdate added in v1.26.0

func DecodeStoredUpdate(buf []byte) (*Update, []byte, error)

DecodeStoredUpdate is DecodeUpdate for bytes ygo itself stored: strings are read as stored, so an update a release before v1.26 stored with invalid UTF-8 still decodes, unchanged (lib0.ReadVarStringAsStored), and shared type refs as releases before 1.53.0 read them (checkTypeRef).

func DecodeUpdate

func DecodeUpdate(buf []byte) (*Update, []byte, error)

DecodeUpdate decodes a V1 update. A string with invalid UTF-8 returns lib0.ErrInvalidUTF8, as yjs throws on it.

func DecodeUpdateV2

func DecodeUpdateV2(buf []byte) (*Update, error)

DecodeUpdateV2 parses V2 wire bytes into an Update. The returned Update is ready for Apply but its blocks have nil Left/Right — Repair fills those at apply time. Mirrors DecodeUpdate (V1) but pulls per-field bytes from the column decoders.

func DecodeUpdateV2Floor added in v1.45.0

func DecodeUpdateV2Floor(buf []byte, floor int) (*Update, error)

DecodeUpdateV2Floor is DecodeUpdateV2 with floor in place of V2StructFloor: the update may hold max(len(buf), floor) structs. Tests of what is bounded past the floor use a small one.

func NewUpdate

func NewUpdate() *Update

NewUpdate returns an empty Update.

func (*Update) Apply

func (u *Update) Apply(txn *doc.TransactionMut) error

Apply integrates every block and delete-set entry in u into the doc represented by txn. Items whose causal dependencies the local store has not yet seen — Origin, RightOrigin, or Parent-by-ID references to unseen clocks — are queued in the doc's pending buffer (Pending) for automatic retry on subsequent Apply calls that satisfy them. Delete-set ranges targeting unseen IDs are likewise queued.

Always returns nil. The previous ErrMissingDependency contract is retired; see docs/tech-debt.md "Pending update buffer not implemented" (now resolved). The signature stays `(*TransactionMut) error` for backwards compatibility with callers that check the error path.

Mirrors yrs Update::integrate (update.rs:234-301) plus the pending-buffer retry loop yrs runs in `Store::try_integrate_pending`.

type UpdateMeta added in v1.53.0

type UpdateMeta struct {
	From, To map[uint64]uint64
}

UpdateMeta is yjs parseUpdateMeta's result: per client, the clock its structs start at and the clock they end at.

func ParseUpdateMetaBytes added in v1.53.0

func ParseUpdateMetaBytes(update []byte, v2 bool, floor int) (UpdateMeta, error)

ParseUpdateMetaBytes is yjs parseUpdateMeta (v2 false) or parseUpdateMetaV2: for each run of one client in wire order, From is the clock it starts at (a later run of the client overwrites) and To the clock its last struct ends at, Skips included.

Jump to

Keyboard shortcuts

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