Skip to content

Commit 2bcdbbb

Browse files
committed
Relaxing back the Send trait on return types for wasm
1 parent 078241f commit 2bcdbbb

File tree

9 files changed

+134
-73
lines changed

9 files changed

+134
-73
lines changed

Cargo.lock

+14
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

+3
Original file line numberDiff line numberDiff line change
@@ -72,3 +72,6 @@ mockito = "1.4"
7272
# WebAssembly
7373
wasm-bindgen-test = "0.3.41"
7474
bumpalo = "~3.14.0"
75+
76+
# Code generation
77+
trait-variant = "0.1.2"

atrium-api/Cargo.toml

+1
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ serde_bytes.workspace = true
2323
serde_json.workspace = true
2424
thiserror.workspace = true
2525
tokio = { workspace = true, optional = true }
26+
trait-variant.workspace = true
2627

2728
[features]
2829
default = ["agent", "bluesky"]

atrium-api/src/agent/store.rs

+4-3
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,12 @@ use std::future::Future;
55
pub use self::memory::MemorySessionStore;
66
pub(crate) use super::Session;
77

8+
#[cfg_attr(not(target_arch = "wasm32"), trait_variant::make(Send))]
89
pub trait SessionStore {
910
#[must_use]
10-
fn get_session(&self) -> impl Future<Output = Option<Session>> + Send;
11+
fn get_session(&self) -> impl Future<Output = Option<Session>>;
1112
#[must_use]
12-
fn set_session(&self, session: Session) -> impl Future<Output = ()> + Send;
13+
fn set_session(&self, session: Session) -> impl Future<Output = ()>;
1314
#[must_use]
14-
fn clear_session(&self) -> impl Future<Output = ()> + Send;
15+
fn clear_session(&self) -> impl Future<Output = ()>;
1516
}

atrium-xrpc/Cargo.toml

+1
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ serde = { workspace = true, features = ["derive"] }
1717
serde_html_form.workspace = true
1818
serde_json.workspace = true
1919
thiserror.workspace = true
20+
trait-variant.workspace = true
2021

2122
[dev-dependencies]
2223
tokio = { workspace = true, features = ["macros", "rt"] }

atrium-xrpc/src/traits.rs

+87-63
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,13 @@ use std::fmt::Debug;
88
use std::future::Future;
99

1010
/// An abstract HTTP client.
11+
#[cfg_attr(not(target_arch = "wasm32"), trait_variant::make(Send))]
1112
pub trait HttpClient {
1213
/// Send an HTTP request and return the response.
1314
fn send_http(
1415
&self,
1516
request: Request<Vec<u8>>,
16-
) -> impl Future<Output = core::result::Result<Response<Vec<u8>>, Box<dyn std::error::Error + Send + Sync + 'static>>> + Send;
17+
) -> impl Future<Output = core::result::Result<Response<Vec<u8>>, Box<dyn std::error::Error + Send + Sync + 'static>>>;
1718
}
1819

