From 8df6027044ceeaad89cd97e2d0c852564d971771 Mon Sep 17 00:00:00 2001 From: Orual Date: Mon, 13 Oct 2025 14:31:57 -0400 Subject: [PATCH] rewrote big explainer doc comment --- README.md | 15 +- .../src/app_bsky/feed/get_timeline.rs | 12 +- crates/jacquard-common/src/lib.rs | 300 +++++++++--------- crates/jacquard-common/src/xrpc.rs | 22 +- crates/jacquard/Cargo.toml | 31 +- crates/jacquard/src/client.rs | 13 +- crates/jacquard/src/lib.rs | 2 - examples/create_whitewind_post.rs | 15 +- examples/post_with_image.rs | 14 +- examples/public_atproto_feed.rs | 2 +- ...tewind_posts.rs => read_whitewind_post.rs} | 0 justfile | 4 +- 12 files changed, 204 insertions(+), 226 deletions(-) rename examples/{read_whitewind_posts.rs => read_whitewind_post.rs} (100%) diff --git a/README.md b/README.md index 38694e71..d090f023 100644 --- a/README.md +++ b/README.md @@ -24,10 +24,8 @@ use clap::Parser; 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; @@ -46,17 +44,8 @@ struct Args { 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); + // 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( diff --git a/crates/jacquard-api/src/app_bsky/feed/get_timeline.rs b/crates/jacquard-api/src/app_bsky/feed/get_timeline.rs index 3d94849c..65934ece 100644 --- a/crates/jacquard-api/src/app_bsky/feed/get_timeline.rs +++ b/crates/jacquard-api/src/app_bsky/feed/get_timeline.rs @@ -13,7 +13,7 @@ PartialEq, Eq, bon::Builder, - jacquard_derive::IntoStatic + jacquard_derive::IntoStatic, )] #[builder(start_fn = new)] #[serde(rename_all = "camelCase")] @@ -33,13 +33,7 @@ pub struct GetTimeline<'a> { #[jacquard_derive::lexicon] #[derive( - serde::Serialize, - serde::Deserialize, - Debug, - Clone, - PartialEq, - Eq, - jacquard_derive::IntoStatic + serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq, jacquard_derive::IntoStatic, )] #[serde(rename_all = "camelCase")] pub struct GetTimelineOutput<'a> { @@ -74,4 +68,4 @@ impl jacquard_common::xrpc::XrpcEndpoint for GetTimelineRequest { const METHOD: jacquard_common::xrpc::XrpcMethod = jacquard_common::xrpc::XrpcMethod::Query; type Request<'de> = GetTimeline<'de>; type Response = GetTimelineResponse; -} \ No newline at end of file +} diff --git a/crates/jacquard-common/src/lib.rs b/crates/jacquard-common/src/lib.rs index 817ac6ca..40e34791 100644 --- a/crates/jacquard-common/src/lib.rs +++ b/crates/jacquard-common/src/lib.rs @@ -1,136 +1,76 @@ -//! # Common types for the jacquard implementation of atproto +//! 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. +//! ## Just `.send()` it //! -//! ### The Problem: Lifetimes + Async + Traits -//! -//! The naive approach would be to put a lifetime parameter on the trait itself: +//! 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. //! -//! ```ignore -//! trait XrpcRequest<'de> { -//! type Output: Deserialize<'de>; -//! // ... -//! } +//! ```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?; //! ``` -//! -//! 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(response: &[u8]) -//! where -//! R: for<'any> XrpcRequest<'any> -//! { -//! // deserialize from response... -//! } +//! 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>> +//! 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`. //! -//! 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. +//! `.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. //! -//! ### Explaining where the buffer goes to `rustc`: GATs + Method-Level Lifetimes +//! ## Punchcard Instructions //! -//! The fix is to use Generic Associated Types (GATs) on the trait's associated types, while keeping -//! the trait itself lifetime-free: +//! 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. //! -//! ```ignore -//! trait XrpcResp { +//! ```rust +//! pub trait XrpcRequest<'de>: Serialize + Deserialize<'de> { //! 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(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: as XrpcRequest<'s>>::Output<'s> -//! ) -> Vec; -//! } -//! ``` -//! -//! The compiler can monomorphize for concrete lifetimes instead of trying to prove bounds hold -//! for *all* lifetimes at once. -//! -//! ### Handling Async with `Response` -//! -//! For the async problem, we use a wrapper type that owns the response buffer: -//! -//! ```ignore -//! pub struct Response { -//! buffer: Bytes, // Refcounted, cheap to clone -//! status: StatusCode, -//! _marker: PhantomData, +//! /// XRPC method (query/GET or procedure/POST) +//! const METHOD: XrpcMethod; +//! type Response: XrpcResp; +//! /// Encode the request body for procedures. +//! fn encode_body(&self) -> Result, EncodeError> { +//! Ok(serde_json::to_vec(self)?) +//! } +//! /// Decode the request body for procedures. (Used server-side) +//! fn decode_body(body: &'de [u8]) -> Result, DecodeError> { +//! let body: Self = serde_json::from_slice(body).map_err(|e| DecodeError::Json(e))?; +//! Ok(Box::new(body)) +//! } //! } -//! ``` -//! -//! 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 { +//! pub trait XrpcResp { //! const NSID: &'static str; +//! /// Output encoding (MIME type) +//! const ENCODING: &'static str; //! type Output<'de>: Deserialize<'de> + IntoStatic; -//! type Err<'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. //! -//! // Response owns the buffer (Bytes is refcounted) +//! ```rust //! pub struct Response { //! buffer: Bytes, //! status: StatusCode, @@ -138,37 +78,111 @@ //! } //! //! impl Response { -//! // Borrow from owned buffer -//! pub fn parse(&self) -> XrpcResult> { -//! serde_json::from_slice(&self.buffer) -//! } -//! -//! // Convert to fully owned -//! pub fn into_output(self) -> XrpcResult> { -//! let borrowed = self.parse()?; -//! Ok(borrowed.into_static()) +//! pub fn parse<'s>( +//! &'s self +//! ) -> Result<::Output<'s>, XrpcError<::Err<'s>>> { +//! // Borrowed parsing into Output or Err //! } +//! pub fn into_output( +//! self +//! ) -> Result<::Output<'static>, XrpcError<::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. //! -//! // Async method returns Response, caller chooses strategy -//! async fn send_xrpc(&self, req: Req) -> Result> -//! where -//! Req: XrpcRequest<'_> -//! { -//! // Do HTTP call, get Bytes buffer -//! // Return Response wrapping that buffer -//! // No lifetime issues - Response owns the buffer -//! } +//! ## Working with Lifetimes and Zero-Copy Deserialization //! -//! // Usage: -//! let response = send_xrpc(request).await?; +//! 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? //! -//! // Zero-copy: borrow from response buffer -//! let output = response.parse()?; // Output<'_> borrows from response +//! The naive approach would be to put a lifetime parameter on the trait itself: //! -//! // Or owned: convert to 'static -//! let output = response.into_output()?; // Output<'static> is fully owned -//! ``` +//!```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(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: as XrpcRequest<'s>>::Output<'s> +//! ) -> Vec; +//! //... 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` or methods with lifetime parameters, //! this is the pattern at work. It looks a bit funky, but it's solving a specific problem diff --git a/crates/jacquard-common/src/xrpc.rs b/crates/jacquard-common/src/xrpc.rs index 31a58129..3d646771 100644 --- a/crates/jacquard-common/src/xrpc.rs +++ b/crates/jacquard-common/src/xrpc.rs @@ -317,27 +317,7 @@ impl<'a, C: HttpClient> XrpcCall<'a, C> { .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)) + process_response(http_response) } } diff --git a/crates/jacquard/Cargo.toml b/crates/jacquard/Cargo.toml index f036a7ab..9a6b3eb7 100644 --- a/crates/jacquard/Cargo.toml +++ b/crates/jacquard/Cargo.toml @@ -12,40 +12,42 @@ exclude.workspace = true license.workspace = true [features] -default = ["api_full", "dns", "loopback"] +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"] -[lib] -name = "jacquard" -path = "src/lib.rs" [[example]] name = "oauth_timeline" path = "../../examples/oauth_timeline.rs" -required-features = ["fancy", "loopback", "api_bluesky"] +required-features = ["fancy"] [[example]] name = "create_post" path = "../../examples/create_post.rs" -required-features = ["fancy", "loopback", "api_bluesky"] +required-features = ["fancy"] [[example]] name = "post_with_image" path = "../../examples/post_with_image.rs" -required-features = ["fancy", "loopback", "api_bluesky"] +required-features = ["fancy"] [[example]] name = "update_profile" path = "../../examples/update_profile.rs" -required-features = ["fancy", "loopback", "api_bluesky"] +required-features = ["fancy"] [[example]] name = "public_atproto_feed" @@ -54,26 +56,27 @@ path = "../../examples/public_atproto_feed.rs" [[example]] name = "create_whitewind_post" path = "../../examples/create_whitewind_post.rs" -required-features = ["fancy", "loopback", "api_full"] +required-features = ["fancy", ] [[example]] -name = "read_whitewind_posts" -path = "../../examples/read_whitewind_posts.rs" -required-features = ["fancy", "api_full"] +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 = ["api_full"] +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", "loopback", "api_full"] +required-features = ["fancy"] [dependencies] jacquard-api = { version = "0.4", path = "../jacquard-api" } diff --git a/crates/jacquard/src/client.rs b/crates/jacquard/src/client.rs index 7fea67d1..080a63f2 100644 --- a/crates/jacquard/src/client.rs +++ b/crates/jacquard/src/client.rs @@ -34,7 +34,7 @@ use jacquard_common::error::TransportError; 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::blob::{Blob, MimeType}; use jacquard_common::types::collection::Collection; use jacquard_common::types::recordkey::{RecordKey, Rkey}; use jacquard_common::types::string::AtUri; @@ -395,13 +395,12 @@ impl Agent { /// /// The collection is inferred from the type parameter. /// The repo is automatically filled from the session info. - pub async fn delete_record( + pub async fn delete_record( &self, - rkey: K, + rkey: RecordKey>, ) -> Result, AgentError> where R: Collection, - K: Into>>, { use jacquard_api::com_atproto::repo::delete_record::DeleteRecord; use jacquard_common::types::ident::AtIdentifier; @@ -411,7 +410,7 @@ impl Agent { let request = DeleteRecord::new() .repo(AtIdentifier::Did(did)) .collection(R::nsid()) - .rkey(rkey.into()) + .rkey(rkey) .build(); let response = self.send(request).await?; @@ -491,7 +490,7 @@ impl Agent { &self, data: impl Into, mime_type: MimeType<'_>, - ) -> Result, AgentError> { + ) -> Result, AgentError> { use http::header::CONTENT_TYPE; use jacquard_api::com_atproto::repo::upload_blob::UploadBlob; @@ -522,7 +521,7 @@ impl Agent { error: Box::new(typed), }, })?; - Ok(BlobRef::Blob(output.blob.into_static())) + Ok(output.blob.into_static()) } /// Update a vec-based data structure with a fetch-modify-put pattern. diff --git a/crates/jacquard/src/lib.rs b/crates/jacquard/src/lib.rs index d6b7e1f4..15bc8dbb 100644 --- a/crates/jacquard/src/lib.rs +++ b/crates/jacquard/src/lib.rs @@ -25,9 +25,7 @@ //! # 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")] diff --git a/examples/create_whitewind_post.rs b/examples/create_whitewind_post.rs index 9e805ecd..6254201b 100644 --- a/examples/create_whitewind_post.rs +++ b/examples/create_whitewind_post.rs @@ -1,4 +1,5 @@ use clap::Parser; +use jacquard::CowStr; use jacquard::api::com_whtwnd::blog::entry::Entry; use jacquard::client::{Agent, FileAuthStore}; use jacquard::oauth::atproto::AtprotoClientMetadata; @@ -6,8 +7,8 @@ use jacquard::oauth::client::OAuthClient; use jacquard::oauth::loopback::LoopbackConfig; use jacquard::types::string::Datetime; use jacquard::xrpc::XrpcClient; -use jacquard::CowStr; use miette::IntoDiagnostic; +use url::Url; #[derive(Parser, Debug)] #[command(author, version, about = "Create a WhiteWind blog post")] @@ -58,9 +59,15 @@ async fn main() -> miette::Result<()> { 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); + 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(()) } diff --git a/examples/post_with_image.rs b/examples/post_with_image.rs index 98d139ba..fa1b8a82 100644 --- a/examples/post_with_image.rs +++ b/examples/post_with_image.rs @@ -1,4 +1,5 @@ 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}; @@ -8,7 +9,6 @@ use jacquard::oauth::loopback::LoopbackConfig; use jacquard::types::blob::MimeType; use jacquard::types::string::Datetime; use jacquard::xrpc::XrpcClient; -use jacquard::CowStr; use miette::IntoDiagnostic; use std::path::PathBuf; @@ -59,14 +59,8 @@ async fn main() -> miette::Result<()> { }; 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"), - }; + println!("Uploading image..."); + let blob = agent.upload_blob(image_data, mime_type).await?; // Create post with image embed let post = Post { @@ -91,7 +85,7 @@ async fn main() -> miette::Result<()> { }; let output = agent.create_record(post, None).await?; - println!("✓ Created post with image: {}", output.uri); + println!("Created post with image: {}", output.uri); Ok(()) } diff --git a/examples/public_atproto_feed.rs b/examples/public_atproto_feed.rs index ee8fb198..523fa06b 100644 --- a/examples/public_atproto_feed.rs +++ b/examples/public_atproto_feed.rs @@ -21,7 +21,7 @@ async fn main() -> miette::Result<()> { let response = http.xrpc(base).send(&request).await?; let output = response.into_output()?; - println!("📰 Latest posts from the AT Protocol feed:\n"); + 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()?; diff --git a/examples/read_whitewind_posts.rs b/examples/read_whitewind_post.rs similarity index 100% rename from examples/read_whitewind_posts.rs rename to examples/read_whitewind_post.rs diff --git a/justfile b/justfile index edad96c3..d0115ec2 100644 --- a/justfile +++ b/justfile @@ -39,11 +39,11 @@ example-whitewind-create *ARGS: # Read a WhiteWind blog post example-whitewind-read *ARGS: - cargo run -p jacquard --example read_whitewind_posts --features fancy,api_full -- {{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,api_full -- {{ARGS}} + cargo run -p jacquard --example read_tangled_repo --features fancy -- {{ARGS}} # Resolve a handle to its DID document example-resolve-did *ARGS: -- 2.51.2