# Collaborative keys

Some data has no single right version: a shared text, a checklist that several people tick, notes edited on a
train. A collaborative key holds the JSON of a [Yjs](https://docs.yjs.dev) document. Every client edits its own
copy, and the copies merge on their own, in whatever order the changes arrive and also after hours offline.
Nothing is accepted or refused change by change, and there is no conflict to resolve.

| | Normal key with server actions (and `base`, see [Conflicts](conflicts.md)) | Collaborative key |
|---|---|---|
| Who decides | The server, call by call: accept, refuse or conflict | Nobody: concurrent edits merge |
| Two people change the same thing | The later call conflicts; a person or a resolver decides | Both changes are kept (text, list items); per map key, one value wins |
| Offline | Calls wait in the queue and may conflict when replayed | Edits merge on reconnect |
| Validation, business rules | Yes, in `handle_action/4` | Only who may read and who may write a document |
| Server code reads the data | From its own records | With `LiveSlice.CRDT.get/3` |
| Good for | Orders, stock, permissions, anything with rules or an audit | Shared text, checklists, notes, settings edited together |
| Cost | One round trip per call | A Yjs document that grows with its history; the y_ex NIF on the server |

Structured business data with rules belongs on normal keys: once a change merged, the server cannot refuse it.

## Client

`live_slice/crdt` binds a store key to a document. Yjs is the app's dependency (`npm install yjs`), passed in as
`Y`, so live_slice itself keeps no runtime dependencies.

```js
import * as Y from "yjs";
import { createStore } from "live_slice";
import { createCollaborativeKey } from "live_slice/crdt";

const store = createStore("notes", { state: { note: { body: "", items: [] }, sync: null } });

const notes = createCollaborativeKey({
  Y,
  store, // or its name
  key: "note", // receives the document's JSON
  doc: "notes:42", // the document's name, or a function of the store's state (see Following the store);
  // the LiveView names the same one (crdt_document/2)
  type: { body: "text", items: "array" }, // "map", "array", "text", or a shape of root types
  statusKey: "sync", // optional: receives {status, writable, unsent}
  // optional: the document was deleted on the server and the local copy replaced (see Deleting a document)
  onReset: ({ generation, previous, discarded, meta, value, unsent, carried, carriedValue, notCarried }) => {},
  // carryOver: false by default; true, or ({ name, generation, previous, meta, value, unsent }) => boolean, puts
  // the copy's unsent changes onto the new document after a delete (see Carrying unsent changes over)
  // optional: a document's local copy has loaded and the key holds it (each document, see Following the store)
  onLoad: ({ name }) => {},
  // persistence: IndexedDB by default (createIndexedDBDocumentStorage), createMemoryDocumentStorage() or null
  // BroadcastChannel: the global one by default, or null to keep tabs apart
  // maxUpdateBytes: the largest update accepted from the server, 16 MiB by default
  // batchMs: how long local changes wait to go out as one push, 50 by default; 0 sends each task's at once
});

notes.update(({ body, items }, Y) => {
  body.insert(0, "Shopping");
  const item = new Y.Map();
  item.set("text", "Milk");
  item.set("done", false);
  items.push([item]);
});
store.getState().note; // { body: "Shopping", items: [{ text: "Milk", done: false }] }

await notes.ready; // the local copy is loaded and the key written
await notes.synced; // the first sync with the server completed
notes.status; // "offline", "waiting", "syncing" or "synced"
notes.name; // the current document's name
notes.loaded; // true once the key holds the current document's local copy
notes.writable; // false once the server said this client may only read
notes.generation; // the generation of the local copy, null until it met a deleted document
notes.unsent; // true while the copy holds changes the server has not acknowledged
notes.unsentSince; // when the oldest of them was made (ms since the epoch), or null
await notes.flush(); // the changes so far are stored locally
await notes.destroy();
```

- **The JSON view.** The key holds the root's JSON (`toJSON()`; a string for a text root, an object with one
  entry per root for a shape), written with `setState`, so as confirmed state: once the local copy is loaded,
  then after every change, at once when `update` returns and in a microtask for changes from elsewhere, so a
  burst of them makes one store update. Subscribers and selectors work on plain JSON. Nested values that did not
  change keep their identity, also the maps of a list when the list shifts, so a selector on one item does not
  fire for another. Treat the value as read-only.
