# `Decree.PersonalFields.KeyStream`
[🔗](https://github.com/sparkle-space/decree/blob/v0.1.0/lib/decree/personal_fields/key_stream.ex#L1)

A subject's wrapped data key, on a stream of its own that can be hard deleted.

The stream is `prefix <> subject_id`. Its head holds the subject's current wrap, and the
ledger is the only place it is read from: nothing here is a process, and nothing is held
between calls.

A host implements `Decree.PersonalFields.KeySource` with `head/3`. It also generates the 32
bytes and wraps them, and unwraps what `head/3` answers: decree takes and answers wrapped
bytes, and never sees the raw key.

## The store declaration

A key stream's prefix must be declared deletable, along with `event_types/0`:

    defmodule MyApp.EventStore do
      use Decree.Store,
        otp_app: :my_app,
        enable_hard_deletes: true,
        deletable: [
          stream_prefixes: ["SubjectKey-"],
          event_types: Decree.PersonalFields.KeyStream.event_types()
        ]
    end

`mint/5` and `rewrap/4` refuse a prefix the store does not declare, with
`{:error, :undeclared_key_stream}`, because a stream outside the declaration gets none of
its refusals: a query or a stray event type would be let in. A store without
`enable_hard_deletes` answers `:undeclared_key_stream` for every prefix, whatever it declares,
because it could never erase the key.

A `use` line resolves `event_types/0` when the store compiles, so `:type_provider` belongs in
compile-time config: a provider set only at runtime makes every key write answer
`:undeclared_deletable_event_type`, with nothing written.

## What this layer can't tell

  - `head/3` answers `:stream_not_found` for a stream that never existed and for one hard
    deleted. Deletion leaves no tombstone. Only the host's own record of what it erased can
    tell the two apart, so a host's `lookup/1` reads that first, and maps this answer to
    `:unknown`.

  - Nothing here answers erased. A store failure is an `{:error, _}` that is not
    `:stream_not_found`, so it can never read as a shred.

  - A mint succeeds on a hard-deleted stream, with a fresh key.

  - An exact version can't tell a re-created stream. After a delete and a mint, a `%Head{}`
    at version 1 from before the delete passes `rewrap/4`, and old key material is back.

  - **So every write needs the host's admission re-check after it.** After a `mint/5` or a
    `rewrap/4` that answers success, the host reads its record again, and if the subject was
    erased it hard deletes the stream. No expected version here does that for it.

## Restores

A restored stream is just a stream. After a whole-database restore `head/3` answers it, and
nothing marks that it predates an erasure. That is the host's to re-apply.

## What a `$all` subscriber sees

Key events reach every subscriber of `$all`: the store delivers them like any other, and a
handler's catch-all clause absorbs them. Each holds the wrapped bytes as base64, the ids, the
master tag and a timestamp, and no declared field. They carry no tags, so no query can reach
them, and they skip `Decree.Event.Append.prepare/4`, which would add some.

A delivered event is in the metadata of `[:decree, :event, :handle]` and of
`Decree.EventStore.ack_event/3`'s telemetry, as every event is. `Inspect` leaves the wrap out
there, so a telemetry handler may inspect that metadata, and must not serialize it.

## Key material

Wrapped bytes never leave here but in a `%Head{}`, whose `Inspect` leaves them out, as the
events' does. A failure answers an atom, `{:append_failed, class}` or
`Decree.PersonalFields.RedactedError.reduce/1`'s reduction, and a raise, an exit or a throw
is caught and reduced the same way. Every argument is checked inside the function, so a bad
one answers a refusal, and no failed clause puts it in a stacktrace.

A key append goes through `Decree.EventStore.append_without_span/4`, and a read through
`Decree.EventStore.read_stream_head/2`, because a span's exception event would publish a
raised term and its stacktrace before the catch here reduces anything.

# `failure`

```elixir
@type failure() :: atom() | {atom(), atom()}
```

A refusal or a failure, with nothing in it that came from a key.

# `event_types`

```elixir
@spec event_types() :: [String.t()]
```

The two stored type strings, for a store's `deletable: [event_types: ...]`.

# `head`

```elixir
@spec head(Decree.Application.t(), String.t(), String.t()) ::
  {:ok, Decree.PersonalFields.KeyStream.Head.t()}
  | {:error, :stream_not_found}
  | {:error, :stream_deleted}
  | {:error, :malformed_key_event}
  | {:error, failure()}
```

Reads a subject's key stream, with one read of its head. Every call reads the store.

Answers `{:ok, %Head{}}`, `{:error, :stream_not_found}` for a stream with no events, whether
it never existed or was hard deleted, `{:error, :stream_deleted}` for a soft-deleted one,
`{:error, :malformed_key_event}` for a head that is not a key event of this subject, or
`{:error, :invalid_subject}` for a subject that is not a canonical UUID. Anything else is a
failed read: an `{:error, _}` that says nothing about the subject.

# `mint`

```elixir
@spec mint(Decree.Application.t(), String.t(), String.t(), binary(), String.t()) ::
  {:ok, key_id :: String.t()} | {:error, :stream_exists} | {:error, failure()}
```

Appends a subject's first wrap at `:no_stream`, and mints its `key_id`.

Every way of losing the stream to another writer answers `{:error, :stream_exists}`, and the
loser then reads the winner's key with `head/3`.

Refuses, with nothing written, a prefix the store does not declare
(`:undeclared_key_stream`), a subject that is not a canonical UUID (`:invalid_subject`), an
empty or non-binary wrap (`:invalid_wrapped_key`) and a master tag that is not non-empty
text (`:invalid_master_tag`). A store without `enable_hard_deletes` answers
`:undeclared_key_stream` for every prefix, because it could never erase the key.

A failed append answers `{:error, {:append_failed, class}}`, with the class of
`Decree.Store.AppendError`. An `:unavailable` one may have landed.

# `rewrap`

```elixir
@spec rewrap(
  Decree.Application.t(),
  Decree.PersonalFields.KeyStream.Head.t(),
  binary(),
  String.t()
) ::
  :ok
  | {:error, :wrong_expected_version}
  | {:error, :not_found}
  | {:error, failure()}
```

Appends a new wrap at the exact version of `head`, keeping its `key_id`.

A `head` that is stale, or of a stream that has gone, answers
`{:error, :wrong_expected_version}`. `{:error, :not_found}` is a stream hard deleted after
this append had read it.

It trusts `head`'s `key_id` and version, so pass a `%Head{}` that `head/3` answered on the
same application.

Refuses, with nothing written, what `mint/5` refuses, and `:invalid_head` for anything that
is not a `%Head{}` as `head/3` answers one. See "What this layer can't tell" for what an
exact version does not catch.

---

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