Skip to content

Latest commit

 

History

History
298 lines (213 loc) · 12.2 KB

snapshots.md

File metadata and controls

298 lines (213 loc) · 12.2 KB

Snapshots and positions

This page covers two ways to name a place in a document that keeps changing:

  • a snapshot names a moment in its history, so you can read the document as it was then, or see what changed between two moments;
  • a relative position names a spot in a text or an array, so a cursor stays on the right character while other people type.

Both are small values. Both can be encoded and sent to peers, because every replica of a document shares the same item ids.

Snapshots

A snapshot is two tables:

  • a state vector (sv): how far each client had got, as a next clock per client;
  • a delete set (ds): which ranges of items were deleted at that moment.

It holds no copy of the content. The content is still in the document, so a snapshot is cheap to take and to keep.

A snapshot is a cut through history

An item was visible at a snapshot when both of these hold:

  1. its clock is below the snapshot's state vector entry for its client (it existed then);
  2. its id is not in the snapshot's delete set (it was not deleted yet).

is_visible(item, &snapshot) is that test. It is Yjs's isVisible.

Garbage collection must be off

Reading the past needs the past content. A document with garbage collection on throws deleted content away when a transaction ends. After that, a snapshot from before the deletion has nothing to show.

So a document you want to read history from must be built with gc = false:

ycpp::Doc doc(/*client_id=*/1, /*gc=*/false);

What happens with gc on:

  • create_doc_from_snapshot refuses with Error::unsupported.
  • TextRef::to_delta with snapshots does not refuse. It simply cannot show removed text that was thrown away. Do not rely on it with gc on.

Taking, encoding and comparing snapshots works with gc on. Only reading old content needs gc off.

Every peer that wants to read history needs gc off. A peer with gc on still syncs fine with peers that have it off.

Taking and encoding a snapshot

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

ycpp::Doc doc(1, /*gc=*/false);
(void)doc.text("t").insert(0, "abcd");

const ycpp::Snapshot snapshot = doc.snapshot();

// To bytes and back, in Yjs's encodeSnapshot format.
const std::vector<ycpp::byte> bytes = ycpp::encode_snapshot(snapshot);
const std::expected<ycpp::Snapshot, ycpp::Error> decoded = ycpp::decode_snapshot(bytes);
// decoded.has_value() && ycpp::equal_snapshots(*decoded, snapshot)

The functions, all in <ycpp/snapshot.hpp>:

Function What it does Yjs name
Doc::snapshot() The document's state vector and delete set right now. snapshot(doc)
empty_snapshot() A snapshot with no clients and no deletions. emptySnapshot
equal_snapshots(a, b) Same clocks and same delete ranges. equalSnapshots
encode_snapshot(s) / encode_snapshot_v2(s) The v1 or v2 bytes. encodeSnapshot / encodeSnapshotV2
decode_snapshot(bytes) / decode_snapshot_v2(bytes) Back to a Snapshot, or an Error. decodeSnapshot / decodeSnapshotV2
is_visible(item, &s) Was the item visible at s? A null snapshot means "now". isVisible
snapshot_contains_update(s, update) Is everything in update already part of s? snapshotContainsUpdate
create_doc_from_snapshot(origin, s, target) Rebuild origin as it was at s, into target. createDocFromSnapshot

Decoding treats the bytes as untrusted. A truncated or inconsistent snapshot returns an Error.

Reading a document as it was

create_doc_from_snapshot rebuilds the past into a fresh document. You then read that document with the normal API. It works for every type: maps, arrays, text, XML.

This example is adapted from tests/test_snapshot.cpp:

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

ycpp::Doc doc(1, /*gc=*/false);
(void)doc.text("t").insert(0, "world!");
const ycpp::Snapshot snapshot = doc.snapshot();
(void)doc.text("t").insert(0, "hello ");

ycpp::Doc restored(9000);
const std::expected<void, ycpp::Error> result =
    ycpp::create_doc_from_snapshot(doc, snapshot, restored);
// result.has_value()
// restored.text("t").to_string() == "world!"
// doc.text("t").to_string()      == "hello world!"

The restored document has the same content as the one Yjs would rebuild. Its encoded bytes may still differ from Yjs's, because ycpp splits the structs at other boundaries. The meaning is the same.

Reviewing changes: text between two snapshots

TextRef::to_delta(snapshot, prev_snapshot) shows a text as it was at snapshot. Given a prev_snapshot too, it also marks what changed since then:

  • text visible at snapshot but not at prev_snapshot carries ychange: {type: "added"};
  • text visible at prev_snapshot but not at snapshot carries ychange: {type: "removed"};
  • text visible at both is plain;
  • text visible at neither is left out.

This is Yjs's YText.toDelta(snapshot, prevSnapshot). It is what editors use to show tracked changes or a version diff. The removed text comes back with the formatting it had.

to_delta between two snapshots

A null pointer means "now". So:

  • to_delta(&s, nullptr) is the text at s, with no marks;
  • to_delta(nullptr, &s) is the text now, with everything since s marked;
  • to_delta(nullptr, nullptr) is the same as to_delta().

This example is Yjs's own testSnapshot, ported in tests/test_text_snapshot.cpp:

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

ycpp::Doc doc(1, /*gc=*/false);
ycpp::TextRef text = doc.text("t");
(void)text.insert(0, "abcd");
const ycpp::Snapshot first = doc.snapshot();
(void)text.insert(1, "x");     // "axbcd"
text.erase(2, 1);              // remove "b": "axcd"
const ycpp::Snapshot second = doc.snapshot();