- **Editing.** `update(fn)` runs `fn(root, Y)` in one Yjs transaction; `root` is the root type, or an object of
  root types for a shape. Store JSON values (null, booleans, finite numbers, strings, arrays and plain objects)
  or Yjs types. Yjs throws on functions and class instances; it stores a `Date` or a `BigInt`, which other
  clients and the server may not read back the same way. When `fn` throws, what it changed is reverted and the
  error rethrown. `update` works before `ready` (the stored copy merges in when it loads) and throws after
  `destroy`, inside another `update`, and when the server said this client may only read. `notes.doc` is the
  `Y.Doc` and `notes.root` the root types, for reading or for libraries that need them. Both are replaced when
  the document is deleted on the server (see [Offline, tabs and restarts](#offline-tabs-and-restarts)): read
  them from the binding each time, or again in `onReset`.
- **Shapes.** Prefer a shape of root types over nested types created on demand. Two clients that create the same
  nested type at the same moment each create their own, and one of them wins with its content; root types
  always merge. For the same reason, do not seed a new document with initial content from several clients.
- **Guards.** The key may not be persisted by the store (`persist.keys`) nor mirrored by the bridge: the
  document has its own persistence and sync, and `createCollaborativeKey` throws. One binding per store key at a
  time.
- **Text fields.** There is no editor binding. The demo binds a plain `<textarea>` with a minimal diff
  (`textDiff` and `editText` in `demo/assets/js/notes_store.js`): each input event becomes the one range that
  changed, and a change from elsewhere moves the caret with the text around it. Diff the field against the
  document's text (`binding.root.body.toString()`), not the store key: the key is written only once the local
  copy has loaded, so typing before that would diff against the empty initial text.
- **Status.** `"offline"`: no connection, or the server refused the document for good (until the next
  connection). `"waiting"`: connected, but the LiveView does not name this document for the key yet (its
  `crdt_document/2` named another one or none); the binding syncs once the LiveView names it. `"syncing"`: an
  exchange or a pushed change waits for its answer. `"synced"`: in sync with the server.
- **Batching.** Local changes are not pushed one by one: the first change starts a `batchMs` timer (50 ms by
  default) and the changes made until it fires go out as one push, merged by Yjs (`Y.mergeUpdates`). Typing 20
  characters 10 ms apart makes 4 websocket frames instead of 20. `batchMs: 0` pushes the changes of each task at
  once, the behaviour before this option (a changed default). A waiting batch is pushed at once when the page is
  hidden or left (`visibilitychange` to hidden, `pagehide`, `beforeunload`), when the binding is destroyed and
  when it switches documents. Only the push waits: each change is written to the local copy at once, so text
  typed just before the tab closes is in the copy even if the socket could not send it, is reported as unsent
  on the next load and goes out with the next sync.
- **Unsent changes.** `binding.unsent` (and `unsent` in the status key) is true while the copy holds local
  changes the server has not acknowledged: typed offline, refused, or pushed and not answered yet.
  `binding.unsentSince` is when the oldest of them was made. A change counts as sent once the answer to the push
  that carried it comes back `ok` (and no earlier push of that exchange failed). It survives a reload: each
  stored update records whether it is pending in the same write as the update, so the copy never holds unsent
  changes without saying so, and a reload reports them before any connection. Once the server acknowledged all
  of a copy's changes, the binding marks the stored updates it holds as acknowledged, including those another
  tab stored and this one sent. A read-only client's offline changes stay unsent. There is no count of
  changes or bytes: Yjs merges updates as they are batched, stored and compacted, so such a number would not be
  stable. Use it for an "N notes not sent yet" list, a sign-out warning, or a "kept on this device since 10:42"
  line. A copy stored by an earlier version counts as unsent until its first sync. Each time the server
  acknowledges changes, the stored updates that hold only acknowledged changes are marked as such, also while
  later changes are still on their way, so a reload does not count a change the server has as unsent. An update
  stored together with an unsent one (both made before one write of the local copy, or merged by a compaction)
  stays unsent with it.

### Following the store

A key often holds the document of what the page shows: the notes of the selected record, say. `doc` can then
be a function of the store's state that returns the document's name, or `null` for none:

```js
const notes = createCollaborativeKey({
  Y,
  store: "map",
  key: "notes",
  doc: (state) => (state.selectedId ? `notes:${state.selectedId}` : null),
  type: "text",
  statusKey: "notesSync",
});
```

- **Switching.** The binding evaluates `doc` on every change of the store. When the name changes, it closes
  the previous document (its local changes not stored yet are still stored, under its own name), opens the new
  one and writes an empty document's JSON to the key at once, while the store is still notifying the change
  that renamed it, so the key never holds the previous document's content under the new name: a subscriber of
  the key sees the empty value first. The new document is open before that write, so every listener it
  notifies (those of the key, and those of the name's source that run after the binding's own subscription,
  which the write notifies again) reads the new `binding.name`, `doc` and `root`, and the status key, written
  in the same `setState`, describes the new document. A listener that changes the name again during that write
  leaves the binding on the last name. (A subscriber of the name's source that runs before the binding's own
  subscription still sees the old key and the old `binding.name`; subscribe after creating the binding, or read
  the key in a subscription of its own.) Then it loads the
  new document's local copy (the key gets it once loaded) and syncs it when the page is connected; offline, it
  is edited from the local copy and synced after the reconnect. A name the binding switches back to while its
  previous session still writes (A, then B, then A in one task, or A, none, A) is loaded once those writes are
  stored, so it shows every change and reports the unsent ones. `binding.name` is the current name, and
  `binding.doc`, `binding.root`, `generation`, `status` and `writable` are the current document's (read them
  from the binding each time). `ready` resolves once the first document was loaded, `synced` the first time
  any document synced. `onReset` concerns the current document. A function that throws keeps the current
  document and is reported with `console.error`.
- **Loaded.** `binding.loaded` is false from the switch until the new document's local copy has loaded and
  the key holds it (also while `doc` names none), then true, already for the subscribers of that key write.
  `onLoad({ name })` is called at that moment for every document the binding loads, the first one included
  (before `ready` resolves), and not for a document left before its copy loaded. It is the signal to enable
  a text field or show the document as opened: unlike a subscription of the key, it comes also when the
  copy is empty and the key does not change. A document's first sync with the server shows in `status`
  (`"synced"`), which is the current document's.
- **No document.** While `doc` returns `null`, the key holds an empty document's JSON (`""` for a text, `{}`
  for a map, `[]` for an array, or one of those per root of a shape), `status` is `"offline"`, `binding.root`
  is an empty document that is never stored or synced, and `update` throws.
