# `LiveSlice.CRDT`
[🔗](https://github.com/CountlinkX-Solutions/live_slice/blob/v0.2.1/lib/live_slice/crdt.ex#L1)

The server side of collaborative keys: one process per document, holding a
Yjs document (`Yex.Doc`, from the optional dependency `y_ex`) that the
clients of every LiveView showing it sync with. See "Collaborative keys" in
`LiveSlice` and the Collaborative keys guide.

Add `{:y_ex, "~> 0.13"}` to the app's dependencies (it ships precompiled
NIFs), and the server to its supervision tree:

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

## Options

  * `:name` - the server's name, `LiveSlice.CRDT` by default. LiveViews
    name it with `collaborative: [notes: [server: MyApp.CRDT]]`.
  * `:persistence` - a module implementing `LiveSlice.CRDT.Persistence`,
    or `{module, opts}`. `LiveSlice.CRDT.MemoryPersistence` by default,
    which loses every document when the server stops: for demos only.
  * `:idle_timeout` - how long a document process stays up without
    subscribed LiveViews, in milliseconds (30 seconds by default). It saves
    the document and stops then.
  * `:save_delay` - how long after the first change of a burst the document
    is saved, in milliseconds (2 seconds by default).
  * `:max_update_bytes` - the largest update a client may send as it
    edits, and the largest state vector (1 MB by default). Larger ones are
    refused with `"too_large"`; the client then sends the change with its
    next sync.
  * `:max_document_bytes` - updates that would make the document larger
    than this are refused with `"document_too_large"` (10 MB by default;
    the size is an estimate, checked exactly when the estimate is over).
    It also bounds what a client sends right after a sync, what the server
    lacks (once per sync, counted against `:rate_limit` as that many
    updates of `:max_update_bytes`), so a document larger than one update
    can be restored from a client.
  * `:rate_limit` - `{count, milliseconds}`: a LiveView may push `count`
    updates of a key per window of that many milliseconds, `{200, 10_000}`
    by default; more are refused with `"rate_limited"` and `retry_after`,
    the milliseconds left in the window (the client sends them in its next
    sync, once the window is over). The window is the key's, whatever
    document is synced: a sync2 and a background delivery count in it too
    (a `deliver1` as one update, a `deliver2` by its size).
  * `:load_timeout` - how long a caller waits for a document that is
    loading from the persistence, in milliseconds (5 seconds by default),
    whether its call started the document or found it loading. A caller
    that waits longer gets `{:error, :load_timeout}` and has sent the
    document nothing; the load goes on, and later callers find the loaded
    document. A sync is then answered `"unavailable"`, and the client
    tries again.

A document process is started on demand, under the server's
`DynamicSupervisor`, registered by document name in its `Registry`; it is
not restarted when it crashes: the next sync starts it again from the
persistence, and the clients send back what it lost. Registry and
supervisor are local, so a document is shared by the LiveViews of one node
only (see the Known limits guide).

## Reading and changing documents on the server

`get/3` returns a document's JSON and `change/4` changes it like a client
would, and broadcasts the change. Both take the root type of the document as
the client declares it: `:map`, `:array` or `:text` for the single root
named "root", or a keyword list such as `[body: :text, items: :array]` for
a shape of roots. Both start the document when it is not running, and
return `{:error, :load_timeout}` when its load takes longer than
`:load_timeout` and `{:error, {:load_failed, reason}}` when it could not
be loaded: the persistence returned `{:error, reason}` (see
`c:LiveSlice.CRDT.Persistence.load/2`), or the document process stopped
before it was loaded, for `reason` (it crashed, or it stopped twice in a
row; once, it is started again). Nothing was read or changed then.

A document process runs one request at a time, its persistence's loads and
saves included. A call it does not answer within 5 seconds (a save to a
slow persistence, say) returns `{:error, :timeout}`; the document may still
run it afterwards, so a change or a delete that timed out may be applied.

    {:ok, %{"body" => body}} = 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" => "From the server", "done" => false}))
    end)

Numbers come back as floats, as Yjs keeps them.

## Deleting documents

`delete/2` drops a document's content and starts it over under a new
generation, so that clients discard their copies instead of restoring
them; see `delete/2` and "Generations" in `LiveSlice.CRDT.Persistence`.

# `root_type`

```elixir
@type root_type() :: :map | :array | :text | [{atom(), :map | :array | :text}]
```

A root type, or a shape of root types by name.

# `server`

```elixir
@type server() :: atom()
```

The server's name.

# `change`

```elixir
@spec change(server(), String.t(), root_type(), (term() -&gt; term())) ::
  :ok | {:error, term()}
```

Runs `fun` with the document's root (or a map of roots for a shape) in one
transaction, and sends the change to every subscribed client.