const std::vector<ycpp::Any> delta = text.to_delta(&second, &first);
// [{"insert":"a"},
//  {"insert":"x","attributes":{"ychange":{"type":"added"}}},
//  {"insert":"b","attributes":{"ychange":{"type":"removed"}}},
//  {"insert":"cd"}]

ycpp::to_json(ycpp::Any{...}) renders a delta operation as JSON when you want to print it.

Custom marks

By default the mark is {type: "added"} or {type: "removed"}. Yjs lets the caller build the mark instead, usually to add who made the change. Pass a function as the third argument. It gets the mark type ("added" or "removed") and the id of the first item of the run:

const auto mark = [](std::string_view type, ycpp::ID id) {
  ycpp::AnyMap value;
  value.entries.emplace_back("type", ycpp::Any{type});
  value.entries.emplace_back("user", ycpp::Any{static_cast<std::int64_t>(id.client)});
  return ycpp::Any{std::move(value)};
};
const std::vector<ycpp::Any> delta = text.to_delta(&second, &first, mark);
// ..."ychange":{"type":"removed","user":1}...

The client id tells you who wrote an added run. For a removed run, it is who wrote the text, not who deleted it. A delete set does not record who deleted. Yjs keeps that in a separate PermanentUserData structure, which ycpp does not have.

Runs instead of a delta

TextRef::runs(snapshot, prev_snapshot) walks the same way and returns one TextRun per operation. A run keeps more than a delta does:

  • text: the characters (or insert for an embed);
  • attributes: the formatting, ychange included;
  • id: the id of the run's first item;
  • type and type_ref: the item of an embedded shared type, if the run is one.

The id is what you need to tie a run back to a place in your own UI.

Things to know

  • The call is not const. A snapshot can end in the middle of a stored struct, so the walk splits structs first, inside a transaction. That transaction merges them back when it ends. The document ends up encoded exactly as before, and no update or event is produced.
  • Snapshots from another document read as empty. Their clocks name clients this document never saw. Snapshots from another replica of the same document work fine.
  • Python does not expose this yet. The Python Text has diff() (the current delta) but no snapshot arguments.

Relative positions

A plain index breaks as soon as someone else edits. If a peer inserts two characters before your cursor, index 2 now points at a different character.

A relative position fixes that. It names the item the cursor sits next to, by id. Edits elsewhere move the item around, but the id stays the same, so the cursor stays with it.

A relative position sticks to an item

The assoc value says which neighbour the position sticks to:

  • assoc >= 0 (the default) sticks to the character after the position;
  • assoc < 0 sticks to the character before it.

It matters when someone types exactly at the cursor. With assoc = 0 the new text lands before the cursor, which is pushed right. With assoc = -1 the cursor stays before the new text.

At the very start or end of a list there may be no character on that side. The position then names the type itself (tname for a root, type for a nested type).

Making and resolving one

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

ycpp::Doc doc(1);
ycpp::TextRef text = doc.text("t");
(void)text.insert(0, "abcde");

const std::optional<ycpp::RelativePosition> cursor = text.sticky_index(2, /*assoc=*/0);

(void)text.insert(0, "XY");      // or a peer's update that does the same

const std::optional<ycpp::AbsolutePosition> now = doc.absolute_position(*cursor);
// now->index == 4

The calls:

Call What it does Yjs name
TextRef::sticky_index(index, assoc) A position in a text. createRelativePositionFromTypeIndex
ArrayRef::sticky_index(index, assoc) A position in an array. same
Doc::relative_position(parent, name, index, assoc) The same, for a list named by parent item or root name. same
Doc::absolute_position(position, follow_undone) The index the position points at now. createAbsolutePositionFromRelativePosition
encode_relative_position(p) / decode_relative_position(bytes) The Yjs binary form. encodeRelativePosition / decodeRelativePosition
relative_position_to_json(p) / relative_position_from_json(json) The Yjs JSON form. relativePositionToJSON / createRelativePositionFromJSON

absolute_position returns an AbsolutePosition:

  • index: the current position, in UTF-16 code units for text, elements for an array;
  • parent or name: which list it is in;
  • assoc: copied from the relative position.

It returns std::nullopt when this document does not have the item yet. That happens when a peer sends you its cursor before the update that created the text under it. Try again after the update.

If the character a position sticks to is deleted, the position collapses to where that character was. With follow_undone = true (the default), a character that was deleted and then brought back by undo is followed to its restored copy.

Sharing cursors with peers

Encode the position and send it, usually inside your awareness state. The binary and JSON forms are the ones Yjs writes, so a Yjs editor can read a cursor that ycpp made, and the other way round.

const std::vector<ycpp::byte> wire = ycpp::encode_relative_position(*cursor);
// ... on the other peer:
const std::optional<ycpp::RelativePosition> theirs = ycpp::decode_relative_position(wire);
if (theirs) {
  const auto where = doc.absolute_position(*theirs);
}

Decoding treats its input as untrusted and returns std::nullopt for bytes or JSON it cannot read.

Positions compare with ==. Two positions made at the same place with the same assoc are equal.

Absolute positions

An absolute position is an index, valid only for one document at one moment. Use it to draw the cursor. Keep the relative position to remember where the cursor is. Recompute the absolute one after every change you apply.

See also