Runs a program that speaks the beamports protocol as an Erlang port: Erlang terms, each after a 4-byte length ({packet, 4}). duckport, oxiport and tantiport speak it when started with --etf, and so can any program built with the Rust crate beamports_etf, or that writes the same messages.

Installation

def deps do
  [
    {:etf_port, "~> 2.0"}
  ]
end

Usage

{:ok, pid} =
  EtfPort.start_link(
    executable: "/usr/local/bin/duckport",
    args: ["--etf", "--database", "/var/db/app/analytics.duckdb"],
    on_state: fn state -> IO.inspect(state, label: "duckport") end
  )

{:ok, %{"rows" => [%{"answer" => 42}]}} =
  EtfPort.call(pid, "query", %{sql: "SELECT 42 AS answer", params: []})

{:error, {:fail, "query_failed", %{"message" => _}}} =
  EtfPort.call(pid, "query", %{sql: "SELEKT", params: []})

{:error, "missing_sql"} = EtfPort.call(pid, "query", %{params: []})

Options of start_link/1:

  • :executable - absolute path of the program (required).
  • :args - its arguments.
  • :name - registers the process.
  • :on_state - a function given each state of the program's, as a map: %{"dimension" => "life", "state" => "running"} once it takes calls, "starting" when it is started, "failed" (with "reason") when it exited and isn't started again.
  • :restart - {count, milliseconds}: how many times a program that exited is started again within that time (default {3, 10_000}).

EtfPort can be started under a supervisor as {EtfPort, options}.

Behaviour

  • Each process owns one program, which it starts at once. Calls wait until the program says it runs (its readiness), then go to it up to its concurrency (from its hello); the rest wait their turn.
  • call/4 answers {:ok, data}, {:error, {:fail, port, details}} for a failure the program declares, or {:error, reason}: the program's error (a binary) or one of the client's (EtfPort.error/0).
  • A call whose time is up (timeout, default 30 000 ms) is cancelled. A program that takes one call at a time and doesn't answer within a grace of 1 s after that is killed, on Windows with taskkill, and started again; the call answers {:error, :uncertain_native_outcome}: a write the program was doing may or may not have happened, so treat the outcome as unknown, not as failed.
  • A program that exits answers its calls in flight {:error, {:native_exit, status}} and is started again within the restart budget; past it, calls answer the same until the budget allows a start again, when it is started by itself, or reset/2 starts it.
  • reset/2 waits for the calls made before it, then stops the program and starts it again: nothing called before it is still running afterwards.
  • Payloads are maps whose keys may be atoms or binaries; atoms other than true, false and nil become binaries, dates and times ISO 8601 text, a Decimal its text. Calls and replies are limited to 16 MiB.
  • hello/1 gives what the program said it is.

License

BSD 3-Clause License, see the LICENSE file.