Nous.Persistence behaviour (nous v0.17.2)

Copy Markdown View Source

Behaviour for pluggable persistence backends.

Implement this behaviour to store and retrieve serialized agent contexts. See Nous.Persistence.ETS for a reference implementation.

Example

defmodule MyApp.RedisPersistence do
  @behaviour Nous.Persistence

  @impl true
  def save(session_id, data) do
    Redix.command(:redix, ["SET", "nous:#{session_id}", JSON.encode!(data)])
    :ok
  end

  @impl true
  def load(session_id) do
    # Decode to string keys; `Nous.Agent.Context.deserialize/1` accepts
    # them. Never `String.to_existing_atom/1` over stored keys — the
    # store's contents are not trusted input.
    case Redix.command(:redix, ["GET", "nous:#{session_id}"]) do
      {:ok, nil} -> {:error, :not_found}
      {:ok, json} -> {:ok, JSON.decode!(json)}
    end
  end

  @impl true
  def delete(session_id) do
    Redix.command(:redix, ["DEL", "nous:#{session_id}"])
    :ok
  end

  @impl true
  def list do
    {:ok, keys} = Redix.command(:redix, ["KEYS", "nous:*"])
    {:ok, Enum.map(keys, &String.replace_prefix(&1, "nous:", ""))}
  end
end

Summary

Callbacks

Delete persisted data for a session.

List all persisted session IDs.

Load serialized context data for a session.

Save serialized context data for a session.

Callbacks

delete(session_id)

@callback delete(session_id :: String.t()) :: :ok | {:error, term()}

Delete persisted data for a session.

list()

@callback list() :: {:ok, [String.t()]} | {:error, term()}

List all persisted session IDs.

load(session_id)

@callback load(session_id :: String.t()) ::
  {:ok, map()} | {:error, :not_found} | {:error, term()}

Load serialized context data for a session.

save(session_id, data)

@callback save(session_id :: String.t(), data :: map()) :: :ok | {:error, term()}

Save serialized context data for a session.