1920
type XrpcResult<O, E> = core::result::Result<OutputDataOrBytes<O>, self::Error<E>>;
@@ -22,88 +23,111 @@ type XrpcResult<O, E> = core::result::Result<OutputDataOrBytes<O>, self::Error<E
2223
///
2324
/// [`send_xrpc()`](XrpcClient::send_xrpc) method has a default implementation,
2425
/// which wraps the [`HttpClient::send_http()`]` method to handle input and output as an XRPC Request.
26+
#[cfg_attr(not(target_arch = "wasm32"), trait_variant::make(Send))]
2527
pub trait XrpcClient: HttpClient {
2628
/// The base URI of the XRPC server.
2729
fn base_uri(&self) -> String;
2830
/// Get the authentication token to use `Authorization` header.
2931
#[allow(unused_variables)]
30-
fn authentication_token(&self, is_refresh: bool) -> impl Future<Output = Option<String>> + Send {
32+
fn authentication_token(&self, is_refresh: bool) -> impl Future<Output = Option<String>> {
3133
async { None }
3234
}
3335
/// Get the `atproto-proxy` header.
34-
fn atproto_proxy_header(&self) -> impl Future<Output = Option<String>> + Send {
36+
fn atproto_proxy_header(&self) -> impl Future<Output = Option<String>> {
3537
async { None }
3638
}
3739
/// Get the `atproto-accept-labelers` header.
38-
fn atproto_accept_labelers_header(&self) -> impl Future<Output = Option<Vec<String>>> + Send {
40+
fn atproto_accept_labelers_header(&self) -> impl Future<Output = Option<Vec<String>>> {
3941
async { None }
4042
}
4143
/// Send an XRPC request and return the response.
42-
fn send_xrpc<P, I, O, E>(&self, request: &XrpcRequest<P, I>) -> impl Future<Output = XrpcResult<O, E>> + Send
44+
#[cfg(not(target_arch = "wasm32"))]
45+
fn send_xrpc<P, I, O, E>(&self, request: &XrpcRequest<P, I>) -> impl Future<Output = XrpcResult<O, E>>
4346
where
4447
P: Serialize + Send + Sync,
4548
I: Serialize + Send + Sync,
4649
O: DeserializeOwned + Send + Sync,
4750
E: DeserializeOwned + Send + Sync + Debug,
51+
// This code is duplicated because of this trait bound.
52+
// `Self` has to be `Sync` for `Future` to be `Send`.
4853
Self: Sync,
4954
{
50-
async {
51-
let mut uri = format!("{}/xrpc/{}", self.base_uri(), request.nsid);
52-
// Query parameters
53-
if let Some(p) = &request.parameters {
54-
serde_html_form::to_string(p).map(|qs| {
55-
uri += "?";
56-
uri += &qs;
57-
})?;
58-
};
59-
let mut builder = Request::builder().method(&request.method).uri(&uri);
60-
// Headers
61-
if let Some(encoding) = &request.encoding {
62-
builder = builder.header(Header::ContentType, encoding);
63-
}
64-
if let Some(token) = self
65-
.authentication_token(
66-
request.method == Method::POST && request.nsid == NSID_REFRESH_SESSION,
67-
)
68-
.await
69-
{
70-
builder = builder.header(Header::Authorization, format!("Bearer {}", token));
71-
}
72-
if let Some(proxy) = self.atproto_proxy_header().await {
73-
builder = builder.header(Header::AtprotoProxy, proxy);
74-
}
75-
if let Some(accept_labelers) = self.atproto_accept_labelers_header().await {
76-
builder = builder.header(Header::AtprotoAcceptLabelers, accept_labelers.join(", "));
77-
}
78-
// Body
79-
let body = if let Some(input) = &request.input {
80-
match input {
81-
InputDataOrBytes::Data(data) => serde_json::to_vec(&data)?,
82-
InputDataOrBytes::Bytes(bytes) => bytes.clone(),
83-
}
84-
} else {
85-
Vec::new()
86-
};
87-
// Send
88-
let (parts, body) =
89-
self.send_http(builder.body(body)?).await.map_err(Error::HttpClient)?.into_parts();
90-
if parts.status.is_success() {
91-
if parts
92-
.headers
93-
.get(http::header::CONTENT_TYPE)
94-
.and_then(|value| value.to_str().ok())
95-
.map_or(false, |content_type| content_type.starts_with("application/json"))
96-
{
97-
Ok(OutputDataOrBytes::Data(serde_json::from_slice(&body)?))
98-
} else {
99-
Ok(OutputDataOrBytes::Bytes(body))
100-
}
101-
} else {
102-
Err(Error::XrpcResponse(XrpcError {
103-
status: parts.status,
104-
error: serde_json::from_slice::<XrpcErrorKind<E>>(&body).ok(),
105-
}))
106-
}
107-
}
55+
send_xrpc(self, request)
56+
}
57+
#[cfg(target_arch = "wasm32")]
58+
fn send_xrpc<P, I, O, E>(&self, request: &XrpcRequest<P, I>) -> impl Future<Output = XrpcResult<O, E>>
59+
where
60+
P: Serialize + Send + Sync,
61+
I: Serialize + Send + Sync,
62+
O: DeserializeOwned + Send + Sync,
63+
E: DeserializeOwned + Send + Sync + Debug,
64+
{
65+
send_xrpc(self, request)
10866
}
10967
}
68+
69+
#[inline(always)]
70+
async fn send_xrpc<P, I, O, E, C: XrpcClient + ?Sized>(client: &C, request: &XrpcRequest<P, I>) -> XrpcResult<O, E>
71+
where
72+
P: Serialize + Send + Sync,
73+
I: Serialize + Send + Sync,
74+
O: DeserializeOwned + Send + Sync,
75+
E: DeserializeOwned + Send + Sync + Debug,
76+
{
77+
let mut uri = format!("{}/xrpc/{}", client.base_uri(), request.nsid);
78+
// Query parameters
79+
if let Some(p) = &request.parameters {
80+
serde_html_form::to_string(p).map(|qs| {
81+
uri += "?";
82+
uri += &qs;
83+
})?;
84+
};
85+
let mut builder = Request::builder().method(&request.method).uri(&uri);
86+
// Headers
87+
if let Some(encoding) = &request.encoding {
88+
builder = builder.header(Header::ContentType, encoding);
89+
}
90+
if let Some(token) = client
91+
.authentication_token(
92+
request.method == Method::POST && request.nsid == NSID_REFRESH_SESSION,
93+
)
94+
.await
95+
{
96+
builder = builder.header(Header::Authorization, format!("Bearer {}", token));
97+
}
98+
if let Some(proxy) = client.atproto_proxy_header().await {
99+
builder = builder.header(Header::AtprotoProxy, proxy);
100+
}
101+
if let Some(accept_labelers) = client.atproto_accept_labelers_header().await {
102+
builder = builder.header(Header::AtprotoAcceptLabelers, accept_labelers.join(", "));
103+
}
104+
// Body
105+
let body = if let Some(input) = &request.input {
106+
match input {
107+
InputDataOrBytes::Data(data) => serde_json::to_vec(&data)?,
108+
InputDataOrBytes::Bytes(bytes) => bytes.clone(),
109+
}
110+
} else {
111+
Vec::new()
112+
};
113+
// Send
114+
let (parts, body) =
115+
client.send_http(builder.body(body)?).await.map_err(Error::HttpClient)?.into_parts();
116+
if parts.status.is_success() {
117+
if parts
118+
.headers
119+
.get(http::header::CONTENT_TYPE)
120+
.and_then(|value| value.to_str().ok())
121+
.map_or(false, |content_type| content_type.starts_with("application/json"))
122+
{
123+
Ok(OutputDataOrBytes::Data(serde_json::from_slice(&body)?))
124+
} else {
125+
Ok(OutputDataOrBytes::Bytes(body))
126+
}
127+
} else {
128+
Err(Error::XrpcResponse(XrpcError {
129+
status: parts.status,
130+
error: serde_json::from_slice::<XrpcErrorKind<E>>(&body).ok(),
131+
}))
132+
}
133+
}

bsky-sdk/Cargo.toml

+1
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ serde_json.workspace = true
2323
thiserror.workspace = true
2424
toml = { version = "0.8.13", optional = true }
2525
unicode-segmentation = { version = "1.11.0", optional = true }
26+
trait-variant.workspace = true
2627

2728
[dev-dependencies]
2829
ipld-core.workspace = true

bsky-sdk/src/agent/config.rs

+6-2
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,9 @@ pub trait Loader {
5151
/// Loads the configuration data.
5252
fn load(
5353
&self,
54-
) -> impl Future<Output = core::result::Result<Config, Box<dyn std::error::Error + Send + Sync + 'static>>> + Send;
54+
) -> impl Future<
55+
Output = core::result::Result<Config, Box<dyn std::error::Error + Send + Sync + 'static>>,
56+
> + Send;
5557
}
5658

5759
/// The trait for saving configuration data.
@@ -60,5 +62,7 @@ pub trait Saver {
6062
fn save(
6163
&self,
6264
config: &Config,
63-
) -> impl Future<Output = core::result::Result<(), Box<dyn std::error::Error + Send + Sync + 'static>>> + Send;
65+
) -> impl Future<
66+
Output = core::result::Result<(), Box<dyn std::error::Error + Send + Sync + 'static>>,
67+
> + Send;
6468
}

bsky-sdk/src/record.rs

+17-5
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ use atrium_api::com::atproto::repo::{
1212
use atrium_api::types::{Collection, LimitedNonZeroU8, TryIntoUnknown};
1313
use atrium_api::xrpc::XrpcClient;
1414

15+
#[cfg_attr(not(target_arch = "wasm32"), trait_variant::make(Send))]
1516
pub trait Record<T, S>
1617
where
1718
T: XrpcClient + Send + Sync,
@@ -21,11 +22,22 @@ where
2122
agent: &BskyAgent<T, S>,
2223
cursor: Option<String>,
2324
limit: Option<LimitedNonZeroU8<100u8>>,
24-
) -> impl Future<Output = Result<list_records::Output>> + Send;
25-
fn get(agent: &BskyAgent<T, S>, rkey: String) -> impl Future<Output = Result<get_record::Output>> + Send;
26-
fn put(self, agent: &BskyAgent<T, S>, rkey: String) -> impl Future<Output = Result<put_record::Output>> + Send;
27-
fn create(self, agent: &BskyAgent<T, S>) -> impl Future<Output = Result<create_record::Output>> + Send;
28-
fn delete(agent: &BskyAgent<T, S>, rkey: String) -> impl Future<Output = Result<delete_record::Output>> + Send;
25+
) -> impl Future<Output = Result<list_records::Output>>;
26+
fn get(
27+
agent: &BskyAgent<T, S>,
28+
rkey: String,
29+
) -> impl Future<Output = Result<get_record::Output>>;
30+
fn put(
31+
self,
32+
agent: &BskyAgent<T, S>,
33+
rkey: String,
34+
) -> impl Future<Output = Result<put_record::Output>>;
35+
fn create(self, agent: &BskyAgent<T, S>)
36+
-> impl Future<Output = Result<create_record::Output>>;
37+
fn delete(
38+
agent: &BskyAgent<T, S>,
39+
rkey: String,
40+
) -> impl Future<Output = Result<delete_record::Output>>;
2941
}
3042

3143
macro_rules! record_impl {

0 commit comments

Comments
 (0)