PhoenixReplay.Storage.Codec (PhoenixReplay v0.6.2)

Copy Markdown View Source

Binary encoding shared by the storage backends.

Terms are stored in compressed Erlang External Term Format, which keeps structs, atoms and tuples intact so recordings re-render exactly. Decoding uses :safe mode, so a recording that references atoms this node has never seen fails to decode instead of growing the atom table.

Summary

Functions

Decodes a binary produced by encode/1 into a struct of the given module, or into a list when shape is :list.

Decodes the frames at the start of binary, in order, stopping at the first incomplete or corrupt one.

Encodes a term.

Encodes a term as a frame that can be appended to a file.

Functions

decode(binary, shape)

@spec decode(binary(), module() | :list) ::
  {:ok, struct() | list()} | {:error, :undecodable}

Decodes a binary produced by encode/1 into a struct of the given module, or into a list when shape is :list.

Structs are rebuilt with struct/2, so data written before a field was added gets the field's default, and recordings go through PhoenixReplay.Recording.upgrade/1.

Recordings hold module names, such as the structs in assigns, and safe decoding refuses atoms the VM has not created yet. In development, where modules load on first use, a recording can name a module that exists but has not been loaded since the node started. The first time a binary does not decode, modules available on the code path but not yet loaded are loaded, which creates only the atoms of modules that really exist, and decoding is retried.

Returns {:error, :undecodable} for corrupt data, atoms of no known module, or a term of a different shape.

decode_frames(binary)

@spec decode_frames(binary()) :: [term()]

Decodes the frames at the start of binary, in order, stopping at the first incomplete or corrupt one.

encode(term)

@spec encode(term()) :: binary()

Encodes a term.

frame(term)

@spec frame(term()) :: iodata()

Encodes a term as a frame that can be appended to a file.

A frame is a marker, the payload's byte size and CRC32, then the payload encoded by encode/1. decode_frames/1 stops at the first frame that is cut short or fails its checksum, so a write torn by a crash loses only itself.