Skip to content

Latest commit

 

History

History
491 lines (364 loc) · 20.5 KB

sync.md

File metadata and controls

491 lines (364 loc) · 20.5 KB

Syncing documents

Two documents converge when each one applies the other's updates. This page covers the bytes that travel between them, and the helpers that speak the same protocols as Yjs.

It covers:

ycpp has no transport. You move the bytes yourself: over a websocket, a serial line, a file, anything.

Updates

An update is a byte string that describes changes to a document. It is the Yjs update format, so a Yjs peer reads it as it is.

There are three ways to get one:

  1. Doc::on_update calls you once per transaction, with that transaction's update.
  2. Doc::encode_state_as_update() gives the whole document as one update.
  3. Doc::encode_state_as_update(state_vector) gives only what a peer is missing (see the next section).

You apply an update with Doc::apply_update. It returns std::expected<void, ycpp::Error>.

#include <ycpp/doc.hpp>
#include <ycpp/map.hpp>

#include <span>
#include <vector>

ycpp::Doc a(1);
ycpp::Doc b(2);

// Forward every transaction of `a` to `b`. A plain function and a context pointer: no allocation.
ycpp::Connection link = a.on_update(
    +[](void* context, std::span<const ycpp::byte> update) {
      (void)static_cast<ycpp::Doc*>(context)->apply_update(update);
    },
    &b);

(void)a.map("settings").set("gain", ycpp::Any{0.5});
// b.to_json("settings") == R"({"gain":0.5})"

link.disconnect();

Some facts about updates:

  • Applying is idempotent. Applying the same update twice changes nothing the second time.
  • Order does not matter. Updates can arrive in any order. Ones that come too early wait (see Pending updates).
  • on_update also fires for updates you apply. It fires for every transaction that changed the document, local or remote. That is what a relay needs. A peer that only talks to one other peer may send a remote update back; that is harmless, because applying twice changes nothing.
  • Empty transactions are silent. A transaction that changed nothing produces no update.

v1 and v2

Yjs has two update formats. Both describe the same changes.

  • v1 is the default everywhere: in Yjs, y-websocket, pycrdt and the sync protocol. on_update hands you v1.
  • v2 packs the same data into run-length encoded columns. It is often smaller.

The v2 entry points mirror the v1 ones:

v1 v2 Yjs name
Doc::apply_update(update) Doc::apply_update_v2(update, origin) applyUpdate / applyUpdateV2
Doc::encode_state_as_update(sv) Doc::encode_state_as_update_v2(sv) encodeStateAsUpdate / ...V2
merge_updates(updates) merge_updates_v2(updates) mergeUpdates / mergeUpdatesV2
encode_state_vector_from_update(u) encode_state_vector_from_update_v2(u) encodeStateVectorFromUpdate / ...V2

convert_update_v1_to_v2 and convert_update_v2_to_v1 translate between the two without loss. The tests check that ycpp's v2 bytes match Yjs byte for byte.

apply_update_v2 takes an origin: observers see it through Doc::origin() while the apply runs. apply_update (v1) takes none; its observers see a null origin.

Use v1 unless both ends agreed on v2. The sync helpers below speak v1 only, as y-protocols does.

State vectors and diffs

A state vector says how much of each client's history a document has. It maps each client id to the next clock that document expects from it.

A clock counts the units a client wrote. For text that is one per UTF-16 code unit, so typing "abc" moves the clock by 3. A deletion never moves a clock.

A state vector selects the diff

To send a peer only what it misses:

  1. The peer sends you its state vector.
  2. You call encode_state_as_update with it.
  3. You get every struct past the peer's clocks, plus your whole delete set.

The delete set always goes whole. It is small: deletions are stored as clock ranges, not one entry per character.

#include <ycpp/doc.hpp>
#include <ycpp/encoding.hpp>
#include <ycpp/state_vector.hpp>
#include <ycpp/text.hpp>

ycpp::Doc a(1);
ycpp::Doc b(2);
(void)a.text("t").insert(0, "abc");
(void)b.apply_update(a.encode_state_as_update());
(void)a.text("t").insert(3, "def");

// b says what it has. On the wire this is a byte string.
ycpp::Encoder encoded(b.memory());
b.state_vector().encode(encoded);

// a reads it back and answers with the difference.
ycpp::Decoder decoder(encoded.bytes());
const std::expected<ycpp::StateVector, ycpp::Error> since = ycpp::StateVector::decode(decoder);
if (since) {
  const std::vector<ycpp::byte> diff = a.encode_state_as_update(*since);
  (void)b.apply_update(diff);  // b.text("t").to_string() == "abcdef"
}

