Elixir ATProtocol firehose & subscription listener

feat: initial proof of concept

ovyerus.com 7cb3b53a 3df61b08

verified
+2 -1
.formatter.exs
···
# Used by "mix format"
[
-
inputs: ["{mix,.formatter}.exs", "{config,lib,test}/**/*.{ex,exs}"]
+
inputs: ["{mix,.formatter}.exs", "{config,lib,test}/**/*.{ex,exs}"],
+
import_deps: [:typedstruct]
]
+68 -12
lib/drinkup.ex
···
-
defmodule Drinkup do
-
@moduledoc """
-
Documentation for `Drinkup`.
-
"""
+
defmodule Drinkup.Firehose do
+
alias Drinkup.Firehose
+
require Logger
-
@doc """
-
Hello world.
+
use WebSockex
-
## Examples
+
@default_host "https://bsky.network"
-
iex> Drinkup.hello()
-
:world
+
@op_regular 1
+
@op_error -1
-
"""
-
def hello do
-
:world
+
# TODO: switch to Gun and GenServer?
+
+
def start_link(opts \\ []) do
+
opts = Keyword.validate!(opts, host: @default_host)
+
host = Keyword.get(opts, :host)
+
cursor = Keyword.get(opts, :cursor)
+
+
url =
+
"#{host}/xrpc/com.atproto.sync.subscribeRepos"
+
|> URI.new!()
+
|> URI.append_query(URI.encode_query(%{cursor: cursor}))
+
|> URI.to_string()
+
+
WebSockex.start_link(url, __MODULE__, %{cursor: cursor})
end
+
+
def handle_connect(conn, state) do
+
Logger.info("Connected to Firehose at #{conn.host}#{conn.path}")
+
{:ok, state}
+
end
+
+
def handle_frame({:binary, msg}, state) do
+
with {:ok, header, next} <- CAR.DagCbor.decode(msg),
+
{:ok, payload, _} <- CAR.DagCbor.decode(next),
+
{%{"op" => @op_regular, "t" => type}, _} <- {header, payload},
+
message <- from_payload(type, payload) do
+
case message do
+
%Firehose.Commit{} = commit ->
+
IO.inspect(commit.ops, label: commit.repo)
+
+
msg ->
+
IO.inspect(msg)
+
end
+
else
+
{%{"op" => @op_error, "t" => type}, payload} ->
+
Logger.error("Got error from Firehose: #{inspect({type, payload})}")
+
+
{:error, reason} ->
+
Logger.warning("Failed to decode frame from Firehose: #{inspect(reason)}")
+
end
+
+
{:ok, state}
+
end
+
+
def handle_frame({:text, msg}, state) do
+
Logger.warning("Got unexpected text frame from Firehose #{inspect(msg)}")
+
{:ok, state}
+
end
+
+
@spec from_payload(String.t(), map()) ::
+
Firehose.Commit.t()
+
| Firehose.Sync.t()
+
| Firehose.Identity.t()
+
| Firehose.Account.t()
+
| Firehose.Info.t()
+
| nil
+
def from_payload("#commit", payload), do: Firehose.Commit.from(payload)
+
def from_payload("#sync", payload), do: Firehose.Sync.from(payload)
+
def from_payload("#identity", payload), do: Firehose.Identity.from(payload)
+
def from_payload("#account", payload), do: Firehose.Account.from(payload)
+
def from_payload("#info", payload), do: Firehose.Info.from(payload)
+
def from_payload(_type, _payload), do: nil
end
+53
lib/firehose/account.ex
···
+
defmodule Drinkup.Firehose.Account do
+
@moduledoc """
+
Struct for account events from the ATProto Firehose.
+
"""
+
+
use TypedStruct
+
+
@type status() ::
+
:takendown
+
| :suspended
+
| :deleted
+
| :deactivated
+
| :desynchronized
+
| :throttled
+
| String.t()
+
+
typedstruct enforce: true do
+
field :seq, integer()
+
field :did, String.t()
+
field :time, NaiveDateTime.t()
+
field :active, bool()
+
field :status, status(), enforce: false
+
end
+
+
@spec from(map()) :: t()
+
def from(%{"seq" => seq, "did" => did, "time" => time, "active" => active} = msg) do
+
status = recognise_status(Map.get(msg, "status"))
+
time = NaiveDateTime.from_iso8601!(time)
+
+
%__MODULE__{
+
seq: seq,
+
did: did,
+
time: time,
+
active: active,
+
status: status
+
}
+
end
+
+
@spec recognise_status(String.t()) :: status()
+
defp recognise_status(status)
+
when status in [
+
"takendown",
+
"suspended",
+
"deleted",
+
"deactivated",
+
"desynchronized",
+
"throttled"
+
],
+
do: String.to_atom(status)
+
+
defp recognise_status(status) when is_binary(status), do: status
+
defp recognise_status(nil), do: nil
+
end
+100
lib/firehose/commit.ex
···
+
defmodule Drinkup.Firehose.Commit do
+
@moduledoc """
+
Struct for commit events from the ATProto Firehose.
+
"""
+
+
# TODO: see atp specs
+
@type tid() :: String.t()
+
+
alias __MODULE__.RepoOp
+
use TypedStruct
+
+
typedstruct enforce: true do
+
field :seq, integer()
+
# DEPCREATED
+
field :rebase, bool()
+
# DEPRECATED
+
field :too_big, bool()
+
field :repo, String.t()
+
field :commit, binary()
+
field :rev, tid()
+
field :since, tid() | nil
+
field :blocks, CAR.Archive.t()
+
field :ops, list(RepoOp.t())
+
# DEPRECATED
+
field :blobs, list(binary())
+
field :prev_data, binary(), enforce: nil
+
field :time, NaiveDateTime.t()
+
end
+
+
@spec from(map()) :: t()
+
def from(
+
%{
+
"seq" => seq,
+
"rebase" => rebase,
+
"tooBig" => too_big,
+
"repo" => repo,
+
"commit" => commit,
+
"rev" => rev,
+
"since" => since,
+
"blocks" => %CBOR.Tag{value: blocks},
+
"ops" => ops,
+
"blobs" => blobs,
+
"time" => time
+
} = msg
+
) do
+
prev_data =
+
Map.get(msg, "prevData")
+
+
time = NaiveDateTime.from_iso8601!(time)
+
{:ok, blocks} = CAR.decode(blocks)
+
+
%__MODULE__{
+
seq: seq,
+
rebase: rebase,
+
too_big: too_big,
+
repo: repo,
+
commit: commit,
+
rev: rev,
+
since: since,
+
blocks: blocks,
+
ops: Enum.map(ops, &RepoOp.from(&1, blocks)),
+
blobs: blobs,
+
prev_data: prev_data,
+
time: time
+
}
+
end
+
+
defmodule RepoOp do
+
typedstruct enforce: true do
+
@type action() :: :create | :update | :delete | String.t()
+
+
field :action, action()
+
field :path, String.t()
+
field :cid, binary()
+
field :prev, binary(), enforce: false
+
field :record, map() | nil
+
end
+
+
@spec from(map(), CAR.Archive.t()) :: t()
+
def from(%{"action" => action, "path" => path, "cid" => cid} = op, %CAR.Archive{} = blocks) do
+
prev = Map.get(op, "prev")
+
record = CAR.Archive.get_block(blocks, cid)
+
+
%__MODULE__{
+
action: recognise_action(action),
+
path: path,
+
cid: cid,
+
prev: prev,
+
record: record
+
}
+
end
+
+
@spec recognise_action(String.t()) :: action()
+
defp recognise_action(action) when action in ["create", "update", "delete"],
+
do: String.to_atom(action)
+
+
defp recognise_action(action) when is_binary(action), do: action
+
defp recognise_action(nil), do: nil
+
end
+
end
+27
lib/firehose/identity.ex
···
+
defmodule Drinkup.Firehose.Identity do
+
@moduledoc """
+
Struct for identity events from the ATProto Firehose.
+
"""
+
+
use TypedStruct
+
+
typedstruct enforce: true do
+
field :seq, integer()
+
field :did, String.t()
+
field :time, NaiveDateTime.t()
+
field :handle, String.t() | nil
+
end
+
+
@spec from(map()) :: t()
+
def from(%{"seq" => seq, "did" => did, "time" => time} = msg) do
+
handle = Map.get(msg, "handle")
+
time = NaiveDateTime.from_iso8601!(time)
+
+
%__MODULE__{
+
seq: seq,
+
did: did,
+
time: time,
+
handle: handle
+
}
+
end
+
end
+22
lib/firehose/info.ex
···
+
defmodule Drinkup.Firehose.Info do
+
@moduledoc """
+
Struct for info events from the ATProto Firehose.
+
"""
+
+
use TypedStruct
+
+
typedstruct enforce: true do
+
field :name, String.t()
+
field :message, String.t() | nil
+
end
+
+
@spec from(map()) :: t()
+
def from(%{"name" => name} = msg) do
+
message = Map.get(msg, "message")
+
+
%__MODULE__{
+
name: name,
+
message: message
+
}
+
end
+
end
+28
lib/firehose/sync.ex
···
+
defmodule Drinkup.Firehose.Sync do
+
@moduledoc """
+
Struct for sync events from the ATProto Firehose.
+
"""
+
+
use TypedStruct
+
+
typedstruct enforce: true do
+
field :seq, integer()
+
field :did, String.t()
+
field :blocks, binary()
+
field :rev, String.t()
+
field :time, NaiveDateTime.t()
+
end
+
+
@spec from(map()) :: t()
+
def from(%{"seq" => seq, "did" => did, "blocks" => blocks, "rev" => rev, "time" => time}) do
+
time = NaiveDateTime.from_iso8601!(time)
+
+
%__MODULE__{
+
seq: seq,
+
did: did,
+
blocks: blocks,
+
rev: rev,
+
time: time
+
}
+
end
+
end
+5 -2
mix.exs
···
# Run "mix help deps" to learn about dependencies.
defp deps do
[
-
# {:dep_from_hexpm, "~> 0.3.0"},
-
# {:dep_from_git, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"}
+
{:cbor, "~> 1.0.0"},
+
{:car, "~> 0.1.0"},
+
{:credo, "~> 1.7", only: [:dev, :test], runtime: false},
+
{:typedstruct, "~> 0.5"},
+
{:websockex, "~> 0.5.0", hex: :websockex_wt}
]
end
end
+12
mix.lock
···
+
%{
+
"bunt": {:hex, :bunt, "1.0.0", "081c2c665f086849e6d57900292b3a161727ab40431219529f13c4ddcf3e7a44", [:mix], [], "hexpm", "dc5f86aa08a5f6fa6b8096f0735c4e76d54ae5c9fa2c143e5a1fc7c1cd9bb6b5"},
+
"car": {:hex, :car, "0.1.1", "a5bc4c5c1be96eab437634b3c0ccad1fe17b5e3d68c22a4031241ae1345aebd4", [:mix], [{:cbor, "~> 1.0.0", [hex: :cbor, repo: "hexpm", optional: false]}, {:typedstruct, "~> 0.5", [hex: :typedstruct, repo: "hexpm", optional: false]}, {:varint, "~> 1.4", [hex: :varint, repo: "hexpm", optional: false]}], "hexpm", "f895dda8123d04dd336db5a2bf0d0b47f4559cd5383f83fcca0700c1b45bfb6a"},
+
"cbor": {:hex, :cbor, "1.0.1", "39511158e8ea5a57c1fcb9639aaa7efde67129678fee49ebbda780f6f24959b0", [:mix], [], "hexpm", "5431acbe7a7908f17f6a9cd43311002836a34a8ab01876918d8cfb709cd8b6a2"},
+
"credo": {:hex, :credo, "1.7.12", "9e3c20463de4b5f3f23721527fcaf16722ec815e70ff6c60b86412c695d426c1", [:mix], [{:bunt, "~> 0.2.1 or ~> 1.0", [hex: :bunt, repo: "hexpm", optional: false]}, {:file_system, "~> 0.2 or ~> 1.0", [hex: :file_system, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: false]}], "hexpm", "8493d45c656c5427d9c729235b99d498bd133421f3e0a683e5c1b561471291e5"},
+
"file_system": {:hex, :file_system, "1.1.0", "08d232062284546c6c34426997dd7ef6ec9f8bbd090eb91780283c9016840e8f", [:mix], [], "hexpm", "bfcf81244f416871f2a2e15c1b515287faa5db9c6bcf290222206d120b3d43f6"},
+
"jason": {:hex, :jason, "1.4.4", "b9226785a9aa77b6857ca22832cffa5d5011a667207eb2a0ad56adb5db443b8a", [:mix], [{:decimal, "~> 1.0 or ~> 2.0", [hex: :decimal, repo: "hexpm", optional: true]}], "hexpm", "c5eb0cab91f094599f94d55bc63409236a8ec69a21a67814529e8d5f6cc90b3b"},
+
"telemetry": {:hex, :telemetry, "1.3.0", "fedebbae410d715cf8e7062c96a1ef32ec22e764197f70cda73d82778d61e7a2", [:rebar3], [], "hexpm", "7015fc8919dbe63764f4b4b87a95b7c0996bd539e0d499be6ec9d7f3875b79e6"},
+
"typedstruct": {:hex, :typedstruct, "0.5.3", "d68ae424251a41b81a8d0c485328ab48edbd3858f3565bbdac21b43c056fc9b4", [:make, :mix], [], "hexpm", "b53b8186701417c0b2782bf02a2db5524f879b8488f91d1d83b97d84c2943432"},
+
"varint": {:hex, :varint, "1.5.1", "17160c70d0428c3f8a7585e182468cac10bbf165c2360cf2328aaa39d3fb1795", [:mix], [], "hexpm", "24f3deb61e91cb988056de79d06f01161dd01be5e0acae61d8d936a552f1be73"},
+
"websockex": {:hex, :websockex_wt, "0.5.0", "8725b3bc741e7a682c21310610d033f0aaeedfb3238d9c8d5522c345c04f3f93", [:mix], [{:telemetry, "~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "f854a5e7dbd61e852ee74565d862d606e884425c8867ddaa49c8a6c6f43d832a"},
+
}