Spectre.Router.Adapter behaviour (Spectre v0.3.4)

Copy Markdown View Source

Native extension point for router evidence providers.

An Adapter receives a projected, read-only routing request and returns scored references to rules that were visible to it. Spectre resolves those references against the compiled Definition, builds authoritative candidates, and leaves the final decision to the configured arbitrator.

defmodule MyApp.BinaryRouter do
  use Spectre.Router.Adapter,
    id: :binary,
    accept: 0.86,
    margin: 0.04,
    strength: :medium

  @impl Spectre.Router.Adapter
  def evaluate(%Spectre.Router.Adapter.Request{text: text, rules: rules}) do
    results =
      rules
      |> Enum.map(&result(&1, score(text, &1)))
      |> Enum.sort_by(& &1.score, :desc)
      |> Enum.take(32)

    {:ok, results}
  end
end

Adapters return evidence only. They cannot provide handlers, owners, terminal routes, acceptance decisions, or executable callbacks. They must rank or filter evidence to at most 32 distinct rule references; the core rejects an oversized response rather than silently choosing evidence for the Adapter.

Summary

Functions

Declares a native router Adapter.

Normalizes Adapter rule data into an examples list.

Builds one Adapter result from a visible RuleView or its {scope, label} ref.

Builds one Adapter result with optional :margin and :matched evidence.

Executes one compiled Adapter by id inside a custom router pipeline.

Types

reply()

@type reply() ::
  {:ok, result() | [result()]} | :skip | {:skip, term()} | {:error, term()}

result()

@type result() :: %{
  :rule => Spectre.Router.Adapter.RuleView.ref(),
  :score => number(),
  optional(:margin) => number() | nil,
  optional(:matched) => term()
}

strength()

@type strength() :: :hard | :strong | :medium | :weak

Callbacks

evaluate(t)

@callback evaluate(Spectre.Router.Adapter.Request.t()) :: reply()

Functions

__using__(opts)

(macro)

Declares a native router Adapter.

Supported options are :id, :accept, :margin, and :strength. The generated descriptor is static and is snapshotted into every Agent that declares the module in its router via.

examples(data)

@spec examples(Spectre.Router.Adapter.RuleView.t() | term()) :: [term()]

Normalizes Adapter rule data into an examples list.

Scalars, ordinary lists, and [examples: [...]] use the same ergonomic shapes as Spectre's built-in similarity providers.

result(rule, score)

Builds one Adapter result from a visible RuleView or its {scope, label} ref.

result(rule, score, opts)

Builds one Adapter result with optional :margin and :matched evidence.

run(context, adapter_id)

@spec run(Spectre.Router.Context.t(), atom()) ::
  {:cont, Spectre.Router.Context.t()} | {:error, term()}

Executes one compiled Adapter by id inside a custom router pipeline.