Expand description
Common types for the jacquard implementation of atproto
§Just .send() it
Jacquard has a couple of .send() methods. One is stateless. it’s the output of a method that creates a request builder, implemented as an extension trait, XrpcExt, on any http client which implements a very simple HttpClient trait. You can use a bare reqwest::Client to make XRPC requests. You call .xrpc(base_url) and get an XrpcCall struct. XrpcCall is a builder, which allows you to pass authentication, atproto proxy settings, labeler headings, and set other options for the final request. There’s also a similar trait DpopExt in the jacquard-oauth crate, which handles that form of authenticated request in a similar way. For basic stuff, this works great, and it’s a useful building block for more complex logic, or when one size does not in fact fit all.
use jacquard_common::xrpc::XrpcExt;
use jacquard_common::http_client::HttpClient;
// ...
let http = reqwest::Client::new();
let base = jacquard_common::deps::fluent_uri::Uri::parse("https://public.api.bsky.app")?.to_owned();
let resp = http.xrpc(base).send(&request).await?;The other, XrpcClient, is stateful, and can be implemented on anything with a bit of internal state to store the base URI (the URL of the PDS being contacted) and the default options. It’s the one you’re most likely to interact with doing normal atproto API client stuff. The Agent struct in the initial example implements that trait, as does the session struct it wraps, and the .send() method used is that trait method.
XrpcClientimplementers don’t have to implement token auto-refresh and so on, but realistically they should implement at least a basic version. There is anAgentSessiontrait which does require full session/state management.
Here is the entire text of XrpcCall::send(). build_http_request() and process_response() are public functions and can be used in other crates. The first does more or less what it says on the tin. The second does less than you might think. It mostly surfaces authentication errors at an earlier level so you don’t have to fully parse the response to know if there was an error or not.
pub async fn send<R>(
self,
request: &R,
) -> XrpcResult<Response<<R as XrpcRequest>::Response>>
where
R: XrpcRequest,
{
let http_request = build_http_request(&self.base, request, &self.opts)
.map_err(TransportError::from)?;
let http_response = self
.client
.send_http(http_request)
.await
.map_err(|e| TransportError::Other(Box::new(e)))?;
process_response(http_response)
}A core goal of Jacquard is to not only provide an easy interface to atproto, but to also make it very easy to build something that fits your needs, and making “helper” functions like those part of the API surface is a big part of that, as are “stateless” implementations like
XrpcExtandXrpcCall.
.send() works for any endpoint and any type that implements the required traits, regardless of what crate it’s defined in. There’s no KnownRecords enum which defines a complete set of known records, and no restriction of Service endpoints in the agent/client, or anything like that, nothing that privileges any set of lexicons or way of working with the library, as much as possible. There’s one primary method and you can put pretty much anything relevant into it. Whatever atproto API you need to call, just .send() it. Okay there are a couple of additional helpers, but we’re focusing on the core one, because pretty much everything else is just wrapping the above send() in one way or another, and they use the same pattern.
§Punchcard Instructions
So how does this work? How does send() and its helper functions know what to do? The answer shouldn’t be surprising to anyone familiar with Rust. It’s traits! Specifically, the following traits, which have generated implementations for every lexicon type ingested by Jacquard’s API code generation, but which honestly aren’t hard to just implement yourself (more tedious than anything). XrpcResp is always implemented on a unit/marker struct with no fields. They provide all the request-specific instructions to the functions.
pub trait XrpcRequest: Serialize {
const NSID: &'static str;
/// XRPC method (query/GET or procedure/POST)
const METHOD: XrpcMethod;
type Response: XrpcResp;
/// Encode the request body for procedures.
fn encode_body(&self) -> Result<Vec<u8>, EncodeError> {
Ok(serde_json::to_vec(self)?)
}
/// Decode the request body for procedures. (Used server-side)
fn decode_body<'de>(body: &'de [u8]) -> Result<Box<Self>, DecodeError>
where
Self: Deserialize<'de>
{
let body: Self = serde_json::from_slice(body).map_err(|e| DecodeError::Json(e))?;
Ok(Box::new(body))
}
}
pub trait XrpcResp {
const NSID: &'static str;
/// Output encoding (MIME type)
const ENCODING: &'static str;
type Output<S: BosStr>;
type Err: Error + Serialize + DeserializeOwned;
}Here are the implementations for GetTimeline. You’ll also note that send() doesn’t return the fully decoded response on success. It returns a Response struct which has a generic parameter that must implement the XrpcResp trait above. Here’s its definition. It’s essentially just a cheaply cloneable byte buffer and a type marker.
pub struct Response<R: XrpcResp> {
buffer: Bytes,
status: StatusCode,
_marker: PhantomData<R>,
}
impl<R: XrpcResp> Response<R> {
pub fn parse<'s, S>(&'s self) -> Result<R::Output<S>, XrpcError<R::Err>>
where
S: BosStr + Deserialize<'s>,
R::Output<S>: Deserialize<'s>,
{
// Parse with the caller's chosen string backing.
}
pub fn into_output(self) -> Result<R::Output<SmolStr>, XrpcError<R::Err>>
where
R::Output<SmolStr>: DeserializeOwned,
{
// Parse into owned/default-backed output.
}
}You decode the response (or the endpoint-specific error) out of this when you are ready. There are two reasons for this. One is separation of concerns: by two-staging the parsing, it is easier to distinguish network and authentication problems from application-level errors. The second is string backing: callers can choose ordinary owned output or explicit borrowed parsing.
§String backing, borrowing, and response parsing
Most generated output types are parameterized over a string backing type: Output<S: BosStr>.
The usual path is owned output:
let output = response.into_output()?;into_output() parses into SmolStr-backed output. This is the convenient default when values
need to be stored, moved independently of the response buffer, or passed through frameworks and
APIs that require DeserializeOwned.
When you specifically want to borrow from the response buffer, choose a borrowed or borrow-or-own backing at parse time:
let output = response.parse::<CowStr<'_>>()?;
let output = response.parse::<&str>()?;Borrowed output works fine across async code as long as the value remains tied to the
buffer-owning Response. The .send() method itself can stay lifetime-free because it returns
that buffer-owning response, and the caller decides whether to parse into owned data or borrow
from the buffer.
XrpcResp stays lifetime-free too. Its success output is a GAT over the backing string type,
and its error type is a plain owned type:
pub trait XrpcResp {
const NSID: &'static str;
const ENCODING: &'static str;
type Output<S: BosStr>;
type Err: Error + Serialize + DeserializeOwned;
}Keeping endpoint errors owned avoids lifetime gymnastics on the unhappy path. If you do not want
to parse the endpoint-specific success type, Response also supports .parse_data() and
.parse_raw() for loosely typed atproto data.
Re-exports§
pub use bos::Bos;pub use bos::BosStr;pub use bos::DefaultStr;pub use bos::FromStaticStr;pub use cowstr::CowStr;pub use into_static::IntoStatic;pub use stream::ByteSink;pub use stream::ByteStream;pub use stream::StreamError;pub use stream::StreamErrorKind;pub use xrpc::StreamingResponse;pub use websocket::CloseCode;pub use websocket::CloseFrame;pub use websocket::WebSocketClient;pub use websocket::WebSocketConnection;pub use websocket::WsMessage;pub use websocket::WsSink;pub use websocket::WsStream;pub use websocket::WsText;pub use websocket::tungstenite_client::TungsteniteClient;pub use types::value::*;
Modules§
- bos
- Borrow-or-share traits for abstracting over owned and borrowed string representations. Borrow-or-share traits for abstracting over owned and borrowed string representations.
- cowstr
- A copy-on-write immutable string type that uses
smol_str::SmolStrfor the “owned” variant. - deps
- Re-exports of external crate dependencies for consistent access across jacquard. Re-exports of external crate dependencies for consistent access across jacquard.
- error
- Error types for XRPC client operations
- http_
client - Minimal HTTP client abstraction shared across crates.
- into_
static - Trait for taking ownership of most borrowed types in jacquard.
- jetstream
- Jetstream subscription support
- macros
atproto!macro.- opt_
serde_ bytes_ helper - Custom serde helpers for bytes::Bytes using serde_bytes
- serde_
bytes_ helper - Custom serde helpers for bytes::Bytes using serde_bytes
- service_
auth - Service authentication JWT parsing and verification for AT Protocol.
- session
- Generic session storage traits and utilities.
- stream
- Stream abstractions for HTTP request/response bodies
- types
- Baseline fundamental AT Protocol data types.
- websocket
- WebSocket client abstraction
- xrpc
- Stateless XRPC utilities and request/response mapping
Macros§
- atproto
- Construct a default-backed atproto
Datavalue from a literal. - format_
smolstr - Formats arguments to a
SmolStr, potentially without allocating. - impl_
bos - Implement
Bosfor types that always borrow from*self.
Structs§
- SmolStr
- A
SmolStris a string type that has the following properties:
Enums§
- Authorization
Token - Authorization token types for XRPC requests.
Traits§
- ToSmol
Str - Convert value to
SmolStrusingfmt::Display, potentially without allocating.
Functions§
- deserialize_
owned - Serde helper for deserializing stuff when you want an owned version
Type Aliases§
- Lazy
- Lazy initialization type for static values.