- **The LiveView must agree.** Its `crdt_document/2` usually names the document from a mirrored key (the
  selection), which the bridge debounces, while a new document's sync would go at once. So before every
  `sync1`, the binding pushes the store's mirrored keys whose debounce is still running (`flushMirror`, below):
  on the same connection, so the LiveView has applied them when the `sync1` arrives. When the LiveView still
  names another document (it looks it up asynchronously, or the client is ahead), the `sync1` is refused with
  `wrong_document` (or `no_document`), the status is `"waiting"`, and the LiveView sends `resync` once its
  `crdt_document/2` names the document after a render, which starts a new exchange (see
  [Sync protocol](#sync-protocol)).

`flushMirror(store, key)` (from `live_slice`) is also there for the app: it pushes a mirrored key at once
instead of when its debounce elapses (every mirrored key of the store without `key`), on the bridges of the
page that mirror it, and returns whether it pushed something. A value the server already holds is not pushed,
and nothing is pushed while the bridge cannot push (the value goes out on the reconnect, as always). Use it
before anything whose server side reads a mirrored key.

## Server

The server side needs the optional dependency `y_ex` (Elixir bindings to the Rust port of Yjs, with precompiled
NIFs for the common platforms) and a `LiveSlice.CRDT` server in the supervision tree:

```elixir
# mix.exs
{:y_ex, "~> 0.13"}

# application.ex
children = [
  # ...
  {LiveSlice.CRDT, name: MyApp.CRDT, persistence: MyApp.NotesPersistence},
  MyAppWeb.Endpoint
]
```

A LiveView declares its collaborative keys, the document each one syncs, and who may read and write it:

```elixir
defmodule MyAppWeb.NoteLive do
  use MyAppWeb, :live_view
  use LiveSlice, store: :notes, collaborative: [note: [server: MyApp.CRDT]]

  def mount(%{"id" => id}, _session, socket) do
    note = MyApp.Notes.get!(id)
    user = socket.assigns.current_user
    {:ok,
     assign(socket,
       note: note,
       can_read?: MyApp.Notes.member?(note, user),
       can_edit?: MyApp.Notes.editor?(note, user)
     )}
  end

  # The document of the key in this LiveView. A client that names another one is refused.
  @impl LiveSlice
  def crdt_document(:note, socket), do: "notes:#{socket.assigns.note.id}"

  # Called on every sync, every update the client sends (:write) and before every change is pushed to the
  # client (:read): keep it cheap.
  @impl LiveSlice
  def authorize_crdt(_doc_name, :read, socket), do: socket.assigns.can_read?
  def authorize_crdt(_doc_name, :write, socket), do: socket.assigns.can_edit?

  # Access revoked while the page is open: the client is told at once instead of at the next change.
  def handle_info({:membership_removed, _note_id}, socket) do
    {:noreply, socket |> assign(can_read?: false, can_edit?: false) |> LiveSlice.CRDT.reauthorize()}
  end

  def render(assigns) do
    ~H"""
    <LiveSlice.bridge id="notes-store" module={__MODULE__} />
    <div id="note" phx-hook="Note" phx-update="ignore" data-doc={"notes:#{@note.id}"}></div>
    """
  end
end
```

Both callbacks are required with `:collaborative`. Access is checked again before every change of the document
is pushed to a client: a LiveView whose `crdt_document/2` names another document now, or whose client may no
longer read, leaves the document and tells its client (step `"refused"`, see [Sync protocol](#sync-protocol)), so
a revoked client receives nothing more. `LiveSlice.CRDT.reauthorize/1` runs the same checks at once, as in the
`handle_info/2` above. The bridge lists the keys in `data-channels`, and only a
bridge that lists a key syncs it, one per store key on a page. A key alone (`collaborative: [:note]`) uses the
server named `LiveSlice.CRDT`. Without `y_ex`, `:collaborative` raises at compile time and `LiveSlice.CRDT`
raises when started; an app that declares no collaborative key compiles and behaves as before.

`LiveSlice.CRDT` keeps one process per document, started on demand and registered by name in a local
`Registry`. It is built on y_ex's `Yex.DocServer` (the process that owns the `Yex.Doc`) and the sync steps of
`Yex.Sync`; it does not use `Yex.Sync.SharedDoc`, which stops as soon as its last observer leaves, cannot take
timer messages and applies client messages with casts that swallow errors. The document process applies the
updates of the LiveViews that synced, sends each change to the others, saves the document and stops when idle.
Options:

- `:persistence`: a module implementing `LiveSlice.CRDT.Persistence` (`load(doc_name, state)` returning
  `{:ok, snapshot, generation}` or `{:ok, nil}`, `save(doc_name, snapshot, generation, state)`, optional
  `init(opts)`), or `{module, opts}`. A document is loaded right after its process starts: a slow load holds up
  the calls to that document only (they wait for it, at most `:load_timeout`), never the start of other
  documents. A failed load is logged and stops the process before it answers any call (clients are told it is
  unavailable and try again), so a partial copy never overwrites a stored one. The whole document is saved as
  one Yjs update `:save_delay` after the first change of a burst (2 seconds) and when the process stops; a
  failed save is logged and tried again. The generation is what makes a delete stick (see
  [Deleting a document](#deleting-a-document)): store it with the snapshot and keep the record of a deleted
  document. A persistence written before generations (`save(doc_name, snapshot, state)`, `load` returning
  `{:ok, snapshot}`) still works, without `delete/2`. The default, `LiveSlice.CRDT.MemoryPersistence`, keeps
  documents and generations in an ETS table: for demos only.
- `:idle_timeout`: how long a document process stays up without a subscribed LiveView, 30 seconds.
- `:load_timeout`: how long a call waits for a document that is loading from the persistence, 5 seconds,
  whether it started the document or found it loading. A call that waits longer gives up having sent the
  document nothing (the load goes on, and later calls find the loaded document); a client's sync is answered
  `"unavailable"` and tried again.
- `:max_update_bytes` (1 MB), `:max_document_bytes` (10 MB, an estimate checked exactly when it is over) and
  `:rate_limit` (`{200, 10_000}`: updates per key and LiveView per 10 seconds, whatever document the key syncs;
  sync2s and background deliveries count in the same window). What goes over is refused; the client keeps the
  change and sends it with its next sync (after the rest of the window, for `rate_limited`).
  What the server lacks after a sync (`sync2`, see [Sync protocol](#sync-protocol)) may be as large as
  `:max_document_bytes`.

Server code reads a document with `get/3` and changes it with `change/4`, which every subscribed client
receives. Both take the root type as the client declares it (`:map`, `:array`, `:text`, or a keyword list for a
shape); numbers come back as floats, as Yjs keeps them. Both, and `delete/2`, start the document when it is not
running and return `{:error, :load_timeout}` when its load takes longer than `:load_timeout`, or
`{:error, {:load_failed, reason}}` when it could not be loaded: the persistence returned `{:error, reason}`, or
the document process stopped before it was loaded, for `reason` (it crashed, or it stopped twice in a row; a
process that stops once, such as one deleted during its load, is started again). Nothing was read, changed or
deleted then. They return `{:error, :timeout}` when the document does not answer within 5 seconds (it is busy,
for example saving to a slow persistence); the request may still run afterwards, so a change or a delete that
timed out may be applied. `change/4` returns `{:error, exception}` when its function raises (what it changed before is kept):

```elixir
{:ok, %{"body" => body, "items" => items}} =
  LiveSlice.CRDT.get(MyApp.CRDT, "notes:42", body: :text, items: :array)

LiveSlice.CRDT.change(MyApp.CRDT, "notes:42", [body: :text, items: :array], fn %{items: items} ->
  Yex.Array.push(items, Yex.MapPrelim.from(%{"text" => "Added by the server", "done" => false}))
end)
```

### Delivering offline changes in the background

A binding syncs only the document it has open, so text typed offline into a document that is not opened again
would stay in the browser. `listUnsentDocuments` lists the local copies that hold unsent changes, and
`deliverUnsentDocuments` sends them over the bridge that carries the key, without a binding or any UI:

```js
import * as Y from "yjs";
import { deliverUnsentDocuments, listUnsentDocuments } from "live_slice/crdt";

await listUnsentDocuments(); // [{ name: "notes:7", since: 1764612345678 }, ...], the oldest first

// For example once the store is connected again (store.onConnection, see Connection state):
const { delivered, reset, failed, skipped } = await deliverUnsentDocuments({
  Y,
  store: "notes",
  key: "note", // a collaborative key the LiveView on the page declares
  filter: (name) => name.startsWith("notes:"),
  type: { body: "text", items: "array" }, // optional: gives each reset copy's JSON as `value`
  // persistence: the document storage, IndexedDB by default; limit: 20 per call; timeout: 5000 ms
  // carryOver: as the binding's option (false by default; it needs type)
});
```

- One document after the other, the oldest first, at most `limit` per call. A copy the LiveView refuses for good
  (`"not_deliverable"`, `"forbidden"`) is reported in `failed` but does not count against `limit`, so copies
  the user can no longer write never hold the newer ones back. Documents a binding of the page has open are left
  to it (`skipped`). Without a connected bridge for the key within `timeout`, each document is reported in
  `failed` with `"not_connected"` and nothing is sent.
- The LiveView must accept it: the server refuses by default. Its `crdt_document/2` names one document per key,
  so a background delivery is a separate step, accepted only when the LiveView implements
  `accept_crdt_delivery/3` for that key and document and `authorize_crdt/3` allows both `:read` and `:write`:

  ```elixir
  @impl LiveSlice
  def accept_crdt_delivery(:note, "notes:" <> id, socket), do: MyApp.Notes.member?(socket.assigns.user, id)
  def accept_crdt_delivery(_key, _doc_name, _socket), do: false
  ```

- The wire: `{step: "deliver1", doc, sv, generation}` is answered `{ok: true, sv, generation}` (the server's
  state vector, without subscribing the client to the document), then `{step: "deliver2", doc, update}` carries
  what the server lacks, accepted once per `deliver1`, bounded by `:max_document_bytes`, and refused (`"reset"`)
  when the document was deleted in between. Both count in the key's `:rate_limit` window, with the binding's
  updates: a `deliver1` as one update (it is refused before it loads the document), a `deliver2` by its size,
  like a `sync2`. Refusals are
  `"not_deliverable"` (not accepted), `"forbidden"`, `"not_synced"` and the usual ones.
- Generations hold: a copy of a deleted document is answered `{ok: false, reason: "reset", generation, meta}`,
  is never delivered, and the local copy takes the new generation and is dropped; it is reported in `reset`
  as `{name, generation, meta, value}`. With `carryOver`, its unsent changes go onto the new generation in the
  same write, the copy is delivered right after (its name is then in `delivered` too), and the entry also has
  `carried`, `carriedValue` and `notCarried` (see [Carrying unsent changes over](#carrying-unsent-changes-over)).
  When a tab or another call (another tab running `deliverUnsentDocuments`) switched the copy first, this call
  carries nothing again and does not deliver: `carried` and `carriedValue` then say what that one carried of
  this copy's unsent changes, read from the storage, so both calls report the text kept. A copy whose unsent
  changes only removed content has `notCarried: "nothing"`.
- What is delivered is marked as acknowledged in the storage, so the next list leaves it out and a binding that
  opens the document later reports it as sent. A document refused or not answered stays unsent for the next
  call. IndexedDB's listing needs `indexedDB.databases()` (current Chrome, Firefox and Safari); it opens each
  document's database in turn, closes the ones it opened, and reports a database it cannot read with
  `console.error` and leaves it out instead of failing the whole listing. A custom storage needs `listPending`.
- Nothing is dropped for you: a copy refused for good stays unsent, listed and tried again by each call, until
  the application decides. `dropUnsentDocument(name, { persistence, Y, type })` drops a local copy (every change
  stored for it, unsent ones included; its generation stays) and resolves with `{name, generation, value}`,
  `value` being the copy's JSON when `Y` and `type` are given, to show or keep it. It rejects while a binding of
  the page has the document open:

  ```js
  for (const { name, reason } of failed.filter(({ reason }) => reason === "forbidden")) {
    const { value } = await dropUnsentDocument(name, { Y, type: { body: "text", items: "array" } });
    keepAsDraft(name, value); // the app decides what the person sees
  }
  ```

### Deleting a document

`LiveSlice.CRDT.delete(MyApp.CRDT, "notes:42")` drops a document's content: the document starts over, empty,
under a new generation that is saved at once, and returns `{:ok, generation}`, that new generation (for example
to broadcast it with the name of who deleted). Deleting is a server call that the application makes and
authorizes; nothing a client sends can delete a document. Without generations, a client that still holds a copy
would send the deleted content back on its next sync, as it restores a document the server lost. With them:

- Every document has a generation, `nil` until its first delete, then a string such as
  `"1764612345678-3fa94c2b1d07"` whose number grows with every delete. Clients keep the generation of their local
  copy and send it with each `sync1`.
- A client that syncs the document when it is deleted is told at once, and a client that held a copy while away
  is told when it syncs again: it discards its copy (in memory and in IndexedDB), the changes it had not sent
  yet included, takes the new generation and syncs the new document. None of the old content reaches the
  server. See [Offline, tabs and restarts](#offline-tabs-and-restarts) for what the application sees.
- Only a delete makes a generation, and the server only discards a client's copy when it knows one: the
  persistence has the deleted document's record, or the document process deleted it. A document whose
  generation is `nil` (never deleted, or one the persistence has no record of: a new document, or
  `MemoryPersistence` after a restart) merges every copy as before, whatever generation it carries, so the first
  client that syncs restores it. The server never takes a generation from a client. So a delete is remembered
  exactly as long as the persistence keeps the record of the deleted document with its generation:
  `MemoryPersistence` forgets deletes when the server stops, and a deleted document then comes back from the
  first client that still holds a copy. A persistence that deletes the row forgets the delete in the same way.
- `delete/2` returns `{:error, :generations_not_supported}` when the persistence has neither `save/4` nor
  `save/5`, and `{:error, {:save_failed, reason}}` when the delete could not be saved; the document is left as it
  was. Like `get/3` and `change/4` it also returns `{:error, :load_timeout}`, `{:error, {:load_failed, reason}}`
  (nothing was deleted) and `{:error, :timeout}` (the delete may still happen), see [Server](#server).
  `delete(doc_name, meta: ...)` deletes on the default server as `delete/3` does.

`delete/3` does the same, returns the same `{:ok, generation}`, and takes metadata about the delete, such as who
made it:

```elixir
{:ok, generation} =
  LiveSlice.CRDT.delete(MyApp.CRDT, "notes:42", meta: %{by: user.name, at: System.os_time(:millisecond)})
```

- `:meta` is a small JSON object (at most 2048 bytes of JSON; anything else raises `ArgumentError`). It travels
  in the reset notice to every client that syncs the document and reaches `onReset` as `meta`, with string
  keys. It is stored with the generation, so a client that comes back later gets it too, when the persistence
  implements `save/5` (`MemoryPersistence` does): `save(doc_name, snapshot, generation, meta, state)`, and
  `load/2` returns `{:ok, snapshot, generation, meta}`. With `save/4` only, the clients told at once get it and
  later ones get `nil`.

### Carrying unsent changes over

By default a delete wins over everything: a client that held changes the server never acknowledged (typed
offline, or on their way when the delete happened) drops them with its copy, and `onReset` hands them to the
application (`value`, `unsent`), which decides what the person sees, for example a "Put it back" button. The
`carryOver` option of the collaborative key does that instead: it puts those changes onto the new generation
automatically.

```js
createCollaborativeKey({
  // ...
  carryOver: true, // or a function: ({ name, generation, previous, meta, value, unsent }) => boolean
  onReset: ({ unsent, carried, carriedValue, notCarried }) => {
    if (carried) showNotice(`Your unsent changes were kept: ${carriedValue}`);
    else if (unsent && notCarried !== "nothing") offerToPutBack(value); // not kept (see notCarried below)
  },
});
```

**It can bring back content someone removed on purpose**: an edit made offline that raced a deliberate clear
reappears after the clear. That is why it is off by default. Turn it on where losing an offline edit is worse
than undoing part of a clear, and use the function form to refuse some deletes, for example by who made them or
why (`meta`, the metadata of `LiveSlice.CRDT.delete/3`): `carryOver: ({ meta }) => meta?.reason !== "retention"`.

- **What is carried.** Only what the copy's unacknowledged changes inserted and is still in it, never the whole
  previous document: a clear by someone else stays a clear for everything the server had received, also the
  copy's own earlier changes. By root type: the characters of a text, the items of an array, the entries of a
  map (nested Yjs types are rebuilt as new ones; a text loses its formatting). Not deletions, and not changes
  inside an item or an entry the server already had (that item went with the delete). Changes count as
  acknowledged as for `unsent` (see Unsent changes), so after a reload too.
- **How it is placed.** Yjs cannot apply the old changes to the new generation: they refer to items and clocks
  of the deleted document. So the carried content is written again as new changes: appended at the end of each
  root as the local copy of the new generation holds it, by a client id of its own; a map entry the new
  generation already has is left as it is. On a reconnect the reset usually comes before the new generation's
  content, and Yjs orders content others added since the delete before or after the carried content (by client
  id), not always after it. Placing it after would need the server to send the new content with the reset; this
  is not done.
- **`onReset` still fires**, with `carried` (true when some of this copy's unsent changes are on the new
  generation, carried by this tab or by another one) and `carriedValue` (what, in the key's shape: a string for
  a text, the items for an array, an object of the entries for a map, one of those per root for a shape; null
  when nothing). Without `carryOver` they are `false` and `null`. `value` and `unsent` keep their meaning. A tab
  that finds the copy switched by another tab or a background delivery reads what was carried from the storage
  (the record below), also when its own function refused. A tab without a local storage (`persistence: null`),
  or with one that does not pass what it holds (see the last item), cannot read that record: it reports only
  what it carried itself, its own changes.
- **Why nothing was carried.** `onReset` also gets `notCarried`: null when `carried` is true, otherwise why none
  of this copy's unsent changes is on the new generation, the first of these that applies:
  - `"off"`: no `carryOver`.
  - `"readonly"`: the client may only read.
  - `"refused"`: the function returned anything but `true`.
  - `"failed"`: the function threw, or the carry-over failed (both reported with `console.error`); for a
    background delivery also a storage that does not pass what it holds (see the last item), which cannot take
    part.
  - `"unknown"`: this tab carried nothing and cannot tell whether another one did. Without a storage, the
    unsent changes were made in another tab (that tab carries them); or its storage does not pass what it
    holds; or, for a background delivery, a tab that recorded no carry-over (its `carryOver` off or refused)
    switched the copy first, so only a tab still holding the changes can carry them.
  - `"nothing"`: nothing needed carrying, so nothing was lost: the unsent changes inserted nothing that is still
    in the copy (they only removed content, removed again what they inserted, or there were none), the server
    had acknowledged what they inserted, or, for a map, they set only keys the new generation already has.

  So `unsent && !carried && notCarried !== "nothing"` means content typed here is not on the new generation
  when this tab handles the reset (with `"unknown"`, or `"refused"` while another tab's function accepts,
  another tab may still keep it, see the function form below): `value`, the whole copy as it was, is there to
  show or put back. `carried` stays true when only part of it was carried (a tab without a storage that carried
  its own changes but not those another tab made).
- **Once, across tabs, reloads and background delivery.** The carried changes are stored in the same storage
  transaction that switches the stored copy to the new generation (`setGeneration`, which also records the ids
  of the changes it looked at and carried). The tab, or `deliverUnsentDocuments` call, that switches the stored
  copy carries every unsent change it holds, those other tabs stored included; a tab that finds it switched
  already carries only its own unsent changes that record does not name (typically none). A reload before
  that transaction finds the old copy and carries it at its next reset; a reload after it finds the new
  generation holding the carried changes, unsent, and sends them once. Without a local storage (`persistence:
  null`) each tab carries only the changes it made itself.
- **The function form** is called at most once per reset, from inside the storage transaction when there is a
  local storage (with `meta` read from the stored copy when the reset came from another tab): keep it
  synchronous and quick. A function that throws or returns anything but `true` carries nothing. Each tab asks
  its own, and a refusal holds only for the tab that refused: when one tab's function refuses and another's
  accepts, the changes the accepting tab holds are kept, whichever meets the delete first. If the accepting tab
  is first, the refusing one reports them carried. If the refusing tab is first, it switches the stored copy
  without recording anything and reports `carried: false`; the accepting tab then carries what it still holds
  when it meets the delete (from the server, the storage or another tab).
- A read-only client carries nothing: its changes would never reach the server.
- **The server needs nothing.** Carried changes are ordinary updates of the new generation, made on the client:
  `accept_crdt_delivery/3`, `authorize_crdt/3` and the persistence see them as any other update, and no update
  of an older generation is ever accepted. A server that refuses them (`forbidden`, `document_too_large`, ...)
  refuses them as any other change: they stay unsent, reported by `unsent`, `listUnsentDocuments` and
  `deliverUnsentDocuments`, until a later sync or `dropUnsentDocument`. The server cannot tell carried content
  from new typing.
- `deliverUnsentDocuments({ carryOver })` does the same for copies it finds deleted (it needs `type`).
- A custom document storage takes part through `setGeneration` (see `crdt_storage.js`): `decide` gets what is
  stored as a second argument, and the change may hold `carry` and `append`. One that ignores them still works:
  the carried changes are stored after the switch (a reload in between loses them), and a storage that does not
  pass the second argument cannot tell tabs apart, so only the tab that switches it carries.

## Sync protocol

The binding and the LiveView exchange the `live_slice:crdt` event, `{store, key, doc, step, ...}`, through the
bridge. Yjs updates and state vectors are binary and travel in base64 inside the JSON: a LiveView hook cannot
push a binary frame (Phoenix sends one only for a payload that is a whole `ArrayBuffer`, and LiveView wraps hook
payloads in an object).

1. Whenever the bridge can push (it joined, reconnected, or the browser is back online), the client sends
   `{step: "sync1", sv, generation}` with its state vector and the generation of its copy (`null` for a copy
   that never met a deleted document). The LiveView checks the document name and `:read`, subscribes to the
   document and answers `{ok: true, update, sv, writable, generation}`: the update the client lacks, the
   server's state vector, whether `:write` is allowed, and the server's generation. A copy that holds content
   of another generation than the one the server knows is answered `{ok: false, reason: "reset",
   generation, meta}` instead, without a subscription (see [Deleting a document](#deleting-a-document)).
2. The client applies that update and sends `{step: "sync2", update}` with what the server lacks, if
   anything: the changes it made offline or while the reply was on its way, or a whole document the server
   lost. The LiveView takes one `sync2` per `sync1` and bounds it by `:max_document_bytes` rather than
   `:max_update_bytes`, so a large offline session, a document over 1 MB restored from a client, or a change too
   large for one update (refused with `too_large`, it goes out with the next exchange) still reaches the server.
   It counts against the rate limit by its size, as that many updates of `:max_update_bytes`, and the window
   lets it through as long as it is not used up. The whole document can then travel in one WebSocket frame, in
   base64: an endpoint that sets `:max_frame_size` on its LiveView socket (Phoenix sets no limit by default)
   must allow it, as it already must for the `sync1` reply that sends a whole document to a new client.
3. Afterwards each side sends its changes as they happen: the client as `{step: "update", update}` pushes,
   answered `{ok: true}` or `{ok: false, reason}`, the server as `live_slice:crdt` events with
   `step: "update"`. The server sends `step: "resync"` when the document process died, and the client starts
   over, and `{step: "reset", generation, meta}` when the document was deleted. Before pushing a change or a reset,
   the LiveView checks the document name and `:read` again; when either fails it leaves the document and sends
   `{step: "refused", reason}` instead (`forbidden`, `wrong_document` or `no_document`), and the client reports
   it and waits for the next connection, as after a refused `sync1`, or for `wrong_document` and
   `no_document`, until the LiveView names the document again (below).
4. A key whose `sync1` was refused with `wrong_document` or `no_document`, or whose document the LiveView left
   for one of those reasons, waits for that name (the last one per key). After each render of the LiveView
   (its assigns changed), when `crdt_document/2` gives that name, the LiveView sends `step: "resync"` for it,
   once, and the client starts a new exchange; meanwhile its status is `"waiting"`. Such an exchange counts
   with the three a connection starts on its own, so a LiveView that keeps changing its mind cannot make the
   client loop, and a `resync` that arrives while a `sync1` is on its way is ignored (that `sync1` gets its own
   answer).

Yjs updates are idempotent and commute, so there is no queue and no mutation id: what was not sent while
disconnected, or got no reply, is part of the next exchange, and an update that arrives twice or out of order
changes nothing more. Changes from the server are applied with a remote origin and never sent back. The client
ignores an update from the server that is not valid base64, larger than `maxUpdateBytes`, or that Yjs cannot
read, reports it with `console.error` and starts a new exchange; a refused update or a push without a reply
starts one after a second. A connection starts at most three such exchanges, then waits for the next connection
with the status `"offline"`. An update refused with `rate_limited` carries `retry_after`, the milliseconds left
in the server's window, and the client starts the next exchange then (waiting at least a second and at most a
minute), without counting it among those three. Refusals are reported with `console.error`: `wrong_document`, `no_document` (`crdt_document/2` returned `nil`),
`forbidden` (for an update, the client then becomes read-only), `not_synced` (an update before `sync1`),
`rate_limited`, `too_large`, `document_too_large`, `invalid_update`, `invalid_payload`, `unknown_key`,
`unknown_store` and `unavailable` (the document could not be started: the LiveView already started it once more
if its process stopped while called, and the client starts a new exchange after a second, counted with the
others; `wrong_document` and `no_document` wait for the LiveView's `resync`, as in step 4; every other refused
`sync1` waits for the next connection).

Measured in the demo (headless Chromium, two clients): a keystroke in the shared text is a Yjs update of about
25 bytes, 33 characters in base64 (a third more), in a WebSocket frame of about 205 characters with LiveView's
envelope and the event's fields. The largest update of the run, a checklist item, was 148 bytes, 200 in base64,
373 in its frame. The envelope, not base64, dominates small updates.

## Offline, tabs and restarts

- **Local copy.** Every change is appended to IndexedDB (a database per document, `live_slice_crdt:<name>`),
  and past 100 stored updates they are compacted into one in a single transaction, so an update another tab
  stored meanwhile is never lost. The copy is loaded before `ready`, so a reload or an offline cold start (with
  the service worker and the offline mount of [Offline cold start](offline-cold-start.md)) shows and edits the
  last local state, and the edits merge once the page connects. A storage that fails is reported once, and
  the document lives in memory. The database also holds the copy's generation (a `meta` store, added in its
  version 2), the metadata of its last delete, and, on each stored update, whether the server has acknowledged
  it (see Unsent changes). Pending updates are compacted apart from acknowledged ones. A custom `persistence`
  implements `load`, `append`, `compact` and `setGeneration`, and optionally `settle` (without it, stored changes
  read back as unsent until the next sync); their contract is in `assets/js/live_slice/crdt_storage.js`.
- **Tabs.** The tabs of a browser profile relay their changes over a `BroadcastChannel`, and a tab that opens
  asks the others for what it lacks. Every tab syncs with the server, and a change relayed from a disconnected
  tab reaches the server through a connected one; a change from the server that one tab relays is not sent back
  by the others.
- **A server that lost the document.** A client that holds a document sends whatever the server lacks on its
  next sync. A server that lost a document (the in-memory persistence after a restart, or changes made after
  the last save when the process crashed) gets it back from the first client that syncs, and the other clients
  converge. That is what keeps a demo usable across restarts.
- **A deleted document.** `LiveSlice.CRDT.delete/2` (see [Deleting a document](#deleting-a-document)) makes the
  clients discard their copies instead. A client discards its copy when the server pushes `reset` while it
  syncs, or answers `reset` to its `sync1` after it was away: the copy goes, in memory and in IndexedDB, with
  every change not sent yet (the accepted loss: changes made offline on a document deleted meanwhile), the
  binding takes the new generation, which it stores next to the copy, and syncs the new document. Then it calls
  `onReset({generation, previous, discarded, meta, value, unsent})`: `discarded` tells whether the copy held
  something, so a UI can say "this document was deleted"; `meta` is the metadata the delete was given
  (`delete/3`), or null; `value` is what the key held just before (the JSON of the discarded copy), so the
  application can offer to paste the text back (`binding.update(...)` on the new document); `unsent` tells
  whether the copy held changes the server had not acknowledged, the ones that were lost, unless `carryOver`
  put them on the new document (`carried`, `carriedValue`, and `notCarried` for why not, see
  [Carrying unsent changes over](#carrying-unsent-changes-over)). A tab that learns of the delete from
  another tab reads `meta` from the stored copy, where the tab that heard it from the server wrote it; it is
  null when that write had not happened yet. The store key holds the new document's JSON at once. The binding works on a
  new `Y.Doc` from then on: `binding.doc` and `binding.root` are new objects and the old `Y.Doc` is destroyed
  (Yjs emits its `"destroy"` event, and changes made to it go nowhere), so code that keeps either, such as an
  editor binding or an observer, reads them again in `onReset`. A copy stored before generations existed has
  none, like a copy that never met a delete: it merges as before with a document that was never deleted, and
  is discarded, with `onReset`, when the server knows the document was deleted since.
- **Tabs and deletes.** Messages between tabs carry the sender's generation, and the stored copy refuses
  changes stored under another generation than its own, so a tab that still holds a deleted document puts none
  of it back: the other tabs ignore its messages and answer with their newer generation, the stored copy
  refuses its changes, and it discards its copy as above (unless the server confirmed its generation on the
  current connection: the server wins). A tab that was offline the whole time is brought to the new document
  this way before it reconnects.

## Limits of collaborative keys

- The server cannot validate or refuse an individual edit after the fact: authorization is per document and
  per direction (read, write). A writer can put anything a document can hold into it. Keep data with rules on
  normal keys and server actions.
- Merging follows Yjs: a delete wins over a concurrent edit inside the deleted item (a list item removed by one
  client and ticked by another stays removed), and for a map key one of two concurrent values wins.
- Documents grow with their history: deleted content leaves small tombstones, and each new client (each page
  load) adds an entry to the state vector. There is no garbage collection tuning, snapshot pruning or
  document size budget beyond `:max_document_bytes`.
- No awareness (cursors, presence), no rich-text editor binding, no undo manager.
- The persistence runs inside the document process: while a load or a save takes long, the document answers
  nothing else. A call it does not answer within 5 seconds gives up: `get/3`, `change/4` and `delete/2` return
  `{:error, :timeout}` (the request may still run afterwards), and a client's sync or update is answered
  `"unavailable"` and sent again later. The LiveView that made the call waits those 5 seconds. A sync that runs
  after its LiveView gave up does not leave that LiveView subscribed. Keep saves well under 5 seconds.
- Single node only. The registry of document processes is local: LiveViews on two nodes of a cluster each start
  their own process for a document, their clients do not see each other's changes, and both processes save
  their whole copy to the persistence, the last save replacing the other. Run the LiveViews of collaborative
  documents on one node.
- A client that turns out to be read-only keeps the changes it made offline before it knew: they stay in its
  local copy and never reach the server.
- Local copies belong to the browser profile, not to a user: clear them on sign-out with
  `indexedDB.deleteDatabase("live_slice_crdt:" + name)` for each document.
- A delete is remembered only as long as the persistence keeps the deleted document's record with its
  generation: after a restart of `MemoryPersistence` (or a persistence restored from an older backup, or one
  that removed the row) the first client that still holds a copy restores the deleted content. A copy that held
  nothing when its `sync1` left and was changed before the answer discards those changes when the server
  answers with another generation: they were made on the generation the server no longer has.
- So on a new device (or after its local copies were cleared), text typed into a document that was deleted at
  least once, before the binding got its first `sync1` reply, is discarded as a reset: the empty copy has no
  generation yet, the server answers with the generation of its last delete, and `onReset` reports
  `{discarded: true, previous: null, value}` with what was typed in `value`. The outcome is always this one,
  online or not; to keep the text, set `carryOver` (see
  [Carrying unsent changes over](#carrying-unsent-changes-over)), apply `value` again in `onReset` (for a text
  root: `binding.update((text) => text.insert(0, value))`), or accept input only once the binding's status is
  `"synced"` on a copy that started empty.
- Restoring a server backup older than the last delete brings back an older generation: every client that
  synced after that delete holds the newer one, is told to reset when it syncs, and discards its local copy,
  changes it had not sent yet included, for the backup's content. The server never takes a generation from a
  client, so it does not recognize the newer generation as a lost record. Restore a backup together with
  everything after it, or expect the clients' local work on that document to be lost.
