···2424use jacquard::CowStr;
2525use jacquard::api::app_bsky::feed::get_timeline::GetTimeline;
2626use jacquard::client::{Agent, FileAuthStore};
2727-use jacquard::oauth::atproto::AtprotoClientMetadata;
2827use jacquard::oauth::client::OAuthClient;
2928use jacquard::oauth::loopback::LoopbackConfig;
3030-use jacquard::oauth::scopes::Scope;
3129use jacquard::types::xrpc::XrpcClient;
3230use miette::IntoDiagnostic;
3331···4644async fn main() -> miette::Result<()> {
4745 let args = Args::parse();
48464949- // File-backed auth store for testing
5050- let store = FileAuthStore::new(&args.store);
5151- let client_data = jacquard_oauth::session::ClientData {
5252- keyset: None,
5353- // Default sets normal localhost redirect URIs and "atproto transition:generic" scopes.
5454- // The localhost helper will ensure you have at least "atproto" and will fix urls
5555- config: AtprotoClientMetadata::default_localhost()
5656- };
5757-5858- // Build an OAuth client
5959- let oauth = OAuthClient::new(store, client_data);
4747+ // Build an OAuth client with file-backed auth store and default localhost config
4848+ let oauth = OAuthClient::with_default_config(FileAuthStore::new(&args.store));
6049 // Authenticate with a PDS, using a loopback server to handle the callback flow
6150 let session = oauth
6251 .login_with_local_server(
···11-//! # Common types for the jacquard implementation of atproto
11+//! Common types for the jacquard implementation of atproto
22//!
33-//! ## Working with Lifetimes and Zero-Copy Deserialization
44-//!
55-//! Jacquard is designed around zero-copy deserialization: types like `Post<'de>` can borrow
66-//! strings and other data directly from the response buffer instead of allocating owned copies.
77-//! This is great for performance, but it creates some interesting challenges when combined with
88-//! async Rust and trait bounds.
33+//! ## Just `.send()` it
94//!
1010-//! ### The Problem: Lifetimes + Async + Traits
55+//! 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.
116//!
1212-//! The naive approach would be to put a lifetime parameter on the trait itself:
1313-//!
1414-//! ```ignore
1515-//! trait XrpcRequest<'de> {
1616-//! type Output: Deserialize<'de>;
1717-//! // ...
1818-//! }
77+//! ```rust
88+//! use jacquard_common::xrpc::XrpcExt;
99+//! use jacquard_common::http_client::HttpClient;
1010+//! // ...
1111+//! let http = reqwest::Client::new();
1212+//! let base = url::Url::parse("https://public.api.bsky.app")?;
1313+//! let resp = http.xrpc(base).send(&request).await?;
1914//! ```
1515+//! 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.
2016//!
2121-//! This looks reasonable until you try to use it in a generic context. If you have a function
2222-//! that works with *any* lifetime, you need a Higher-Ranked Trait Bound (HRTB):
1717+//! >`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.
2318//!
2424-//! ```ignore
2525-//! fn foo<R>(response: &[u8])
2626-//! where
2727-//! R: for<'any> XrpcRequest<'any>
2828-//! {
2929-//! // deserialize from response...
3030-//! }
1919+//! 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.
2020+//!
2121+//! ```rust
2222+//! pub async fn send<'s, R>(
2323+//! self,
2424+//! request: &R,
2525+//! ) -> XrpcResult<Response<<R as XrpcRequest<'s>>::Response>>
2626+//! where
2727+//! R: XrpcRequest<'s>,
2828+//! {
2929+//! let http_request = build_http_request(&self.base, request, &self.opts)
3030+//! .map_err(TransportError::from)?;
3131+//! let http_response = self
3232+//! .client
3333+//! .send_http(http_request)
3434+//! .await
3535+//! .map_err(|e| TransportError::Other(Box::new(e)))?;
3636+//! process_response(http_response)
3737+//! }
3138//! ```
3939+//! >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`.
3240//!
3333-//! The `for<'any>` bound says "this type must implement `XrpcRequest` for *every possible lifetime*",
3434-//! which is effectively the same as requiring `DeserializeOwned`. You've just thrown away your
3535-//! zero-copy optimization, and this also won't work on most of the types in jacquard. The vast
3636-//! majority of them have either a custom Deserialize implementation which will borrow if it
3737-//! can, a #[serde(borrow)] attribute on one or more fields, or an equivalent lifetime bound
3838-//! attribute, associated with the Deserialize derive macro.
4141+//! `.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.
3942//!
4040-//! It gets worse with async. If you want to return borrowed data from an async method, where does
4141-//! the lifetime come from? The response buffer needs to outlive the borrow, but the buffer is
4242-//! consumed by the HTTP call. You end up with "cannot infer appropriate lifetime" errors or even
4343-//! more confusing errors because the compiler can't prove the buffer will stay alive. You *could*
4444-//! do some lifetime laundering with `unsafe`, but you don't actually *need* to tell rustc to "trust
4545-//! me, bro", you can, with some cleverness, explain this to the compiler in a way that it can
4646-//! reason about perfectly well.
4343+//! ## Punchcard Instructions
4744//!
4848-//! ### Explaining where the buffer goes to `rustc`: GATs + Method-Level Lifetimes
4545+//! 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.
4946//!
5050-//! The fix is to use Generic Associated Types (GATs) on the trait's associated types, while keeping
5151-//! the trait itself lifetime-free:
5252-//!
5353-//! ```ignore
5454-//! trait XrpcResp {
4747+//! ```rust
4848+//! pub trait XrpcRequest<'de>: Serialize + Deserialize<'de> {
4949+//! const NSID: &'static str;
5050+//! /// XRPC method (query/GET or procedure/POST)
5151+//! const METHOD: XrpcMethod;
5252+//! type Response: XrpcResp;
5353+//! /// Encode the request body for procedures.
5454+//! fn encode_body(&self) -> Result<Vec<u8>, EncodeError> {
5555+//! Ok(serde_json::to_vec(self)?)
5656+//! }
5757+//! /// Decode the request body for procedures. (Used server-side)
5858+//! fn decode_body(body: &'de [u8]) -> Result<Box<Self>, DecodeError> {
5959+//! let body: Self = serde_json::from_slice(body).map_err(|e| DecodeError::Json(e))?;
6060+//! Ok(Box::new(body))
6161+//! }
6262+//! }
6363+//! pub trait XrpcResp {
5564//! const NSID: &'static str;
5656-//!
5757-//! // GATs: lifetime is on the associated type, not the trait
6565+//! /// Output encoding (MIME type)
6666+//! const ENCODING: &'static str;
5867//! type Output<'de>: Deserialize<'de> + IntoStatic;
5959-//! type Err<'de>: Deserialize<'de> + IntoStatic;
6868+//! type Err<'de>: Error + Deserialize<'de> + IntoStatic;
6069//! }
6170//! ```
7171+//! 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.
6272//!
6363-//! Now you can write trait bounds without HRTBs:
7373+//! ```rust
7474+//! pub struct Response<R: XrpcResp> {
7575+//! buffer: Bytes,
7676+//! status: StatusCode,
7777+//! _marker: PhantomData<R>,
7878+//! }
6479//!
6565-//! ```ignore
6666-//! fn foo<R: XrpcResp>(response: &[u8]) {
6767-//! // Compiler can pick a concrete lifetime for R::Output<'_>
8080+//! impl<R: XrpcResp> Response<R> {
8181+//! pub fn parse<'s>(
8282+//! &'s self
8383+//! ) -> Result<<Resp as XrpcResp>::Output<'s>, XrpcError<<Resp as XrpcResp>::Err<'s>>> {
8484+//! // Borrowed parsing into Output or Err
8585+//! }
8686+//! pub fn into_output(
8787+//! self
8888+//! ) -> Result<<Resp as XrpcResp>::Output<'static>, XrpcError<<Resp as XrpcResp>::Err<'static>>>
8989+//! where ...
9090+//! { /* Owned parsing into Output or Err */ }
6891//! }
6992//! ```
9393+//! 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.
7094//!
7171-//! Methods that need lifetimes use method-level generic parameters:
7272-//!
7373-//! ```ignore
7474-//! // This is part of a trait from jacquard itself, used to genericize updates to the Bluesky
7575-//! // preferences union, so that if you implement a similar lexicon type in your AppView or App
7676-//! // Server API, you don't have to special-case it.
9595+//! ## Working with Lifetimes and Zero-Copy Deserialization
7796//!
7878-//! trait VecUpdate {
7979-//! type GetRequest<'de>: XrpcRequest<'de>; // GAT
8080-//! type PutRequest<'de>: XrpcRequest<'de>; // GAT
8181-//!
8282-//! // Method-level lifetime, not trait-level
8383-//! fn extract_vec<'s>(
8484-//! output: <Self::GetRequest<'s> as XrpcRequest<'s>>::Output<'s>
8585-//! ) -> Vec<Self::Item>;
8686-//! }
8787-//! ```
9797+//! 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?
8898//!
8989-//! The compiler can monomorphize for concrete lifetimes instead of trying to prove bounds hold
9090-//! for *all* lifetimes at once.
9999+//! The naive approach would be to put a lifetime parameter on the trait itself:
91100//!
9292-//! ### Handling Async with `Response<R: XrpcResp>`
101101+//!```ignore
102102+//!// Note: I actually DO do this for XrpcRequest as you can see above,
103103+//!// because it is implemented on the request parameter struct, which has this
104104+//!// sort of lifetime bound inherently, and we need it to implement Deserialize
105105+//!// for server-side handling.
106106+//!trait NaiveXrpcRequest<'de> {
107107+//! type Output: Deserialize<'de>;
108108+//! // ...
109109+//!}
110110+//!```
93111//!
9494-//! For the async problem, we use a wrapper type that owns the response buffer:
112112+//! 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:
95113//!
9696-//! ```ignore
9797-//! pub struct Response<R: XrpcResp> {
9898-//! buffer: Bytes, // Refcounted, cheap to clone
9999-//! status: StatusCode,
100100-//! _marker: PhantomData<R>,
101101-//! }
102102-//! ```
114114+//!```ignore
115115+//!fn parse<R>(response: &[u8]) ... // return type
116116+//!where
117117+//! R: for<'any> XrpcRequest<'any>
118118+//!{ /* deserialize from response... */ }
119119+//!```
103120//!
104104-//! This lets async methods return a `Response` that owns its buffer, then the *caller* decides
105105-//! the lifetime strategy:
121121+//! 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.
106122//!
107107-//! ```ignore
108108-//! // Zero-copy: borrow from the owned buffer
109109-//! let output: R::Output<'_> = response.parse()?;
123123+//! 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.
110124//!
111111-//! // Owned: convert to 'static via IntoStatic
112112-//! let output: R::Output<'static> = response.into_output()?;
113113-//! ```
125125+//!```ignore
126126+//!fn parse<'s, R: XrpcRequest<'s>>(response: &'s [u8]) ... // return type with the same lifetime
127127+//!{ /* deserialize from response... */ }
128128+//!```
114129//!
115115-//! The async method doesn't need to know or care about lifetimes - it just returns the `Response`.
116116-//! The caller gets full control over whether to use borrowed or owned data. It can even decide
117117-//! after the fact that it doesn't want to parse out the API response type that it asked for. Instead
118118-//! it can call `.parse_data()` or `.parse_raw()` on the response to get loosely typed, validated
119119-//! data or minimally typed maximally accepting data values out.
130130+//! 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.
120131//!
121121-//! ### Example: XRPC Traits in Practice
132132+//! ### Explaining where the buffer goes to `rustc`
122133//!
123123-//! Here's how the pattern works with the XRPC layer:
134134+//! The fix is to use Generic Associated Types (GATs) on the trait's associated types, while keeping the trait itself lifetime-free:
124135//!
125125-//! ```ignore
126126-//! // XrpcResp uses GATs, not trait-level lifetime
127127-//! trait XrpcResp {
128128-//! const NSID: &'static str;
129129-//! type Output<'de>: Deserialize<'de> + IntoStatic;
130130-//! type Err<'de>: Deserialize<'de> + IntoStatic;
131131-//! }
136136+//!```ignore
137137+//!pub trait XrpcResp {
138138+//! const NSID: &'static str;
139139+//! /// Output encoding (MIME type)
140140+//! const ENCODING: &'static str;
141141+//! type Output<'de>: Deserialize<'de> + IntoStatic;
142142+//! type Err<'de>: Error + Deserialize<'de> + IntoStatic;
143143+//!}
144144+//!```
132145//!
133133-//! // Response owns the buffer (Bytes is refcounted)
134134-//! pub struct Response<R: XrpcResp> {
135135-//! buffer: Bytes,
136136-//! status: StatusCode,
137137-//! _marker: PhantomData<R>,
138138-//! }
146146+//!Now you can write trait bounds without HRTBs, and with lifetime bounds that are actually possible for Jacquard's borrowed deserializing types to meet:
139147//!
140140-//! impl<R: XrpcResp> Response<R> {
141141-//! // Borrow from owned buffer
142142-//! pub fn parse(&self) -> XrpcResult<R::Output<'_>> {
143143-//! serde_json::from_slice(&self.buffer)
144144-//! }
148148+//!```ignore
149149+//!fn parse<'s, R: XrpcResp>(response: &'s [u8]) /* return type with same lifetime */ {
150150+//! // Compiler can pick a concrete lifetime for R::Output<'_> or have it specified easily
151151+//!}
152152+//!```
145153//!
146146-//! // Convert to fully owned
147147-//! pub fn into_output(self) -> XrpcResult<R::Output<'static>> {
148148-//! let borrowed = self.parse()?;
149149-//! Ok(borrowed.into_static())
150150-//! }
151151-//! }
154154+//!Methods that need lifetimes use method-level generic parameters:
152155//!
153153-//! // Async method returns Response, caller chooses strategy
154154-//! async fn send_xrpc<Req>(&self, req: Req) -> Result<Response<Req::Response>>
155155-//! where
156156-//! Req: XrpcRequest<'_>
157157-//! {
158158-//! // Do HTTP call, get Bytes buffer
159159-//! // Return Response wrapping that buffer
160160-//! // No lifetime issues - Response owns the buffer
161161-//! }
156156+//!```ignore
157157+//!// This is part of a trait from jacquard itself, used to genericize updates to things like the Bluesky
158158+//!// preferences union, so that if you implement a similar lexicon type in your app, you don't have
159159+//!// to special-case it. Instead you can do a relatively simple trait implementation and then call
160160+//!// .update_vec() with a modifier function or .update_vec_item() with a single item you want to set.
161161+//
162162+//!pub trait VecUpdate {
163163+//! type GetRequest<'de>: XrpcRequest<'de>; //GAT
164164+//! type PutRequest<'de>: XrpcRequest<'de>; //GAT
165165+//! //... more stuff
166166+//
167167+//! //Method-level lifetime, not trait-level
168168+//! fn extract_vec<'s>(
169169+//! output: <Self::GetRequest<'s> as XrpcRequest<'s>>::Output<'s>
170170+//! ) -> Vec<Self::Item>;
171171+//! //... more stuff
172172+//!}
173173+//!```
162174//!
163163-//! // Usage:
164164-//! let response = send_xrpc(request).await?;
175175+//!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:
165176//!
166166-//! // Zero-copy: borrow from response buffer
167167-//! let output = response.parse()?; // Output<'_> borrows from response
177177+//!```ignore
178178+//!// Zero-copy: borrow from the owned buffer
179179+//!let output: R::Output<'_> = response.parse()?;
180180+//
181181+//!// Owned: convert to 'static via IntoStatic
182182+//!let output: R::Output<'static> = response.into_output()?;
183183+//!```
168184//!
169169-//! // Or owned: convert to 'static
170170-//! let output = response.into_output()?; // Output<'static> is fully owned
171171-//! ```
185185+//! 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.
172186//!
173187//! When you see types like `Response<R: XrpcResp>` or methods with lifetime parameters,
174188//! 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
···317317 .await
318318 .map_err(|e| crate::error::TransportError::Other(Box::new(e)))?;
319319320320- let status = http_response.status();
321321- // If the server returned 401 with a WWW-Authenticate header, expose it so higher layers
322322- // (e.g., DPoP handling) can detect `error="invalid_token"` and trigger refresh.
323323- if status.as_u16() == 401 {
324324- if let Some(hv) = http_response.headers().get(http::header::WWW_AUTHENTICATE) {
325325- return Err(crate::error::ClientError::Auth(
326326- crate::error::AuthError::Other(hv.clone()),
327327- ));
328328- }
329329- }
330330- let buffer = Bytes::from(http_response.into_body());
331331-332332- if !status.is_success() && !matches!(status.as_u16(), 400 | 401) {
333333- return Err(crate::error::HttpError {
334334- status,
335335- body: Some(buffer),
336336- }
337337- .into());
338338- }
339339-340340- Ok(Response::new(buffer, status))
320320+ process_response(http_response)
341321 }
342322}
343323
···3434pub use jacquard_common::error::{ClientError, XrpcResult};
3535use jacquard_common::http_client::HttpClient;
3636pub use jacquard_common::session::{MemorySessionStore, SessionStore, SessionStoreError};
3737-use jacquard_common::types::blob::{BlobRef, MimeType};
3737+use jacquard_common::types::blob::{Blob, MimeType};
3838use jacquard_common::types::collection::Collection;
3939use jacquard_common::types::recordkey::{RecordKey, Rkey};
4040use jacquard_common::types::string::AtUri;
···395395 ///
396396 /// The collection is inferred from the type parameter.
397397 /// The repo is automatically filled from the session info.
398398- pub async fn delete_record<R, K>(
398398+ pub async fn delete_record<R>(
399399 &self,
400400- rkey: K,
400400+ rkey: RecordKey<Rkey<'_>>,
401401 ) -> Result<DeleteRecordOutput<'static>, AgentError>
402402 where
403403 R: Collection,
404404- K: Into<RecordKey<Rkey<'static>>>,
405404 {
406405 use jacquard_api::com_atproto::repo::delete_record::DeleteRecord;
407406 use jacquard_common::types::ident::AtIdentifier;
···411410 let request = DeleteRecord::new()
412411 .repo(AtIdentifier::Did(did))
413412 .collection(R::nsid())
414414- .rkey(rkey.into())
413413+ .rkey(rkey)
415414 .build();
416415417416 let response = self.send(request).await?;
···491490 &self,
492491 data: impl Into<bytes::Bytes>,
493492 mime_type: MimeType<'_>,
494494- ) -> Result<BlobRef<'static>, AgentError> {
493493+ ) -> Result<Blob<'static>, AgentError> {
495494 use http::header::CONTENT_TYPE;
496495 use jacquard_api::com_atproto::repo::upload_blob::UploadBlob;
497496···522521 error: Box::new(typed),
523522 },
524523 })?;
525525- Ok(BlobRef::Blob(output.blob.into_static()))
524524+ Ok(output.blob.into_static())
526525 }
527526528527 /// Update a vec-based data structure with a fetch-modify-put pattern.
-2
crates/jacquard/src/lib.rs
···2525//! # use clap::Parser;
2626//! # use jacquard::CowStr;
2727//! use jacquard::api::app_bsky::feed::get_timeline::GetTimeline;
2828-//! use jacquard::client::credential_session::{CredentialSession, SessionKey};
2928//! use jacquard::client::{Agent, FileAuthStore};
3030-//! use jacquard::oauth::atproto::AtprotoClientMetadata;
3129//! use jacquard::oauth::client::OAuthClient;
3230//! use jacquard::xrpc::XrpcClient;
3331//! # #[cfg(feature = "loopback")]
···11use clap::Parser;
22+use jacquard::CowStr;
23use jacquard::api::app_bsky::embed::images::{Image, Images};
34use jacquard::api::app_bsky::feed::post::{Post, PostEmbed};
45use jacquard::client::{Agent, FileAuthStore};
···89use jacquard::types::blob::MimeType;
910use jacquard::types::string::Datetime;
1011use jacquard::xrpc::XrpcClient;
1111-use jacquard::CowStr;
1212use miette::IntoDiagnostic;
1313use std::path::PathBuf;
1414···5959 };
6060 let mime_type = MimeType::new_static(mime_str);
61616262- println!("📤 Uploading image...");
6363- let blob_ref = agent.upload_blob(image_data, mime_type).await?;
6464-6565- // Extract the Blob from the BlobRef
6666- let blob = match blob_ref {
6767- jacquard::types::blob::BlobRef::Blob(b) => b,
6868- _ => miette::bail!("Expected Blob, got LegacyBlob"),
6969- };
6262+ println!("Uploading image...");
6363+ let blob = agent.upload_blob(image_data, mime_type).await?;
70647165 // Create post with image embed
7266 let post = Post {
···9185 };
92869387 let output = agent.create_record(post, None).await?;
9494- println!("✓ Created post with image: {}", output.uri);
8888+ println!("Created post with image: {}", output.uri);
95899690 Ok(())
9791}
+1-1
examples/public_atproto_feed.rs
···2121 let response = http.xrpc(base).send(&request).await?;
2222 let output = response.into_output()?;
23232424- println!("📰 Latest posts from the AT Protocol feed:\n");
2424+ println!("Latest posts from the AT Protocol feed:\n");
2525 for (i, item) in output.feed.iter().enumerate() {
2626 // Deserialize the post record from the Data type
2727 let post: Post = from_data(&item.post.record).into_diagnostic()?;