A better Rust ATProto crate

rewrote big explainer doc comment

Orual 8df60270 0da48a57

Changed files
+193 -215
crates
jacquard
jacquard-api
src
app_bsky
jacquard-common
examples
+2 -13
README.md
···
use jacquard::CowStr;
use jacquard::api::app_bsky::feed::get_timeline::GetTimeline;
use jacquard::client::{Agent, FileAuthStore};
-
use jacquard::oauth::atproto::AtprotoClientMetadata;
use jacquard::oauth::client::OAuthClient;
use jacquard::oauth::loopback::LoopbackConfig;
-
use jacquard::oauth::scopes::Scope;
use jacquard::types::xrpc::XrpcClient;
use miette::IntoDiagnostic;
···
async fn main() -> miette::Result<()> {
let args = Args::parse();
-
// File-backed auth store for testing
-
let store = FileAuthStore::new(&args.store);
-
let client_data = jacquard_oauth::session::ClientData {
-
keyset: None,
-
// Default sets normal localhost redirect URIs and "atproto transition:generic" scopes.
-
// The localhost helper will ensure you have at least "atproto" and will fix urls
-
config: AtprotoClientMetadata::default_localhost()
-
};
-
-
// Build an OAuth client
-
let oauth = OAuthClient::new(store, client_data);
// Authenticate with a PDS, using a loopback server to handle the callback flow
let session = oauth
.login_with_local_server(
···
use jacquard::CowStr;
use jacquard::api::app_bsky::feed::get_timeline::GetTimeline;
use jacquard::client::{Agent, FileAuthStore};
use jacquard::oauth::client::OAuthClient;
use jacquard::oauth::loopback::LoopbackConfig;
use jacquard::types::xrpc::XrpcClient;
use miette::IntoDiagnostic;
···
async fn main() -> miette::Result<()> {
let args = Args::parse();
+
// Build an OAuth client with file-backed auth store and default localhost config
+
let oauth = OAuthClient::with_default_config(FileAuthStore::new(&args.store));
// Authenticate with a PDS, using a loopback server to handle the callback flow
let session = oauth
.login_with_local_server(
+3 -9
crates/jacquard-api/src/app_bsky/feed/get_timeline.rs
···
PartialEq,
Eq,
bon::Builder,
-
jacquard_derive::IntoStatic
)]
#[builder(start_fn = new)]
#[serde(rename_all = "camelCase")]
···
#[jacquard_derive::lexicon]
#[derive(
-
serde::Serialize,
-
serde::Deserialize,
-
Debug,
-
Clone,
-
PartialEq,
-
Eq,
-
jacquard_derive::IntoStatic
)]
#[serde(rename_all = "camelCase")]
pub struct GetTimelineOutput<'a> {
···
const METHOD: jacquard_common::xrpc::XrpcMethod = jacquard_common::xrpc::XrpcMethod::Query;
type Request<'de> = GetTimeline<'de>;
type Response = GetTimelineResponse;
-
}
···
PartialEq,
Eq,
bon::Builder,
+
jacquard_derive::IntoStatic,
)]
#[builder(start_fn = new)]
#[serde(rename_all = "camelCase")]
···
#[jacquard_derive::lexicon]
#[derive(
+
serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq, jacquard_derive::IntoStatic,
)]
#[serde(rename_all = "camelCase")]
pub struct GetTimelineOutput<'a> {
···
const METHOD: jacquard_common::xrpc::XrpcMethod = jacquard_common::xrpc::XrpcMethod::Query;
type Request<'de> = GetTimeline<'de>;
type Response = GetTimelineResponse;
+
}
+146 -132
crates/jacquard-common/src/lib.rs
···
-
//! # Common types for the jacquard implementation of atproto
//!
-
//! ## Working with Lifetimes and Zero-Copy Deserialization
-
//!
-
//! Jacquard is designed around zero-copy deserialization: types like `Post<'de>` can borrow
-
//! strings and other data directly from the response buffer instead of allocating owned copies.
-
//! This is great for performance, but it creates some interesting challenges when combined with
-
//! async Rust and trait bounds.
//!
-
//! ### The Problem: Lifetimes + Async + Traits
//!
-
//! The naive approach would be to put a lifetime parameter on the trait itself:
-
//!
-
//! ```ignore
-
//! trait XrpcRequest<'de> {
-
//! type Output: Deserialize<'de>;
-
//! // ...
-
//! }
//! ```
//!
-
//! This looks reasonable until you try to use it in a generic context. If you have a function
-
//! that works with *any* lifetime, you need a Higher-Ranked Trait Bound (HRTB):
//!
-
//! ```ignore
-
//! fn foo<R>(response: &[u8])
-
//! where
-
//! R: for<'any> XrpcRequest<'any>
-
//! {
-
//! // deserialize from response...
-
//! }
//! ```
//!
-
//! The `for<'any>` bound says "this type must implement `XrpcRequest` for *every possible lifetime*",
-
//! which is effectively the same as requiring `DeserializeOwned`. You've just thrown away your
-
//! zero-copy optimization, and this also won't work on most of the types in jacquard. The vast
-
//! majority of them have either a custom Deserialize implementation which will borrow if it
-
//! can, a #[serde(borrow)] attribute on one or more fields, or an equivalent lifetime bound
-
//! attribute, associated with the Deserialize derive macro.
//!
-
//! It gets worse with async. If you want to return borrowed data from an async method, where does
-
//! the lifetime come from? The response buffer needs to outlive the borrow, but the buffer is
-
//! consumed by the HTTP call. You end up with "cannot infer appropriate lifetime" errors or even
-
//! more confusing errors because the compiler can't prove the buffer will stay alive. You *could*
-
//! do some lifetime laundering with `unsafe`, but you don't actually *need* to tell rustc to "trust
-
//! me, bro", you can, with some cleverness, explain this to the compiler in a way that it can
-
//! reason about perfectly well.
//!
-
//! ### Explaining where the buffer goes to `rustc`: GATs + Method-Level Lifetimes
//!
-
//! The fix is to use Generic Associated Types (GATs) on the trait's associated types, while keeping
-
//! the trait itself lifetime-free:
-
//!
-
//! ```ignore
-
//! trait XrpcResp {
//! const NSID: &'static str;
-
//!
-
//! // GATs: lifetime is on the associated type, not the trait
//! type Output<'de>: Deserialize<'de> + IntoStatic;
-
//! type Err<'de>: Deserialize<'de> + IntoStatic;
//! }
//! ```
//!
-
//! Now you can write trait bounds without HRTBs:
//!
-
//! ```ignore
-
//! fn foo<R: XrpcResp>(response: &[u8]) {
-
//! // Compiler can pick a concrete lifetime for R::Output<'_>
//! }
//! ```
//!
-
//! Methods that need lifetimes use method-level generic parameters:
-
//!
-
//! ```ignore
-
//! // This is part of a trait from jacquard itself, used to genericize updates to the Bluesky
-
//! // preferences union, so that if you implement a similar lexicon type in your AppView or App
-
//! // Server API, you don't have to special-case it.
//!
-
//! trait VecUpdate {
-
//! type GetRequest<'de>: XrpcRequest<'de>; // GAT
-
//! type PutRequest<'de>: XrpcRequest<'de>; // GAT
-
//!
-
//! // Method-level lifetime, not trait-level
-
//! fn extract_vec<'s>(
-
//! output: <Self::GetRequest<'s> as XrpcRequest<'s>>::Output<'s>
-
//! ) -> Vec<Self::Item>;
-
//! }
-
//! ```
//!
-
//! The compiler can monomorphize for concrete lifetimes instead of trying to prove bounds hold
-
//! for *all* lifetimes at once.
//!
-
//! ### Handling Async with `Response<R: XrpcResp>`
//!
-
//! For the async problem, we use a wrapper type that owns the response buffer:
//!
-
//! ```ignore
-
//! pub struct Response<R: XrpcResp> {
-
//! buffer: Bytes, // Refcounted, cheap to clone
-
//! status: StatusCode,
-
//! _marker: PhantomData<R>,
-
//! }
-
//! ```
//!
-
//! This lets async methods return a `Response` that owns its buffer, then the *caller* decides
-
//! the lifetime strategy:
//!
-
//! ```ignore
-
//! // Zero-copy: borrow from the owned buffer
-
//! let output: R::Output<'_> = response.parse()?;
//!
-
//! // Owned: convert to 'static via IntoStatic
-
//! let output: R::Output<'static> = response.into_output()?;
-
//! ```
//!
-
//! The async method doesn't need to know or care about lifetimes - it just returns the `Response`.
-
//! The caller gets full control over whether to use borrowed or owned data. It can even decide
-
//! after the fact that it doesn't want to parse out the API response type that it asked for. Instead
-
//! it can call `.parse_data()` or `.parse_raw()` on the response to get loosely typed, validated
-
//! data or minimally typed maximally accepting data values out.
//!
-
//! ### Example: XRPC Traits in Practice
//!
-
//! Here's how the pattern works with the XRPC layer:
//!
-
//! ```ignore
-
//! // XrpcResp uses GATs, not trait-level lifetime
-
//! trait XrpcResp {
-
//! const NSID: &'static str;
-
//! type Output<'de>: Deserialize<'de> + IntoStatic;
-
//! type Err<'de>: Deserialize<'de> + IntoStatic;
-
//! }
//!
-
//! // Response owns the buffer (Bytes is refcounted)
-
//! pub struct Response<R: XrpcResp> {
-
//! buffer: Bytes,
-
//! status: StatusCode,
-
//! _marker: PhantomData<R>,
-
//! }
//!
-
//! impl<R: XrpcResp> Response<R> {
-
//! // Borrow from owned buffer
-
//! pub fn parse(&self) -> XrpcResult<R::Output<'_>> {
-
//! serde_json::from_slice(&self.buffer)
-
//! }
//!
-
//! // Convert to fully owned
-
//! pub fn into_output(self) -> XrpcResult<R::Output<'static>> {
-
//! let borrowed = self.parse()?;
-
//! Ok(borrowed.into_static())
-
//! }
-
//! }
//!
-
//! // Async method returns Response, caller chooses strategy
-
//! async fn send_xrpc<Req>(&self, req: Req) -> Result<Response<Req::Response>>
-
//! where
-
//! Req: XrpcRequest<'_>
-
//! {
-
//! // Do HTTP call, get Bytes buffer
-
//! // Return Response wrapping that buffer
-
//! // No lifetime issues - Response owns the buffer
-
//! }
//!
-
//! // Usage:
-
//! let response = send_xrpc(request).await?;
//!
-
//! // Zero-copy: borrow from response buffer
-
//! let output = response.parse()?; // Output<'_> borrows from response
//!
-
//! // Or owned: convert to 'static
-
//! let output = response.into_output()?; // Output<'static> is fully owned
-
//! ```
//!
//! When you see types like `Response<R: XrpcResp>` or methods with lifetime parameters,
//! this is the pattern at work. It looks a bit funky, but it's solving a specific problem
···
+
//! 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.
//!
+
//! ```rust
+
//! use jacquard_common::xrpc::XrpcExt;
+
//! use jacquard_common::http_client::HttpClient;
+
//! // ...
+
//! let http = reqwest::Client::new();
+
//! let base = url::Url::parse("https://public.api.bsky.app")?;
+
//! 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.
//!
+
//! >`XrpcClient` implementers don't *have* to implement token auto-refresh and so on, but realistically they *should* implement at least a basic version. There is an `AgentSession` trait which does require full session/state management.
//!
+
//! Here is the entire text of `XrpcCall::send()`. [`build_http_request()`](https://tangled.org/@nonbinary.computer/jacquard/blob/main/crates/jacquard-common/src/xrpc.rs#L400) and [`process_response()`](https://tangled.org/@nonbinary.computer/jacquard/blob/main/crates/jacquard-common/src/xrpc.rs#L344) 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.
+
//!
+
//! ```rust
+
//! pub async fn send<'s, R>(
+
//! self,
+
//! request: &R,
+
//! ) -> XrpcResult<Response<<R as XrpcRequest<'s>>::Response>>
+
//! where
+
//! R: XrpcRequest<'s>,
+
//! {
+
//! 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 `XrpcExt` and `XrpcCall`.
//!
+
//! `.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.
//!
+
//! ```rust
+
//! pub trait XrpcRequest<'de>: Serialize + Deserialize<'de> {
+
//! 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(body: &'de [u8]) -> Result<Box<Self>, DecodeError> {
+
//! 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<'de>: Deserialize<'de> + IntoStatic;
+
//! type Err<'de>: Error + Deserialize<'de> + IntoStatic;
//! }
//! ```
+
//! Here are the implementations for [`GetTimeline`](https://tangled.org/@nonbinary.computer/jacquard/blob/main/crates/jacquard-api/src/app_bsky/feed/get_timeline.rs). 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.
//!
+
//! ```rust
+
//! pub struct Response<R: XrpcResp> {
+
//! buffer: Bytes,
+
//! status: StatusCode,
+
//! _marker: PhantomData<R>,
+
//! }
//!
+
//! impl<R: XrpcResp> Response<R> {
+
//! pub fn parse<'s>(
+
//! &'s self
+
//! ) -> Result<<Resp as XrpcResp>::Output<'s>, XrpcError<<Resp as XrpcResp>::Err<'s>>> {
+
//! // Borrowed parsing into Output or Err
+
//! }
+
//! pub fn into_output(
+
//! self
+
//! ) -> Result<<Resp as XrpcResp>::Output<'static>, XrpcError<<Resp as XrpcResp>::Err<'static>>>
+
//! where ...
+
//! { /* Owned parsing into Output or Err */ }
//! }
//! ```
+
//! You decode the response (or the endpoint-specific error) out of this, borrowing from the buffer or taking ownership so you can drop the buffer. There are two reasons for this. One is separation of concerns. By two-staging the parsing, it's easier to distinguish network and authentication problems from application-level errors. The second is lifetimes and borrowed deserialization.
//!
+
//! ## Working with Lifetimes and Zero-Copy Deserialization
//!
+
//! Jacquard is designed around zero-copy/borrowed deserialization: types like [`Post<'a>`](https://tangled.org/@nonbinary.computer/jacquard/blob/main/crates/jacquard-api/src/app_bsky/feed/post.rs) can borrow strings and other data directly from the response buffer instead of allocating owned copies. This is great for performance, but it creates some interesting challenges, especially in async contexts. So how do you specify the lifetime of the borrow?
//!
+
//! The naive approach would be to put a lifetime parameter on the trait itself:
//!
+
//!```ignore
+
//!// Note: I actually DO do this for XrpcRequest as you can see above,
+
//!// because it is implemented on the request parameter struct, which has this
+
//!// sort of lifetime bound inherently, and we need it to implement Deserialize
+
//!// for server-side handling.
+
//!trait NaiveXrpcRequest<'de> {
+
//! type Output: Deserialize<'de>;
+
//! // ...
+
//!}
+
//!```
//!
+
//! This looks reasonable until you try to use it in a generic context. If you have a function that works with *any* lifetime, you need a Higher-ranked trait bound:
//!
+
//!```ignore
+
//!fn parse<R>(response: &[u8]) ... // return type
+
//!where
+
//! R: for<'any> XrpcRequest<'any>
+
//!{ /* deserialize from response... */ }
+
//!```
//!
+
//! The `for<'any>` bound says "this type must implement `XrpcRequest` for *every possible lifetime*", which, for `Deserialize`, is effectively the same as requiring `DeserializeOwned`. You've probably just thrown away your zero-copy optimization, and furthermore that trait bound just straight-up won't work on most of the types in Jacquard. The vast majority of them have either a custom Deserialize implementation which will borrow if it can, a `#[serde(borrow)]` attribute on one or more fields, or an equivalent lifetime bound attribute, associated with the Deserialize derive macro. You will get "Deserialize implementation not general enough" if you try. And no, you cannot have an additional deserialize implementation for the `'static` lifetime due to how serde works.
//!
+
//! If you instead try something like the below function signature and specify a specific lifetime, it will compile in isolation, but when you go to use it, the Rust compiler will not generally be able to figure out the lifetimes at the call site, and will complain about things being dropped while still borrowed, even if you convert the response to an owned/ `'static` lifetime version of the type.
//!
+
//!```ignore
+
//!fn parse<'s, R: XrpcRequest<'s>>(response: &'s [u8]) ... // return type with the same lifetime
+
//!{ /* deserialize from response... */ }
+
//!```
//!
+
//! It gets worse with async. If you want to return borrowed data from an async method, where does the lifetime come from? The response buffer needs to outlive the borrow, but the buffer is consumed or potentially has to have an unbounded lifetime. You end up with confusing and frustrating errors because the compiler can't prove the buffer will stay alive or that you have taken ownership of the parts of it you care about. You *could* do some lifetime laundering with `unsafe`, but that road leads to potential soundness issues, and besides, you don't actually *need* to tell `rustc` to "trust me, bro", you can, with some cleverness, explain this to the compiler in a way that it can reason about perfectly well.
//!
+
//! ### Explaining where the buffer goes to `rustc`
//!
+
//! The fix is to use Generic Associated Types (GATs) on the trait's associated types, while keeping the trait itself lifetime-free:
//!
+
//!```ignore
+
//!pub trait XrpcResp {
+
//! const NSID: &'static str;
+
//! /// Output encoding (MIME type)
+
//! const ENCODING: &'static str;
+
//! type Output<'de>: Deserialize<'de> + IntoStatic;
+
//! type Err<'de>: Error + Deserialize<'de> + IntoStatic;
+
//!}
+
//!```
//!
+
//!Now you can write trait bounds without HRTBs, and with lifetime bounds that are actually possible for Jacquard's borrowed deserializing types to meet:
//!
+
//!```ignore
+
//!fn parse<'s, R: XrpcResp>(response: &'s [u8]) /* return type with same lifetime */ {
+
//! // Compiler can pick a concrete lifetime for R::Output<'_> or have it specified easily
+
//!}
+
//!```
//!
+
//!Methods that need lifetimes use method-level generic parameters:
//!
+
//!```ignore
+
//!// This is part of a trait from jacquard itself, used to genericize updates to things like the Bluesky
+
//!// preferences union, so that if you implement a similar lexicon type in your app, you don't have
+
//!// to special-case it. Instead you can do a relatively simple trait implementation and then call
+
//!// .update_vec() with a modifier function or .update_vec_item() with a single item you want to set.
+
//
+
//!pub trait VecUpdate {
+
//! type GetRequest<'de>: XrpcRequest<'de>; //GAT
+
//! type PutRequest<'de>: XrpcRequest<'de>; //GAT
+
//! //... more stuff
+
//
+
//! //Method-level lifetime, not trait-level
+
//! fn extract_vec<'s>(
+
//! output: <Self::GetRequest<'s> as XrpcRequest<'s>>::Output<'s>
+
//! ) -> Vec<Self::Item>;
+
//! //... more stuff
+
//!}
+
//!```
//!
+
//!The compiler can monomorphize for concrete lifetimes instead of trying to prove bounds hold for *all* lifetimes at once, or struggle to figure out when you're done with a buffer. `XrpcResp` being separate and lifetime-free lets async methods like `.send()` return a `Response` that owns the response buffer, and then the *caller* decides the lifetime strategy:
//!
+
//!```ignore
+
//!// Zero-copy: borrow from the owned buffer
+
//!let output: R::Output<'_> = response.parse()?;
+
//
+
//!// Owned: convert to 'static via IntoStatic
+
//!let output: R::Output<'static> = response.into_output()?;
+
//!```
//!
+
//! The async method doesn't need to know or care about lifetimes for the most part - it just returns the `Response`. The caller gets full control over whether to use borrowed or owned data. It can even decide after the fact that it doesn't want to parse out the API response type that it asked for. Instead it can call `.parse_data()` or `.parse_raw()` on the response to get loosely typed, validated data or minimally typed maximally accepting data values out.
//!
//! When you see types like `Response<R: XrpcResp>` or methods with lifetime parameters,
//! this is the pattern at work. It looks a bit funky, but it's solving a specific problem
+1 -21
crates/jacquard-common/src/xrpc.rs
···
.await
.map_err(|e| crate::error::TransportError::Other(Box::new(e)))?;
-
let status = http_response.status();
-
// If the server returned 401 with a WWW-Authenticate header, expose it so higher layers
-
// (e.g., DPoP handling) can detect `error="invalid_token"` and trigger refresh.
-
if status.as_u16() == 401 {
-
if let Some(hv) = http_response.headers().get(http::header::WWW_AUTHENTICATE) {
-
return Err(crate::error::ClientError::Auth(
-
crate::error::AuthError::Other(hv.clone()),
-
));
-
}
-
}
-
let buffer = Bytes::from(http_response.into_body());
-
-
if !status.is_success() && !matches!(status.as_u16(), 400 | 401) {
-
return Err(crate::error::HttpError {
-
status,
-
body: Some(buffer),
-
}
-
.into());
-
}
-
-
Ok(Response::new(buffer, status))
}
}
···
.await
.map_err(|e| crate::error::TransportError::Other(Box::new(e)))?;
+
process_response(http_response)
}
}
+17 -14
crates/jacquard/Cargo.toml
···
license.workspace = true
[features]
-
default = ["api_full", "dns", "loopback"]
derive = ["dep:jacquard-derive"]
api = ["jacquard-api/com_atproto", "jacquard-api/com_bad_example" ]
api_bluesky = ["api", "jacquard-api/bluesky" ]
api_full = ["api", "jacquard-api/bluesky", "jacquard-api/other", "jacquard-api/lexicon_community"]
api_all = ["api_full", "jacquard-api/ufos"]
dns = ["jacquard-identity/dns"]
fancy = ["miette/fancy"]
# Propagate loopback to oauth (server + browser helper)
loopback = ["jacquard-oauth/loopback", "jacquard-oauth/browser-open"]
-
[lib]
-
name = "jacquard"
-
path = "src/lib.rs"
[[example]]
name = "oauth_timeline"
path = "../../examples/oauth_timeline.rs"
-
required-features = ["fancy", "loopback", "api_bluesky"]
[[example]]
name = "create_post"
path = "../../examples/create_post.rs"
-
required-features = ["fancy", "loopback", "api_bluesky"]
[[example]]
name = "post_with_image"
path = "../../examples/post_with_image.rs"
-
required-features = ["fancy", "loopback", "api_bluesky"]
[[example]]
name = "update_profile"
path = "../../examples/update_profile.rs"
-
required-features = ["fancy", "loopback", "api_bluesky"]
[[example]]
name = "public_atproto_feed"
···
[[example]]
name = "create_whitewind_post"
path = "../../examples/create_whitewind_post.rs"
-
required-features = ["fancy", "loopback", "api_full"]
[[example]]
-
name = "read_whitewind_posts"
-
path = "../../examples/read_whitewind_posts.rs"
-
required-features = ["fancy", "api_full"]
[[example]]
name = "read_tangled_repo"
path = "../../examples/read_tangled_repo.rs"
-
required-features = ["api_full"]
[[example]]
name = "resolve_did"
path = "../../examples/resolve_did.rs"
[[example]]
name = "update_preferences"
path = "../../examples/update_preferences.rs"
-
required-features = ["fancy", "loopback", "api_full"]
[dependencies]
jacquard-api = { version = "0.4", path = "../jacquard-api" }
···
license.workspace = true
[features]
+
default = ["api_full", "dns", "loopback", "derive"]
derive = ["dep:jacquard-derive"]
+
# Minimal API bindings
api = ["jacquard-api/com_atproto", "jacquard-api/com_bad_example" ]
+
# Bluesky API bindings
api_bluesky = ["api", "jacquard-api/bluesky" ]
+
# Bluesky API bindings, plus a curated selection of community lexicons
api_full = ["api", "jacquard-api/bluesky", "jacquard-api/other", "jacquard-api/lexicon_community"]
+
# All captured generated lexicon API bindings
api_all = ["api_full", "jacquard-api/ufos"]
dns = ["jacquard-identity/dns"]
+
# Pretty debug prints for examples
fancy = ["miette/fancy"]
# Propagate loopback to oauth (server + browser helper)
loopback = ["jacquard-oauth/loopback", "jacquard-oauth/browser-open"]
[[example]]
name = "oauth_timeline"
path = "../../examples/oauth_timeline.rs"
+
required-features = ["fancy"]
[[example]]
name = "create_post"
path = "../../examples/create_post.rs"
+
required-features = ["fancy"]
[[example]]
name = "post_with_image"
path = "../../examples/post_with_image.rs"
+
required-features = ["fancy"]
[[example]]
name = "update_profile"
path = "../../examples/update_profile.rs"
+
required-features = ["fancy"]
[[example]]
name = "public_atproto_feed"
···
[[example]]
name = "create_whitewind_post"
path = "../../examples/create_whitewind_post.rs"
+
required-features = ["fancy", ]
[[example]]
+
name = "read_whitewind_post"
+
path = "../../examples/read_whitewind_post.rs"
+
required-features = ["fancy"]
[[example]]
name = "read_tangled_repo"
path = "../../examples/read_tangled_repo.rs"
+
required-features = ["fancy"]
[[example]]
name = "resolve_did"
path = "../../examples/resolve_did.rs"
+
required-features = ["fancy"]
[[example]]
name = "update_preferences"
path = "../../examples/update_preferences.rs"
+
required-features = ["fancy"]
[dependencies]
jacquard-api = { version = "0.4", path = "../jacquard-api" }
+6 -7
crates/jacquard/src/client.rs
···
pub use jacquard_common::error::{ClientError, XrpcResult};
use jacquard_common::http_client::HttpClient;
pub use jacquard_common::session::{MemorySessionStore, SessionStore, SessionStoreError};
-
use jacquard_common::types::blob::{BlobRef, MimeType};
use jacquard_common::types::collection::Collection;
use jacquard_common::types::recordkey::{RecordKey, Rkey};
use jacquard_common::types::string::AtUri;
···
///
/// The collection is inferred from the type parameter.
/// The repo is automatically filled from the session info.
-
pub async fn delete_record<R, K>(
&self,
-
rkey: K,
) -> Result<DeleteRecordOutput<'static>, AgentError>
where
R: Collection,
-
K: Into<RecordKey<Rkey<'static>>>,
{
use jacquard_api::com_atproto::repo::delete_record::DeleteRecord;
use jacquard_common::types::ident::AtIdentifier;
···
let request = DeleteRecord::new()
.repo(AtIdentifier::Did(did))
.collection(R::nsid())
-
.rkey(rkey.into())
.build();
let response = self.send(request).await?;
···
&self,
data: impl Into<bytes::Bytes>,
mime_type: MimeType<'_>,
-
) -> Result<BlobRef<'static>, AgentError> {
use http::header::CONTENT_TYPE;
use jacquard_api::com_atproto::repo::upload_blob::UploadBlob;
···
error: Box::new(typed),
},
})?;
-
Ok(BlobRef::Blob(output.blob.into_static()))
}
/// Update a vec-based data structure with a fetch-modify-put pattern.
···
pub use jacquard_common::error::{ClientError, XrpcResult};
use jacquard_common::http_client::HttpClient;
pub use jacquard_common::session::{MemorySessionStore, SessionStore, SessionStoreError};
+
use jacquard_common::types::blob::{Blob, MimeType};
use jacquard_common::types::collection::Collection;
use jacquard_common::types::recordkey::{RecordKey, Rkey};
use jacquard_common::types::string::AtUri;
···
///
/// The collection is inferred from the type parameter.
/// The repo is automatically filled from the session info.
+
pub async fn delete_record<R>(
&self,
+
rkey: RecordKey<Rkey<'_>>,
) -> Result<DeleteRecordOutput<'static>, AgentError>
where
R: Collection,
{
use jacquard_api::com_atproto::repo::delete_record::DeleteRecord;
use jacquard_common::types::ident::AtIdentifier;
···
let request = DeleteRecord::new()
.repo(AtIdentifier::Did(did))
.collection(R::nsid())
+
.rkey(rkey)
.build();
let response = self.send(request).await?;
···
&self,
data: impl Into<bytes::Bytes>,
mime_type: MimeType<'_>,
+
) -> Result<Blob<'static>, AgentError> {
use http::header::CONTENT_TYPE;
use jacquard_api::com_atproto::repo::upload_blob::UploadBlob;
···
error: Box::new(typed),
},
})?;
+
Ok(output.blob.into_static())
}
/// Update a vec-based data structure with a fetch-modify-put pattern.
-2
crates/jacquard/src/lib.rs
···
//! # use clap::Parser;
//! # use jacquard::CowStr;
//! use jacquard::api::app_bsky::feed::get_timeline::GetTimeline;
-
//! use jacquard::client::credential_session::{CredentialSession, SessionKey};
//! use jacquard::client::{Agent, FileAuthStore};
-
//! use jacquard::oauth::atproto::AtprotoClientMetadata;
//! use jacquard::oauth::client::OAuthClient;
//! use jacquard::xrpc::XrpcClient;
//! # #[cfg(feature = "loopback")]
···
//! # use clap::Parser;
//! # use jacquard::CowStr;
//! use jacquard::api::app_bsky::feed::get_timeline::GetTimeline;
//! use jacquard::client::{Agent, FileAuthStore};
//! use jacquard::oauth::client::OAuthClient;
//! use jacquard::xrpc::XrpcClient;
//! # #[cfg(feature = "loopback")]
+11 -4
examples/create_whitewind_post.rs
···
use clap::Parser;
use jacquard::api::com_whtwnd::blog::entry::Entry;
use jacquard::client::{Agent, FileAuthStore};
use jacquard::oauth::atproto::AtprotoClientMetadata;
···
use jacquard::oauth::loopback::LoopbackConfig;
use jacquard::types::string::Datetime;
use jacquard::xrpc::XrpcClient;
-
use jacquard::CowStr;
use miette::IntoDiagnostic;
#[derive(Parser, Debug)]
#[command(author, version, about = "Create a WhiteWind blog post")]
···
extra_data: Default::default(),
};
-
let output = agent.create_record(entry, None).await?;
-
println!("✓ Created WhiteWind blog post: {}", output.uri);
-
println!(" View at: https://whtwnd.com/post/{}", output.uri);
Ok(())
}
···
use clap::Parser;
+
use jacquard::CowStr;
use jacquard::api::com_whtwnd::blog::entry::Entry;
use jacquard::client::{Agent, FileAuthStore};
use jacquard::oauth::atproto::AtprotoClientMetadata;
···
use jacquard::oauth::loopback::LoopbackConfig;
use jacquard::types::string::Datetime;
use jacquard::xrpc::XrpcClient;
use miette::IntoDiagnostic;
+
use url::Url;
#[derive(Parser, Debug)]
#[command(author, version, about = "Create a WhiteWind blog post")]
···
extra_data: Default::default(),
};
+
let mut output = agent.create_record(entry, None).await?;
+
println!("Created WhiteWind blog post: {}", output.uri);
+
let url = Url::parse(format!(
+
"https://whtwnd.nat.vg/{}/{}",
+
output.uri.authority(),
+
output.uri.rkey().map(|r| r.as_ref()).unwrap_or("")
+
))
+
.into_diagnostic()?;
+
println!("View at: {}", url);
Ok(())
}
+4 -10
examples/post_with_image.rs
···
use clap::Parser;
use jacquard::api::app_bsky::embed::images::{Image, Images};
use jacquard::api::app_bsky::feed::post::{Post, PostEmbed};
use jacquard::client::{Agent, FileAuthStore};
···
use jacquard::types::blob::MimeType;
use jacquard::types::string::Datetime;
use jacquard::xrpc::XrpcClient;
-
use jacquard::CowStr;
use miette::IntoDiagnostic;
use std::path::PathBuf;
···
};
let mime_type = MimeType::new_static(mime_str);
-
println!("📤 Uploading image...");
-
let blob_ref = agent.upload_blob(image_data, mime_type).await?;
-
-
// Extract the Blob from the BlobRef
-
let blob = match blob_ref {
-
jacquard::types::blob::BlobRef::Blob(b) => b,
-
_ => miette::bail!("Expected Blob, got LegacyBlob"),
-
};
// Create post with image embed
let post = Post {
···
};
let output = agent.create_record(post, None).await?;
-
println!("✓ Created post with image: {}", output.uri);
Ok(())
}
···
use clap::Parser;
+
use jacquard::CowStr;
use jacquard::api::app_bsky::embed::images::{Image, Images};
use jacquard::api::app_bsky::feed::post::{Post, PostEmbed};
use jacquard::client::{Agent, FileAuthStore};
···
use jacquard::types::blob::MimeType;
use jacquard::types::string::Datetime;
use jacquard::xrpc::XrpcClient;
use miette::IntoDiagnostic;
use std::path::PathBuf;
···
};
let mime_type = MimeType::new_static(mime_str);
+
println!("Uploading image...");
+
let blob = agent.upload_blob(image_data, mime_type).await?;
// Create post with image embed
let post = Post {
···
};
let output = agent.create_record(post, None).await?;
+
println!("Created post with image: {}", output.uri);
Ok(())
}
+1 -1
examples/public_atproto_feed.rs
···
let response = http.xrpc(base).send(&request).await?;
let output = response.into_output()?;
-
println!("📰 Latest posts from the AT Protocol feed:\n");
for (i, item) in output.feed.iter().enumerate() {
// Deserialize the post record from the Data type
let post: Post = from_data(&item.post.record).into_diagnostic()?;
···
let response = http.xrpc(base).send(&request).await?;
let output = response.into_output()?;
+
println!("Latest posts from the AT Protocol feed:\n");
for (i, item) in output.feed.iter().enumerate() {
// Deserialize the post record from the Data type
let post: Post = from_data(&item.post.record).into_diagnostic()?;
examples/read_whitewind_posts.rs examples/read_whitewind_post.rs
+2 -2
justfile
···
# Read a WhiteWind blog post
example-whitewind-read *ARGS:
-
cargo run -p jacquard --example read_whitewind_posts --features fancy,api_full -- {{ARGS}}
# Read info about a Tangled git repository
example-tangled-repo *ARGS:
-
cargo run -p jacquard --example read_tangled_repo --features fancy,api_full -- {{ARGS}}
# Resolve a handle to its DID document
example-resolve-did *ARGS:
···
# Read a WhiteWind blog post
example-whitewind-read *ARGS:
+
cargo run -p jacquard --example read_whitewind_posts --features fancy -- {{ARGS}}
# Read info about a Tangled git repository
example-tangled-repo *ARGS:
+
cargo run -p jacquard --example read_tangled_repo --features fancy -- {{ARGS}}
# Resolve a handle to its DID document
example-resolve-did *ARGS: