Skip to content

Latest commit

 

History

History
209 lines (154 loc) · 8.18 KB

getting-started.md

File metadata and controls

209 lines (154 loc) · 8.18 KB

Getting started

ycpp is a CRDT library in C++23. It lets several copies of one document be edited at the same time, on different machines, and always brings them back to the same state.

It speaks the Yjs format. An update written by ycpp can be read by Yjs in a browser, by Yrs, by pycrdt or by a y-websocket server, and the other way round. If you know Yjs, most names map directly: Y.Doc is ycpp::Doc, doc.getMap("x") is doc.map("x"), Y.applyUpdate is doc.apply_update.

It is built for desktops and for microcontrollers:

  • No exceptions, no RTTI, no threads, no iostreams. Errors come back as std::expected.
  • Memory comes from a std::pmr::memory_resource you pass in, so a board can use a pool.
  • Every update is treated as untrusted input. A malformed update is refused as a whole and leaves the document untouched.

Build it

ycpp uses Meson (1.5 or newer) and a C++23 compiler.

meson setup builddir
ninja -C builddir
meson test -C builddir

It builds a static library by default. Its two dependencies, dragonbox and fast_float, are fetched as Meson wraps. They format and parse floating point numbers without pulling in the heavy parts of the standard library.

Use it as a subproject

Put a wrap file in your project's subprojects/ directory, for example subprojects/ycpp.wrap:

[wrap-git]
directory = ycpp
url = https://github.com/PRISM-GUI/ycpp.git
revision = main
depth = 1

[provide]
dependency_names = ycpp

Then ask for the dependency in your meson.build:

ycpp_dep = dependency('ycpp')
executable('app', 'main.cpp', dependencies: ycpp_dep)

Pin revision to a commit for reproducible builds. ycpp brings its own wraps for dragonbox and fast_float in its subprojects/ directory. If your build does not find them, copy them into yours with meson wrap promote.

When ycpp is a subproject, it builds the library and nothing else: no tests, no fuzzer, no benchmarks.

Options you may set

Pass them with -D to meson setup, or as default_options of the subproject. As a subproject, prefix them with ycpp: (for example -Dycpp:undo=disabled).

Option Default What it does
array enabled The Array type.
text enabled The Text type, with formatting. A map-only build can turn it off.
xml auto The xml types. They need text and array; auto follows them.
subdoc enabled Subdocuments (a document stored inside another one).
undo enabled The UndoManager. Off, the library pays nothing for it.
observe_deep enabled Deep observers (observe_deep), as Yjs's observeDeep.
max_any_depth 32 How deeply nested a value may be. Deeper values are refused, both when decoding and when writing.
simd none Vectorised UTF-8 checks: none, sse4.2, avx2 or native. Keep none on a board.

A type turned off is not lost. Its items are still stored and relayed unchanged to other peers. You only lose the functions that read and write it.

The configuration you built with is in the generated header <ycpp/config.hpp>. It defines YCPP_FEATURE_TEXT, YCPP_FEATURE_ARRAY, YCPP_FEATURE_XML, YCPP_FEATURE_SUBDOC, YCPP_FEATURE_UNDO and YCPP_FEATURE_DEEP_OBSERVE to 0 or 1.

The main objects

The main objects: a Doc holds root types, a write becomes a transaction, the transaction emits events and an update

  • Doc: one copy (a replica) of a document. It holds every item ever written, each named by a client id and a clock. You give each replica its own client id.
  • Root types: the named top-level values of a document. doc.map("settings") returns the root map called settings, creating it on first use. Every peer that asks for the same name gets the same type.
  • Handles: MapRef, ArrayRef, TextRef and the xml handles. They are cheap to copy. A handle follows its Doc when the Doc is moved. Once the Doc is destroyed, the handle is inert: every call does nothing.
  • Transactions: a group of changes that becomes one update and one batch of events. Each write is its own transaction, unless you group several with doc.transact(). See Events and transactions.
  • Updates: bytes that describe a change. on_update hands you one per transaction. You send it to the peers however you like, and they call apply_update with it.

Your first program

Two documents, Alice and Bob. Alice writes to a map. Every update she emits is applied to Bob.

#include <cstdio>
#include <span>

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

int main() {
  ycpp::Doc alice(1);  // client id 1
  ycpp::Doc bob(2);    // client id 2

  // A plain function pointer and a context pointer: no std::function, so no allocation.
  // A capture-less lambda converts to the function pointer.
  ycpp::Connection link = alice.on_update(
      [](void* context, std::span<const ycpp::byte> update) {
        auto* peer = static_cast<ycpp::Doc*>(context);
        (void)peer->apply_update(update);
      },
      &bob);

  ycpp::MapRef settings = alice.map("settings");
  (void)settings.set("gain", ycpp::Any{0.5});
  (void)settings.set("name", ycpp::Any{"mic"});

  std::printf("%s\n", bob.to_json("settings").c_str());  // {"gain":0.5,"name":"mic"}

  link.disconnect();
}

What happens, step by step:

  1. settings.set("gain", ...) is a write. It opens a transaction, adds one item, and closes it.
  2. Closing the transaction encodes what changed as an update.
  3. on_update calls our function with those bytes.
  4. Bob applies them. His root map settings now holds the same key.

set returns std::expected<void, Error>. It refuses a value that peers could not read back: one nested deeper than max_any_depth, or a string that is not valid UTF-8.

Concurrent edits converge

Now both edit while they are not connected, then exchange what the other is missing.

#include <cstdio>

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

int main() {
  ycpp::Doc alice(1);
  ycpp::Doc bob(2);

  (void)alice.map("settings").set("gain", ycpp::Any{0.5});
  (void)bob.map("settings").set("gain", ycpp::Any{0.8});

  // Each side sends only what the other lacks: the state vector says what a peer already has.
  const auto to_bob = alice.encode_state_as_update(bob.state_vector());
  const auto to_alice = bob.encode_state_as_update(alice.state_vector());
  (void)bob.apply_update(to_bob);
  (void)alice.apply_update(to_alice);

  std::printf("%s\n", alice.to_json("settings").c_str());  // {"gain":0.8}
  std::printf("%s\n", bob.to_json("settings").c_str());    // {"gain":0.8}
}

Two replicas write the same key offline, exchange updates, and end in the same state

Both end with the same value. For two concurrent sets of the same key, the write of the higher client id wins, as in Yjs. The result does not depend on the order updates arrive in, and applying the same update twice changes nothing.

encode_state_as_update() with no argument encodes the whole document. That is what a new peer needs. The sync protocol in Sync does this exchange for you over any transport.

Choosing client ids

Each replica needs a client id that no other replica uses. Two replicas with the same id would write different items under the same name, and the documents would break. Yjs picks a random 32-bit number per session; doing the same is a good default. The id is fixed when the Doc is constructed.

The Doc constructor

explicit Doc(std::uint64_t client_id, bool gc = true,
             std::pmr::memory_resource* memory = std::pmr::new_delete_resource());
  • gc: when true, the content of deleted items is thrown away at the end of each transaction, as Yjs's doc.gc. Turn it off when you need to look at old versions (see Snapshots).
  • memory: where the document allocates. It must outlive the Doc.

A Doc cannot be copied. It can be moved, and handles and observers follow it.

Next