Returns `{:error, exception}` when `fun` raises; what it changed before is
kept, as with Yjs transactions (there is no rollback). Returns
`{:error, :load_timeout}` when the document is still loading after
`:load_timeout` and `{:error, {:load_failed, reason}}` when it could not
be loaded; `fun` did not run then. Returns `{:error, :timeout}` when the
document did not answer in time: `fun` may still run afterwards, and its
change reach the clients.

# `delete`

```elixir
@spec delete(server(), String.t()) :: {:ok, String.t()} | {:error, term()}
@spec delete(String.t(), keyword()) :: {:ok, String.t()} | {:error, term()}
```

Deletes a document: its content is dropped, and it starts over, empty,
under a new generation, which is saved at once (`c:LiveSlice.CRDT.Persistence.save/5`,
or `save/4` for a persistence without it).
Returns `{:ok, generation}`, the generation the document starts over
with (a string such as `"1764612345678-3fa94c2b1d07"`); `delete/3` does
the same and takes metadata.

Clients that sync the document at that moment are told at once (a
`live_slice:crdt` event of step `"reset"`, after the same checks as any
change pushed to them): they discard their local copy, the changes they
had not sent yet included, and sync the new, empty document (a client
key with `carryOver` writes those unsent changes again as new changes
of the new generation, which reach the server as ordinary updates; see
"Carrying unsent changes over" in the Collaborative keys guide). A
client that held a copy while away is told the same when it syncs
again, so its copy never brings the deleted content back. The
application decides who may delete (this is a server call; no client
message can delete a document) and may fill the new document afterwards
with `change/4`.

Returns `{:error, :generations_not_supported}` when the persistence keeps
no generation (it implements `save/3` only), and `{:error, {:save_failed,
reason}}` when the delete could not be saved; the document is then left
as it was. Like `get/3`, it returns `{:error, :load_timeout}` or
`{:error, {:load_failed, reason}}` when the document could not be loaded
first, and deletes nothing then, and `{:error, :timeout}` when the
document did not answer in time: the delete may still happen afterwards.
A deleted document is remembered as
long as the persistence keeps its record:
`LiveSlice.CRDT.MemoryPersistence` forgets it when the server stops, and
then the first client that syncs a copy restores it.

# `delete`

```elixir
@spec delete(server(), String.t(), keyword()) :: {:ok, String.t()} | {:error, term()}
```

Deletes a document as `delete/2` does, returns the same `{:ok,
generation}` (the errors are those of `delete/2`), and takes options.

## Options

  * `:meta` - a small JSON object (a map with string or atom keys whose
    JSON is at most 2048 bytes) that says something about
    the delete, such as who made it and when: `meta: %{by: user.name, at:
    System.os_time(:millisecond)}`. It travels in the reset notice to every
    client that syncs the document (`onReset` receives it as `meta`, with
    string keys) and is stored with the generation, so a client that comes
    back later is told too, when the persistence implements
    `c:LiveSlice.CRDT.Persistence.save/5`; with `save/4` only, the clients
    told at once get it and later ones get `nil`. Raises `ArgumentError`
    for anything else.

`delete(doc_name, opts)` deletes on the default server as
`delete(LiveSlice.CRDT, doc_name, opts)` does.

# `get`

```elixir
@spec get(server(), String.t(), root_type()) :: {:ok, term()} | {:error, term()}
```

Returns the JSON of a document's root (`root_type`, see the module
documentation), starting its process when needed.

Returns `{:error, :load_timeout}` when the document is still loading
after `:load_timeout`, `{:error, {:load_failed, reason}}` when it could
not be loaded, and `{:error, :timeout}` when it did not answer in time
(see "Reading and changing documents on the server" in the module
documentation).

# `reauthorize`

```elixir
@spec reauthorize(Phoenix.LiveView.Socket.t()) :: Phoenix.LiveView.Socket.t()
```

Checks the collaborative keys this LiveView's client synced again:
`c:LiveSlice.crdt_document/2` must still name the same document and
`c:LiveSlice.authorize_crdt/3` must still allow `:read`. A key that fails
leaves its document, and its client is told with a `live_slice:crdt`
event of step `"refused"` (reason `"forbidden"`, `"wrong_document"` or
`"no_document"`): it stops syncing the key until its next connection,
with the status "offline".

The same checks run before every change of the document is pushed to the
client, so a revoked client never receives one; call this after changing
what the callbacks read to make the change take effect at once instead of
at the next change of the document:

    def handle_info({:membership_removed, _note_id}, socket) do
      {:noreply, socket |> assign(member?: false) |> LiveSlice.CRDT.reauthorize()}
    end

A LiveView without collaborative keys is returned unchanged.

# `start_link`

```elixir
@spec start_link(keyword()) :: Supervisor.on_start()
```

Starts the server; see the module documentation for the options.

---

*Consult [api-reference.md](api-reference.md) for complete listing*
