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

Where `LiveSlice.CRDT` keeps its documents between document processes.

A document process loads its document once when it starts, and saves the
whole document, encoded as one Yjs update (`Yex.encode_state_as_update/1`),
`:save_delay` milliseconds after the first change of a burst and when it
stops. Pass the module, or `{module, opts}`, as the `:persistence` option of
`LiveSlice.CRDT`; `c:init/1`, when defined, is called once with `opts` when
the server starts, in its supervisor, and what it returns is given to the
other callbacks (without it, `opts` is).

    defmodule MyApp.NotesPersistence do
      @behaviour LiveSlice.CRDT.Persistence

      @impl true
      def init(_opts), do: nil

      @impl true
      def load(doc_name, _state) do
        case MyApp.Repo.get(MyApp.Document, doc_name) do
          nil -> {:ok, nil}
          document -> {:ok, document.state, document.generation}
        end
      end

      @impl true
      def save(doc_name, snapshot, generation, _state) do
        %MyApp.Document{name: doc_name, state: snapshot, generation: generation}
        |> MyApp.Repo.insert(
          on_conflict: {:replace, [:state, :generation]},
          conflict_target: :name
        )
        |> case do
          {:ok, _} -> :ok
          {:error, changeset} -> {:error, changeset}
        end
      end
    end

The load runs right after the document process started, so a slow load
holds up the calls to that document only, never the start of other
documents; those calls wait for it, at most the server's `:load_timeout`
(5 seconds by default), after which `LiveSlice.CRDT.get/3`, `change/4`
and `delete/2` return `{:error, :load_timeout}` and a client is told the
document is unavailable. A failed load is logged and stops the process
before it answers any call: `LiveSlice.CRDT.get/3`, `change/4` and
`delete/2` return `{:error, {:load_failed, reason}}`, and clients are told
the document is unavailable and try again a second later. So a document is never saved over with a partial copy. A
failed save is logged and tried again after `:save_delay`.

## Generations

Every document has a generation: `nil` until it is first deleted, then the
string `LiveSlice.CRDT.delete/2` made for it (and returned as `{:ok,
generation}`). Clients keep the generation
of their local copy and send it when they sync, so that a copy of a
deleted document is discarded instead of being sent back to the server.
For a delete to be remembered, the persistence keeps the generation with
the snapshot: it implements `c:save/4` (which `LiveSlice.CRDT` then calls
instead of `c:save/3`) and returns `{:ok, snapshot, generation}` from
`c:load/2`. A delete is saved as an empty document with its new
generation, so the record must stay: removing it forgets the delete, and
the first client that syncs restores the old content, as it restores any
document the server has no record of.

`LiveSlice.CRDT.delete/3` takes metadata (who deleted, when), sent to the
clients with the reset. To keep it for clients that come back later, the
persistence implements `c:save/5`, which receives it next to the
generation (`nil` when the last delete had none, or for a document never
deleted), and returns it from `c:load/2` as `{:ok, snapshot, generation,
meta}`. `LiveSlice.CRDT` calls `save/5` when it is defined, otherwise
`save/4`, otherwise `save/3`.

A persistence written before generations (`c:save/3`, and `c:load/2`
returning `{:ok, snapshot}`) keeps working: its documents are of
generation `nil`, and `LiveSlice.CRDT.delete/2` returns
`{:error, :generations_not_supported}`.

# `generation`

```elixir
@type generation() :: String.t() | nil
```

A document's generation: `nil` until its first delete.

# `meta`

```elixir
@type meta() :: map() | nil
```

The metadata of the delete that made the generation (see `LiveSlice.CRDT.delete/3`).

# `init`
*optional* 

```elixir
@callback init(opts :: term()) :: term()
```

Called once when the server starts; returns the state given to the other callbacks.

# `load`

```elixir
@callback load(doc_name :: String.t(), state :: term()) ::
  {:ok, binary() | nil}
  | {:ok, binary() | nil, generation()}
  | {:ok, binary() | nil, generation(), meta()}
  | {:error, term()}
```

Returns the stored document as one Yjs update and its generation (and the
metadata of its delete, for a persistence that implements `c:save/5`), or
`{:ok, nil}` when there is no record of it. `{:ok, snapshot}` is a record
of generation `nil`.

# `save`
*optional* 

```elixir
@callback save(doc_name :: String.t(), snapshot :: binary(), state :: term()) ::
  :ok | {:error, term()}
```

Stores the whole document, given as one Yjs update, without its generation.

# `save`
*optional* 

```elixir
@callback save(
  doc_name :: String.t(),
  snapshot :: binary(),
  generation :: generation(),
  state :: term()
) ::
  :ok | {:error, term()}
```

Stores the whole document, given as one Yjs update, and its generation.

# `save`
*optional* 

```elixir
@callback save(
  doc_name :: String.t(),
  snapshot :: binary(),
  generation :: generation(),
  meta :: meta(),
  state :: term()
) :: :ok | {:error, term()}
```

Stores the whole document, given as one Yjs update, its generation and the
metadata of the delete that made it (a map with string keys, or `nil`).

---

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