Something went wrong. Try again.
ATProto utilities for the Ash Framework forked from lekkice.moe/ash-atproto
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322defmodule AshAtproto.DataLayer do @behaviour Ash.DataLayer
alias Ash.{Error, Query, Changeset} alias Spark.Dsl.Extension alias AshAtproto.DataLayer.{Dsl, Info} alias AshAtproto.XRPC.OAuthClient
alias Atex.IdentityResolver alias Atex.DID.Document
use Extension, sections: Dsl.sections()
@default_limit 50 @max_limit 100
@impl true def can?(_, :create), do: true def can?(_, :destroy), do: true def can?(_, :read), do: true def can?(_, :limit), do: true def can?(_, :sort), do: true def can?(_, {:sort, :string}), do: true def can?(_, :keyset), do: true
# XRPC endpoint doesn't support filters, but it's needed for `Ash.get/2` def can?(_, :filter), do: true def can?(_, {:filter_expr, %{operator: :==}}), do: true
def can?(_, :composite_primary_key), do: true
def can?(_, _), do: false
@impl true def data_layer_keyset_by_default?(), do: true
@impl true def create(resource, changeset) do # TODO handle error {:ok, client} = get_client_from_actor(changeset)
record_type = Info.atproto_repo_record_type!(resource)
payload = changeset.attributes |> Map.drop([:rkey, :repo_did, :cid]) |> Map.put("$type", record_type)
params = %{ repo: client.resource.did, collection: record_type, record: payload }
# TODO resource override? case OAuthClient.post(client, "com.atproto.repo.createRecord", json: params) do {:ok, %{status: 200, body: body}, _client} -> {:ok, %{rkey: rkey}} = get_uri_data(body["uri"])
record = changeset.data |> Map.merge(changeset.attributes) |> Map.merge(%{ repo_did: client.resource.did, rkey: rkey, cid: body["cid"] }) |> set_loaded()
{:ok, record}
{:error, response, _client} -> {:error, Error.to_ash_error("Failed to create: #{inspect(response.body)}")} end end
@impl true def destroy(resource, changeset) do case get_client_from_actor(changeset) do {:ok, client} -> record_type = Info.atproto_repo_record_type!(resource)
rkey = changeset.data.rkey
params = %{ repo: client.resource.did, collection: record_type, rkey: rkey }
case OAuthClient.post(client, "com.atproto.repo.deleteRecord", json: params) do {:ok, %{status: 200}, _client} -> :ok
{:error, response, _client} -> {:error, Ash.Error.to_ash_error("Failed to destroy: #{inspect(response.body)}")} end
{:error, reason} -> {:error, reason} end end
@impl true def run_query(query, resource, _parent \\ nil)
# query using uri def run_query(%Query{context: %{atproto_uri: target_uri}} = query, resource, parent) do case get_uri_data(target_uri) do {:ok, %{authority: repo_did, rkey: rkey}} -> context_without_uri = Map.delete(query.context, :atproto_uri)
query_with_context = %{query | context: context_without_uri} |> Ash.Query.set_context(%{repo_did: repo_did, rkey: rkey})
run_query(query_with_context, resource, parent)
{:error, error} -> {:error, error} end end
# query for a single record def run_query(%Query{context: %{repo_did: repo_did, rkey: rkey}}, resource, _parent) do record_type = AshAtproto.DataLayer.Info.atproto_repo_record_type!(resource) pds_url = get_pds_endpoint!(repo_did)
params = [ repo: repo_did, collection: record_type, rkey: rkey ]
case Atex.XRPC.unauthed_get(pds_url, "com.atproto.repo.getRecord", params: params) do {:ok, %{status: 200, body: body}} -> valid_attributes = Ash.Resource.Info.attributes(resource)
record = body |> map_to_record(resource, valid_attributes)
{:ok, [record]}
{:error, reason} -> {:error, Ash.Error.to_ash_error(reason)} end end
# query for `Ash.get/2` def run_query( %Query{ filter: %Ash.Filter.Simple{ predicates: predicates } } = query, resource, parent ) do extracted_context = Enum.reduce(predicates, %{}, fn %{operator: :==, left: %{attribute: %{name: :repo_did}}, right: repo_did}, acc -> Map.put(acc, :repo_did, repo_did)
%{operator: :==, left: %{attribute: %{name: :rkey}}, right: rkey}, acc -> Map.put(acc, :rkey, rkey)
_other, acc -> acc end)
query_with_context = %{query | filter: nil} |> Ash.Query.set_context(extracted_context)
run_query(query_with_context, resource, parent) end
# query for a list of records def run_query(%Query{} = query, resource, _parent) do target_repo_did = query.context[:repo_did] || get_did_from_actor(query)
if is_nil(target_repo_did) do {:error, Error.Query.InvalidQuery.exception( message: "The context must include the `:repo_did` to read from atproto." )} else pds_url = get_pds_endpoint!(target_repo_did) record_type = AshAtproto.DataLayer.Info.atproto_repo_record_type!(resource)
page_opts = query.context[:data_layer][:keyset_opts] || [] cursor = page_opts[:after]
params = [ repo: target_repo_did, collection: record_type, limit: min(query.limit || @default_limit, @max_limit) ]
params = if cursor, do: Keyword.put(params, :cursor, cursor), else: params
params = if query.context[:atproto_reverse], do: Keyword.put(params, :reverse, true), else: params
case Atex.XRPC.unauthed_get(pds_url, "com.atproto.repo.listRecords", params: params) do {:ok, %{status: 200, body: body}} -> valid_attributes = Ash.Resource.Info.attributes(resource)
records = body["records"] |> Enum.map(fn item -> map_to_record(item, resource, valid_attributes, body["cursor"]) end)
{:ok, records}
{:error, reason} -> {:error, Ash.Error.to_ash_error(reason)} end end end
@impl true def resource_to_query(resource, domain), do: %Query{resource: resource, domain: domain}
@impl true def limit(query, limit, _), do: {:ok, %Query{query | limit: limit}} @impl true def sort(query, sort, _resource), do: {:ok, %Query{query | sort: sort}} @impl true def set_context(_resource, query, context), do: {:ok, %Query{query | context: context}} @impl true def filter(query, filter, _resource), do: {:ok, %Query{query | filter: filter}}
# --- Helpers --- defp set_loaded(record), do: %{record | __meta__: %Ecto.Schema.Metadata{state: :loaded, schema: record.__struct__}}
defp get_client_from_actor(%Changeset{} = changeset) do case changeset.context[:private][:actor] do nil -> {:error, Error.to_ash_error("Authentication required: You must pass `actor: user` to Ash.create!")}
user_resource -> OAuthClient.new(user_resource) end end
defp get_did_from_actor(%{context: %{private: %{actor: %{did: did}}}}) when not is_nil(did), do: did
defp get_did_from_actor(_), do: nil
defp get_pds_endpoint!(did) do case IdentityResolver.resolve(did) do {:ok, identity} -> Document.get_pds_endpoint(identity.document)
{:error, reason} -> raise "Could not resolve PDS endpoint for DID #{did}: #{inspect(reason)}" end end
defp get_uri_data("at://" <> path) do [clean_path | _] = String.split(path, ["?", "#"])
case String.split(clean_path, "/") do [authority, _collection, rkey] -> {:ok, %{ authority: authority, rkey: rkey }}
_ -> {:error, :invalid_uri_structure} end end
defp get_uri_data(_invalid_uri) do {:error, :invalid_scheme} end
defp map_to_record(map, resource, valid_attributes, cursor \\ nil) do raw_json = map["value"] || %{}
{:ok, %{authority: target_repo_did, rkey: rkey}} = get_uri_data(map["uri"])
base_attrs = %{ repo_did: target_repo_did, rkey: rkey, cid: map["cid"], uri: map["uri"] }
safe_attrs = Enum.reduce(valid_attributes, base_attrs, fn attribute, acc -> json_key = to_string(attribute.source || attribute.name)
if Map.has_key?(raw_json, json_key) do case Ash.Type.cast_stored( attribute.type, raw_json[json_key], attribute.constraints ) do {:ok, value} -> Map.put(acc, attribute.name, value) :error -> acc end else acc end end)
Kernel.struct(resource, safe_attrs) |> Ash.Resource.put_metadata(:keyset, cursor) endend