StateVector is a small sorted list of (client, clock) pairs:

  • get(client) returns the next clock, or 0 for a client it never saw.
  • set(client, clock) writes one entry.
  • entries() returns the pairs, sorted by client.
  • encode(encoder) and the static decode(decoder) write and read the Yjs wire form.

Encoded state vectors list clients in descending id order, as Yjs writes them. Yrs (and so pycrdt) writes them ascending. The decoded result is the same.

Working with updates without a document

These functions read and write update bytes directly. They are in <ycpp/update.hpp>. Each one returns std::expected<std::vector<byte>, Error>.

Function What it does Yjs name
merge_updates(updates) One update holding everything in updates. mergeUpdates
encode_state_vector_from_update(update) The state vector an update covers. encodeStateVectorFromUpdate
get_update(update, state_vector) The part of update a peer at state_vector misses. diffUpdate
convert_update_v1_to_v2(update) Same update, v2 format. convertUpdateFormatV1ToV2
convert_update_v2_to_v1(update) Same update, v1 format. convertUpdateFormatV2ToV1

A server that stores updates can use them to compact a log, or to answer a sync request, without loading a document. This example is adapted from tests/test_update.cpp:

#include <ycpp/doc.hpp>
#include <ycpp/map.hpp>
#include <ycpp/update.hpp>

#include <span>
#include <vector>

ycpp::Doc source(4);
(void)source.map("m").set("a", ycpp::Any{1});
const std::vector<ycpp::byte> first = source.encode_state_as_update();
(void)source.map("m").set("b", ycpp::Any{2});
const std::vector<ycpp::byte> full = source.encode_state_as_update();

// What a peer that only holds `first` is missing.
const auto state = ycpp::encode_state_vector_from_update(first);
const auto delta = ycpp::get_update(full, *state);

// Two updates folded into one.
const std::vector<std::span<const ycpp::byte>> parts{first, *delta};
const auto merged = ycpp::merge_updates(parts);
// A fresh document fed `*merged` reads {"a":1,"b":2}.

(Check each std::expected before you dereference it. The example skips that to stay short.)

Pending updates

Updates can arrive out of order. An update may name structs the document does not have yet: the character to its left, or the one to its right, or the type it belongs to. Yjs does not drop such an update, and neither does ycpp. The part that cannot land yet waits in a pending list.

An out-of-order update waits in pending

What happens, step by step:

  1. An update arrives. Every struct whose dependencies are present integrates right away.
  2. A struct that depends on a missing id goes to the pending list. ycpp records the id it waits for.
  3. A deletion of clocks the document has not seen goes to a pending delete set.
  4. The state vector does not count pending structs. It only says what really integrated.
  5. A later update brings the missing id. ycpp then retries the pending list, and the waiting structs integrate.

The pending list is only retried when one of the ids it waits for arrives. An unrelated update does not rescan it, so a large pending list does not slow down every apply.

encode_state_as_update includes the pending structs and pending deletions, after the document's own structs. Yjs does the same. So a document that relays updates passes on what it could not apply itself, and another peer that has the missing piece can use them.

#include <ycpp/doc.hpp>
#include <ycpp/state_vector.hpp>
#include <ycpp/text.hpp>

ycpp::Doc a(1);
(void)a.text("t").insert(0, "abc");
const ycpp::StateVector after_abc = a.state_vector();
const std::vector<ycpp::byte> first = a.encode_state_as_update();
(void)a.text("t").insert(3, "def");
const std::vector<ycpp::byte> second = a.encode_state_as_update(after_abc);

ycpp::Doc b(2);
ycpp::TextRef text = b.text("t");
(void)b.apply_update(second);    // "def" needs "c" (1:2) on its left: it waits
// text.to_string() == ""   and   b.state_vector().get(1) == 0

(void)b.apply_update(first);     // "abc" arrives, the pending "def" is retried
// text.to_string() == "abcdef" and b.state_vector().get(1) == 6

There is no timeout. A struct waits until its dependency arrives, or until the document is destroyed. If a dependency never comes, the struct stays pending. The sync handshake below makes that unlikely: the step 2 answer carries everything the asking peer misses.

The sync protocol

y-protocols defines how two peers bring each other up to date. <ycpp/sync.hpp> speaks it. It has three messages:

Message Sub-type Payload Sent when
step 1 0 the sender's state vector a peer connects
step 2 1 an update with what the step 1 sender misses in answer to a step 1
update 2 an update after every local change

The y-protocols sync handshake

The handshake, step by step:

  1. Each peer sends a step 1 with its state vector as soon as it connects.
  2. Each peer answers the step 1 it receives with a step 2: the diff against that state vector.
  3. Each peer applies the step 2 it receives. Both now hold the same document.
  4. From then on, each local change goes out as an update message.

A message is the sub-type as a varuint, then the payload as a length-prefixed byte string.

Writing messages

Function Writes
write_sync_step1(encoder, doc) a step 1 with doc's state vector
write_sync_step2(encoder, doc, state_vector) a step 2. An empty state_vector means the whole document. Returns an error, and writes nothing, if state_vector does not decode.
write_update(encoder, update) an update message

Reading messages

Function Takes Returns
read_sync_message(decoder, reply, doc) a decoder at a sync message the sub-type it read. A step 1 writes its step 2 answer into reply. A step 2 or an update is applied to doc.
handle_sync_message(message, doc) one sync message, no outer frame (pycrdt's shape) the reply bytes: a step 2 for a step 1, empty otherwise
handle_message(frame, doc) one whole y-websocket frame the reply as a whole frame, ready to send. A frame that is not a sync frame returns an empty reply, not an error.

Framing for y-websocket

y-websocket puts one more varuint in front of every message: the message type. MessageType::sync is 0 and MessageType::awareness is 1. write_message(encoder, type, payload) adds it.

A frame in, a frame out: the reply from handle_message already carries its frame, so it goes straight to the socket. The messages you write yourself, like the step 1 and your updates, need write_message(..., MessageType::sync, ...).

Here is a complete client loop. send_frame is your transport.

#include <ycpp/any.hpp>
#include <ycpp/awareness.hpp>
#include <ycpp/doc.hpp>
#include <ycpp/encoding.hpp>
#include <ycpp/sync.hpp>

#include <span>

void send_frame(std::span<const ycpp::byte> frame);  // your websocket

void send_sync(std::span<const ycpp::byte> message) {
  ycpp::Encoder frame;
  ycpp::write_message(frame, ycpp::MessageType::sync, message);
  send_frame(frame.bytes());
}

// Once the socket is open: say what we have.
void on_open(const ycpp::Doc& doc) {
  ycpp::Encoder step1;
  ycpp::write_sync_step1(step1, doc);
  send_sync(step1.bytes());
}

// Every local change: send it as an update message.
void on_local_update(void*, std::span<const ycpp::byte> update) {
  ycpp::Encoder message;
  ycpp::write_update(message, update);
  send_sync(message.bytes());
}

// Every frame from the socket.
void on_frame(std::span<const ycpp::byte> frame, ycpp::Doc& doc, ycpp::Awareness& awareness,
              std::uint64_t now_ms) {
  ycpp::Decoder decoder(frame);
  const auto type = decoder.read_var_uint();
  if (!type) {
    return;  // not even a message type: drop it
  }
  if (*type == static_cast<std::uint64_t>(ycpp::MessageType::awareness)) {
    const auto update = decoder.read_var_uint8_array_view();
    if (update) {
      (void)awareness.apply_update(*update, ycpp::Any{"remote"}, now_ms);
    }
    return;
  }
  const auto reply = ycpp::handle_message(frame, doc);
  if (reply && !reply->empty()) {
    send_frame(*reply);  // the step 2 answer to the server's step 1, already framed
  }
}

// Wiring: doc.on_update(on_local_update);

on_update also fires for the updates handle_message applies, so this client echoes them back to the server. That is correct, only wasteful. To skip echoes, write local changes inside doc.transact(origin) and check doc.origin() in the handler.

Awareness

Awareness carries state that should not be stored in the document: a user's name, colour, cursor or selection. Each client publishes one JSON-like value. Peers keep the latest value per client, and forget clients that go silent.

<ycpp/awareness.hpp> is a port of y-protocols' awareness.js. It produces and reads the same bytes.

Awareness: one state per client, with a clock

States and clocks

Each client's entry has a state, a clock and a timestamp:

  • The state is an Any, usually a map. A missing state means the client left.
  • The clock goes up by one each time that client changes its state. A peer keeps an incoming entry only if its clock is newer than the one it holds. So an old message can never overwrite a newer state.
  • The timestamp (last_updated) is when this awareness last accepted an entry for that client.

meta_of(client) returns the clock and timestamp. state_of(client) returns the state, or null.

No timer inside

ycpp has no clock and no thread. Every call that needs the time takes now_ms, a millisecond count you choose (any monotonic source works). You call check_outdated(now_ms) from your own timer. y-protocols runs the same check every 3 seconds.

check_outdated does two things:

  1. It renews the local state when half the timeout has passed, so peers know this client is alive. With the default timeout of 30 000 ms that is every 15 s. Send the local state after it renews.
  2. It drops every other client that has been silent for the whole timeout. It returns those clients.

Using it

#include <ycpp/any.hpp>
#include <ycpp/awareness.hpp>
#include <ycpp/doc.hpp>
#include <ycpp/encoding.hpp>
#include <ycpp/json.hpp>
#include <ycpp/sync.hpp>

ycpp::Doc doc(7);
ycpp::Awareness awareness(doc, /*now_ms=*/0);   // starts with an empty map as the local state

const auto state = ycpp::parse_json(R"({"user":{"name":"alice","color":"#ff0000"}})");
awareness.set_local_state(*state, /*now_ms=*/0);
awareness.set_local_state_field("cursor", ycpp::Any{std::int64_t{3}}, /*now_ms=*/10);

// Send our own entry.
const std::uint64_t me[] = {doc.client_id()};
const auto update = awareness.encode_update(me);
ycpp::Encoder frame;
ycpp::write_awareness_message(frame, *update);   // type 1 + length-prefixed update
// send_frame(frame.bytes());

// On disconnect: an undefined state removes ours, and peers see us leave.
awareness.set_local_state(ycpp::Any{}, /*now_ms=*/20);

The other calls:

Call What it does
apply_update(update, origin, now_ms) Reads a peer's message. origin is handed to observers as it is.
encode_update(clients) Encodes the entries of clients. Fails for a client it never heard of.
remove_states(clients, origin, now_ms) Drops clients at once, as a server does when a connection closes.
observe(fn, context) Calls fn(context, kind, changes, origin) after each change. Returns an id for unobserve.
modify_awareness_update(update, transform, context) Rewrites every state in a message, keeping the framing.
is_awareness_disconnect_message(message) True for a message that only removes one client's state.

Observers get two kinds of call, as in y-protocols:

  • AwarenessKind::change: a state appeared, went away, or changed value.
  • AwarenessKind::update: any entry was accepted, even with the same value. Use this one to forward messages.

AwarenessChanges lists the added, updated and removed clients.

A peer can never remove your local state. If a message tries, your awareness bumps its own clock instead, so the next message you send puts your state back.

Encoding

An awareness update is:

  1. a varuint: the number of entries;
  2. for each entry: the client id (varuint), the clock (varuint) and the state as a JSON string.

The JSON string null means "this client has no state any more". Over y-websocket the update is wrapped as message type 1, then the update as a length-prefixed byte string. That is what write_awareness_message writes.

Talking to Yjs, y-websocket and pycrdt

ycpp reads and writes Yjs 13 updates. The differential tests replay sessions recorded with real Yjs and require the same bytes. In practice:

  • Yjs in a browser. Send the bytes of on_update and apply what Yjs sends. Yjs's Y.applyUpdate and Y.encodeStateAsUpdate are the counterparts.
  • y-websocket. Use the framed loop above. The server sends its step 1 when you connect; your handle_message answers it. The server also forwards awareness frames, which you route to your Awareness.
  • pycrdt. pycrdt's handle_sync_message takes and returns the unframed shape, like ycpp's handle_sync_message. Doc.get_update() and Doc.apply_update() are plain v1 updates both ways. The ycpp Python binding is itself pycrdt-compatible.

Byte-for-byte equality holds with Yjs. With Yrs and pycrdt, some bytes differ while the meaning is the same: Yrs writes client lists in ascending order and numbers as floats. Each side still reads the other's updates.

Malformed input

Every byte string from the wire is treated as untrusted. That covers updates (v1 and v2), state vectors, sync messages, awareness messages, snapshots and relative positions.

The guarantee:

  • Malformed input returns an Error. It never crashes and never throws.
  • A malformed update changes nothing. ycpp checks the whole update before it integrates any struct, so it never stops halfway with half the update applied.
  • write_sync_step2 with a malformed state vector writes nothing. read_sync_message leaves the reply empty when it fails.

The errors (<ycpp/error.hpp>):

Error Meaning
truncated The bytes end too early.
malformed The bytes do not follow the format: a bad tag, a count larger than the input, invalid UTF-8, a clock past 32 bits.
unsupported The call cannot be done: a handle whose document is gone, or restoring a snapshot from a document that collects garbage.
too_deep A local value is nested deeper than max_any_depth, so peers would refuse it.
clock_exhausted The local client's 32-bit clock space is full; the write is refused.

How this is checked, and what the limits are (nesting depth, decoding cost), is in embedded.md.

Note that an update which decodes fine but depends on missing structs is not an error. It is accepted, and its unready part waits in pending.

See also