Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

Seanaye/add/axum rpc macro (#440)

Sean Aye354f2776aa78
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index 94bda9a26c..c9c276c0f9 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -1270,6 +1270,39 @@ dependencies = [
"url",
]
+[[package]]
+name = "axum_rpc"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "async-trait",
+ "axum_rpc_emit",
+ "http 1.3.1",
+ "js-sys",
+ "reqwest-middleware",
+ "web-sys",
+]
+
+[[package]]
+name = "axum_rpc_emit"
+version = "0.1.0"
+dependencies = [
+ "axum_rpc_parse",
+ "cool_asserts",
+ "proc-macro2",
+ "quote",
+ "unsynn",
+]
+
+[[package]]
+name = "axum_rpc_parse"
+version = "0.1.0"
+dependencies = [
+ "cool_asserts",
+ "quote",
+ "unsynn",
+]
+
[[package]]
name = "backoff"
version = "0.4.0"
@@ -6398,9 +6431,9 @@ dependencies = [
[[package]]
name = "proc-macro2"
-version = "1.0.93"
+version = "1.0.103"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "60946a68e5f9d28b0dc1c21bb8a97ee7d018a8b322fa57838ba31cc878e22d99"
+checksum = "5ee95bc4ef87b8d5ba32e8b7714ccc834865276eab0aed5c9958d00ec45f49e8"
dependencies = [
"unicode-ident",
]
@@ -6584,9 +6617,9 @@ dependencies = [
[[package]]
name = "quote"
-version = "1.0.38"
+version = "1.0.42"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0e4dccaaaf89514f546c693ddc140f729f958c247918a13380cccc6078391acc"
+checksum = "a338cc41d27e6cc6dce6cefc13a0729dfbb81c262b1f519331575dd80ef3067f"
dependencies = [
"proc-macro2",
]
@@ -6941,6 +6974,20 @@ dependencies = [
"thiserror 1.0.69",
]
+[[package]]
+name = "reqwest-middleware"
+version = "0.4.2"
+source = "git+https://github.com/seanaye/reqwest-middleware#1e4298aaac963498ffe3c84c83c6748afd03593d"
+dependencies = [
+ "anyhow",
+ "async-trait",
+ "http 1.3.1",
+ "reqwest",
+ "serde",
+ "thiserror 2.0.17",
+ "tower-service",
+]
+
[[package]]
name = "reserve-port"
version = "2.3.0"
diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.toml
index 7d89b0b48b..de4b8f2e64 100644
--- a/rust/cloud-storage/Cargo.toml
+++ b/rust/cloud-storage/Cargo.toml
@@ -89,6 +89,9 @@ members = [
"properties_service",
"properties_service_client",
"roles_and_permissions",
+ "rpc/axum_rpc",
+ "rpc/axum_rpc_emit",
+ "rpc/axum_rpc_parse",
"s3_client",
"scribe",
"search_processing_service",
@@ -146,6 +149,7 @@ ego-tree = "0.6.2"
either = "1"
futures = "0.3.31"
hex = "0.4.3"
+http = "1"
http-body-util = "0.1.2"
jsonwebtoken = "9.3.1"
lambda_runtime = "0.13.0"
@@ -156,11 +160,13 @@ nom = "8"
openssl = { version = "0.10.71", features = ["vendored"] }
ordered-float = "5"
pdfium-render = { version = "0.8.28" }
+quote = "1"
rand = "0.9.0"
recursion = "0.5.4"
redis = "0.29.0"
regex = "1.11.1"
reqwest = { version = "0.12.12", features = ["json"] }
+reqwest-middleware = { git = "https://github.com/seanaye/reqwest-middleware" }
schemars = { version = "1.0.4", features = ["chrono04"] }
serde = { version = "1.0.214", features = ["derive"] }
serde_dynamo = { version = "4", features = ["aws-sdk-dynamodb+1"] }
@@ -190,6 +196,7 @@ tower-http = { version = "0.6.1", features = [
tracing = "0.1.41"
tracing-subscriber = { version = "0.3.20", features = ["env-filter", "json"] }
tracing-tree = "0.4.0"
+unsynn = "0.3"
urlencoding = "2.1.3"
utoipa = { version = "5.2.0", features = [
"axum_extras",
@@ -212,6 +219,7 @@ bzip2 = { version = "0.5.1", default-features = false, features = [
] }
derive_builder = "0.20.2"
doppleganger = "0.5"
+js-sys = "0.3"
once_cell = "1.21.3"
scraper = "0.18"
strum_macros = "0.27.1"
diff --git a/rust/cloud-storage/deny.toml b/rust/cloud-storage/deny.toml
index 65e2e0f2f1..579dca9dda 100644
--- a/rust/cloud-storage/deny.toml
+++ b/rust/cloud-storage/deny.toml
@@ -220,7 +220,6 @@ deny = [
skip = [
# These duplicates are due to complex dependency trees from AWS SDK, async-stripe, axum, and other major dependencies
{ crate = "base64", reason = "AWS SDK and other dependencies require different versions" },
- { crate = "bitflags", reason = "Different dependencies require bitflags v1 and v2" },
{ crate = "core-foundation", reason = "Different dependencies require different versions" },
{ crate = "crypto-bigint", reason = "AWS cryptographic dependencies version mismatch" },
{ crate = "cssparser", reason = "HTML parsing dependencies version mismatch" },
@@ -229,7 +228,6 @@ skip = [
{ crate = "getrandom", reason = "Random number generation dependencies" },
{ crate = "h2", reason = "HTTP/2 dependencies version mismatch" },
{ crate = "hashbrown", reason = "Different dependencies require different versions" },
- { crate = "heck", reason = "Case conversion dependencies" },
{ crate = "html5ever", reason = "HTML parsing dependencies" },
{ crate = "http", reason = "Hyper and AWS SDK version mismatch" },
{ crate = "http-body", reason = "Hyper and AWS SDK version mismatch" },
@@ -277,6 +275,8 @@ skip = [
{ crate = "windows_x86_64_gnullvm", reason = "Windows dependencies" },
{ crate = "windows_x86_64_msvc", reason = "Windows dependencies" },
{ crate = "zerocopy", reason = "Zero-copy serialization dependencies" },
+ { crate = "zune-core", reason = "Duplicated dep" },
+ { crate = "zune-jpeg", reason = "Deuplicated dep" },
]
# Similarly to `skip` allows you to skip certain crates during duplicate
# detection. Unlike skip, it also includes the entire tree of transitive
@@ -301,7 +301,7 @@ unknown-git = "warn"
# if not specified. If it is specified but empty, no registries are allowed.
allow-registry = ["https://github.com/rust-lang/crates.io-index"]
# List of URLs for allowed Git repositories
-allow-git = []
+allow-git = ["git+https://github.com/seanaye/reqwest-middleware"]
[sources.allow-org]
# github.com organizations to allow git sources for
diff --git a/rust/cloud-storage/rpc/axum_rpc/.helix/languages.toml b/rust/cloud-storage/rpc/axum_rpc/.helix/languages.toml
new file mode 100644
index 0000000000..da038d03e5
--- /dev/null
+++ b/rust/cloud-storage/rpc/axum_rpc/.helix/languages.toml
@@ -0,0 +1,5 @@
+[[language]]
+name = "rust"
+
+[language-server.rust-analyzer.config]
+cargo.target = "wasm32-unknown-unknown"
diff --git a/rust/cloud-storage/rpc/axum_rpc/Cargo.toml b/rust/cloud-storage/rpc/axum_rpc/Cargo.toml
new file mode 100644
index 0000000000..f103cb56d5
--- /dev/null
+++ b/rust/cloud-storage/rpc/axum_rpc/Cargo.toml
@@ -0,0 +1,17 @@
+[package]
+edition = "2024"
+name = "axum_rpc"
+publish = false
+version = "0.1.0"
+
+
+[dependencies]
+anyhow = { workspace = true }
+axum_rpc_emit = { path = "../axum_rpc_emit" }
+
+[target.'cfg(target_arch = "wasm32")'.dependencies]
+async-trait = { workspace = true }
+http = { workspace = true }
+js-sys = { workspace = true }
+reqwest-middleware = { workspace = true }
+web-sys = { version = "0.3", features = ["Headers", "console"] }
diff --git a/rust/cloud-storage/rpc/axum_rpc/src/lib.rs b/rust/cloud-storage/rpc/axum_rpc/src/lib.rs
new file mode 100644
index 0000000000..db44a5a435
--- /dev/null
+++ b/rust/cloud-storage/rpc/axum_rpc/src/lib.rs
@@ -0,0 +1,33 @@
+pub use anyhow;
+pub use axum_rpc_emit::*;
+
+#[cfg(target_family = "wasm")]
+pub trait MaybeSend {}
+#[cfg(target_family = "wasm")]
+impl<T> MaybeSend for T {}
+
+#[cfg(not(target_family = "wasm"))]
+pub trait MaybeSend: Send {}
+#[cfg(not(target_family = "wasm"))]
+impl<T> MaybeSend for T where T: Send {}
+
+#[cfg(target_family = "wasm")]
+pub trait MaybeSync {}
+#[cfg(target_family = "wasm")]
+impl<T> MaybeSync for T {}
+
+#[cfg(not(target_family = "wasm"))]
+pub trait MaybeSync: Sync {}
+#[cfg(not(target_family = "wasm"))]
+impl<T> MaybeSync for T where T: Sync {}
+
+macro_rules! if_wasm {
+ ($($item:item)*) => {$(
+ #[cfg(target_arch = "wasm32")]
+ $item
+ )*}
+}
+
+if_wasm! {
+ pub mod wasm;
+}
diff --git a/rust/cloud-storage/rpc/axum_rpc/src/wasm.rs b/rust/cloud-storage/rpc/axum_rpc/src/wasm.rs
new file mode 100644
index 0000000000..3e956912b3
--- /dev/null
+++ b/rust/cloud-storage/rpc/axum_rpc/src/wasm.rs
@@ -0,0 +1,123 @@
+use std::sync::Arc;
+
+use http::Extensions;
+use js_sys::wasm_bindgen::{JsCast, JsValue};
+use js_sys::{Array, Reflect};
+use reqwest_middleware::Next;
+use reqwest_middleware::reqwest::{Request, Response};
+use reqwest_middleware::{
+ Middleware,
+ reqwest::header::{HeaderMap, HeaderName, HeaderValue},
+};
+
+trait JsCastRes: Sized {
+ /// attempt to cast the jsvalue into T at runtime
+ fn cast<T: JsCast>(self) -> Result<T, JsValue>;
+ /// uses cast and logs the error if the received value was incorrect
+ fn cast_and_log<T: JsCast>(self) -> Option<T> {
+ match self.cast() {
+ Ok(v) => Some(v),
+ Err(e) => {
+ web_sys::console::log_2(
+ &JsValue::from_str(&format!(
+ "Expected to receive a value of type {}, but instead received:",
+ std::any::type_name::<T>()
+ )),
+ &e,
+ );
+ None
+ }
+ }
+ }
+}
+
+impl JsCastRes for Result<JsValue, JsValue> {
+ fn cast<T: JsCast>(self) -> Result<T, JsValue> {
+ self.and_then(|ok| ok.dyn_into())
+ }
+}
+
+/// Helper function to convert web_sys::Headers to reqwest::HeaderMap
+fn headers_to_headermap(headers: &web_sys::Headers) -> HeaderMap {
+ let mut map = HeaderMap::new();
+
+ // Get the entries iterator
+ let entries = headers.entries();
+
+ loop {
+ let Ok(next) = entries.next() else {
+ web_sys::console::log_1(&JsValue::from_str("Failed to get next entry"));
+ break;
+ };
+
+ // Check if done
+ let done = Reflect::get(&next, &JsValue::from_str("done"))
+ .ok()
+ .and_then(|v| v.as_bool())
+ .unwrap_or(true);
+
+ if done {
+ break;
+ }
+
+ // Get the value [name, value]
+ if let Ok(value) = Reflect::get(&next, &JsValue::from_str("value")) {
+ if let Ok(array) = value.dyn_into::<Array>() {
+ if let (Some(name), Some(val)) =
+ (array.get(0).as_string(), array.get(1).as_string())
+ {
+ if let (Ok(header_name), Ok(header_value)) = (
+ HeaderName::from_bytes(name.as_bytes()),
+ HeaderValue::from_str(&val),
+ ) {
+ map.insert(header_name, header_value);
+ }
+ }
+ }
+ }
+ }
+
+ map
+}
+
+pub struct JsHeaderMiddleware {
+ inner: Arc<dyn Fn() -> HeaderMap>,
+}
+
+// SAFETY: browser based wasm only has 1 thread so this is never actually sent
+// THIS IS UNSOUND IN THREADED WASM ENVIRONMENTS
+unsafe impl Send for JsHeaderMiddleware {}
+unsafe impl Sync for JsHeaderMiddleware {}
+
+impl JsHeaderMiddleware {
+ pub fn new(f: js_sys::Function) -> Self {
+ let inner = Arc::new(move || {
+ let Some(res) = f
+ .call0(&JsValue::UNDEFINED)
+ .cast_and_log::<web_sys::Headers>()
+ else {
+ return HeaderMap::default();
+ };
+ headers_to_headermap(&res)
+ });
+
+ Self { inner }
+ }
+}
+
+#[async_trait::async_trait(?Send)]
+impl Middleware for JsHeaderMiddleware {
+ async fn handle(
+ &self,
+ mut req: Request,
+ extensions: &mut Extensions,
+ next: Next<'_>,
+ ) -> Result<Response, reqwest_middleware::Error> {
+ let headers = req.headers_mut();
+ let merge = (self.inner)();
+
+ headers.extend(merge.into_iter().filter_map(|(k, v)| Some((k?, v))));
+
+ next.run(req, extensions).await
+ }
+}
diff --git a/rust/cloud-storage/rpc/axum_rpc_emit/Cargo.toml b/rust/cloud-storage/rpc/axum_rpc_emit/Cargo.toml
new file mode 100644
index 0000000000..dac08e02fe
--- /dev/null
+++ b/rust/cloud-storage/rpc/axum_rpc_emit/Cargo.toml
@@ -0,0 +1,17 @@
+[package]
+edition = "2024"
+name = "axum_rpc_emit"
+publish = false
+version = "0.1.0"
+
+[lib]
+proc-macro = true
+
+[dependencies]
+axum_rpc_parse = { path = "../axum_rpc_parse" }
+proc-macro2 = "1.0.103"
+quote = { workspace = true }
+unsynn = { workspace = true }
+
+[dev-dependencies]
+cool_asserts = "2"
diff --git a/rust/cloud-storage/rpc/axum_rpc_emit/src/lib.rs b/rust/cloud-storage/rpc/axum_rpc_emit/src/lib.rs
new file mode 100644
index 0000000000..ac2c59d873
--- /dev/null
+++ b/rust/cloud-storage/rpc/axum_rpc_emit/src/lib.rs
@@ -0,0 +1,632 @@
+use axum_rpc_parse::{ClientDirective, KRouter, ModPath, Trait, TraitFn, TraitItem};
+use proc_macro2::TokenStream;
+use quote::quote;
+use unsynn::*;
+
+fn attr_macros_inner(attr: TokenStream, mut input: TokenStream) -> TokenStream {
+ let mut i = input.clone().to_token_iter();
+
+ let target = parse_top_level_attr(&attr);
+
+ match i.parse::<Cons<Trait, EndOfStream>>() {
+ Ok(Cons { first, .. }) => {
+ input.extend(generate_target(target, first));
+ input
+ }
+ Err(err) => {
+ panic!("Could not parse type declaration: {input}\nError: {err}");
+ }
+ }
+}
+
+enum ToGenerate {
+ Client { bindgen: bool },
+ Router,
+}
+
+fn parse_top_level_attr(attr: &TokenStream) -> ToGenerate {
+ let mut i = attr.to_token_iter();
+
+ match i.parse::<Cons<CommaDelimitedVec<Either<KRouter, ClientDirective>>, EndOfStream>>() {
+ Ok(Cons { first, .. }) => {
+ let has_router = first.iter().any(|v| matches!(v.value, Either::First(_)));
+ let bindgen = first.iter().find_map(|v| match &v.value {
+ Either::Second(a) => Some(a.inner.as_ref().map(|_| true).unwrap_or_default()),
+ _ => None,
+ });
+ match (has_router, bindgen) {
+ (true, None) => ToGenerate::Router,
+ (false, Some(bindgen)) => ToGenerate::Client { bindgen },
+ _ => panic!("Expected one of `router` or `client`"),
+ }
+ }
+ Err(err) => {
+ panic!("Could not parse type declaration {attr}\nError: {err}");
+ }
+ }
+}
+
+#[proc_macro_attribute]
+pub fn attr_macros(
+ attr: proc_macro::TokenStream,
+ input: proc_macro::TokenStream,
+) -> proc_macro::TokenStream {
+ attr_macros_inner(attr.into(), input.into()).into()
+}
+
+fn generate_target(target: ToGenerate, tokens: Trait) -> TokenStream {
+ // Validate that all trait functions have exactly 1 argument (besides &self)
+ validate_trait_functions(&tokens);
+
+ match target {
+ ToGenerate::Client { bindgen } => generate_client(&tokens, bindgen),
+ ToGenerate::Router => generate_router(&tokens),
+ }
+}
+
+fn validate_trait_functions(tokens: &Trait) {
+ for item in tokens.body.content.iter() {
+ if let TraitItem::Fn(f) = &item.value {
+ let args_count = f.args.content.second.len();
+ if args_count > 2 {
+ panic!(
+ "RPC trait method '{}' must have 0, 1, or 2 arguments (besides &self), but found {}. \
+ RPC methods should take the form: fn method_name(&self, [extractor: Self::AssociatedType,] [arg: ArgType]) -> ...",
+ f.name, args_count
+ );
+ }
+ }
+ }
+}
+
+/// Check if a ModPath represents an associated type (e.g., Self::SomeType)
+fn is_associated_type(path: &ModPath) -> bool {
+ // Check if path is Self::Something (no leading ::, first ident is "Self", has at least 2 segments)
+ if path.first.is_some() {
+ return false; // Has leading ::, not an associated type
+ }
+
+ let segments = &path.second;
+ if segments.len() < 2 {
+ return false; // Need at least Self::TypeName
+ }
+
+ // Check if first segment is "Self"
+ segments.first().map(|d| d.value == "Self").unwrap_or(false)
+}
+
+fn generate_bindgen(tokens: &Trait, client_name: &Ident) -> TokenStream {
+ fn generate_client_method(f: &TraitFn, trait_name: &Ident) -> TokenStream {
+ let method_name = &f.name;
+ let args = &f.args.content.second;
+
+ // Separate extractor args from JSON args - wasm_bindgen can't handle associated types
+ let json_args: Vec<_> = args
+ .iter()
+ .filter(|arg| !is_associated_type(&arg.value.val))
+ .collect();
+
+ // Generate argument streams only for non-extractor args
+ let arg_streams: Vec<_> = json_args
+ .iter()
+ .map(|arg| {
+ let name = &arg.value.name;
+ let val = generate_mod_path(&arg.value.val);
+ quote! { #name: #val }
+ })
+ .collect();
+
+ // Generate argument names to pass to trait method
+ // For extractors, pass (), for JSON args pass the actual value
+ let call_args: Vec<_> = args
+ .iter()
+ .map(|arg| {
+ let name = &arg.value.name;
+ if is_associated_type(&arg.value.val) {
+ quote! { () }
+ } else {
+ quote! { #name }
+ }
+ })
+ .collect();
+
+ let ok = f.return_type.ok.to_token_stream();
+
+ quote! {
+ pub async fn #method_name(&self, #(#arg_streams),*) -> Result<#ok, String> {
+ #trait_name::#method_name(self, #(#call_args),*).await.map_err(|e| e.to_string())
+ }
+ }
+ }
+
+ let methods = tokens
+ .body
+ .content
+ .iter()
+ .filter_map(|Delimited { value, .. }| match value {
+ TraitItem::Fn(f) => Some(generate_client_method(f, &tokens.name)),
+ TraitItem::AssociatedType(_) => None,
+ });
+
+ quote! {
+ #[::wasm_bindgen::prelude::wasm_bindgen]
+ impl #client_name {
+ pub fn construct(s: String) -> Result<Self, String> {
+ let url = s.parse().map_err(|_| String::from("invalid url"))?;
+ Ok(Self::builder().build(url).map_err(|e| e.to_string())?)
+ }
+
+ pub fn construct_with_headers(
+ s: String,
+ // TODO: fix this it causes the compile to fail
+ // consider moving this code outside of quote
+ // #[wasm_bindgen(typescript_type = "() => Headers")]
+ headers_fn: ::js_sys::Function
+ ) -> Result<Self, String> {
+ let url = s.parse().map_err(|_| String::from("invalid url"))?;
+ let middleware = ::axum_rpc::wasm::JsHeaderMiddleware::new(headers_fn);
+ Ok(Self::builder()
+ .with(middleware)
+ .build(url)
+ .map_err(|e| e.to_string())?)
+ }
+
+ #(#methods)*
+
+ }
+
+ }
+}
+
+fn generate_client(tokens: &Trait, bindgen: bool) -> TokenStream {
+ let trait_name = &tokens.name;
+ let name_str = trait_name.to_string();
+ let client_name = quote::format_ident!("{name_str}Client");
+ let builder_name = quote::format_ident!("{name_str}ClientBuilder");
+
+ let methods = generate_client_methods(tokens);
+ let associated_types = generate_client_associated_types(tokens);
+
+ let mut output = match bindgen {
+ true => quote! {
+ #[::wasm_bindgen::prelude::wasm_bindgen]
+ },
+ false => quote! {},
+ };
+
+ output.extend(quote! {
+ #[derive(Clone)]
+ pub struct #client_name {
+ endpoint: ::url::Url,
+ client: ::std::sync::Arc<::reqwest_middleware::ClientWithMiddleware>
+ }
+
+
+ impl #client_name {
+ pub fn builder() -> #builder_name {
+ #builder_name::new()
+ }
+
+ fn get_endpoint(&self, s: &'static str) -> ::url::Url {
+ let mut url = self.endpoint.clone();
+ url.path_segments_mut().unwrap().push(s);
+ url
+ }
+ }
+
+ impl #trait_name for #client_name {
+ #(#associated_types)*
+
+ #(#methods)*
+ }
+
+
+ pub struct #builder_name {
+ builder: ::reqwest_middleware::ClientBuilder,
+ }
+
+ #[derive(Debug)]
+ pub struct CannotBeBase;
+
+ impl std::fmt::Display for CannotBeBase {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "Url cannot be a base. Must pass a qualified url e.g. https://macro.com")
+ }
+ }
+
+
+ impl #builder_name {
+ pub fn new_with_client(client: ::reqwest::Client) -> Self {
+ #builder_name {
+ builder: ::reqwest_middleware::ClientBuilder::new(client)
+ }
+ }
+
+ pub fn new() -> Self {
+ let client = ::reqwest::Client::new();
+ Self::new_with_client(client)
+ }
+
+ pub fn with<M: ::reqwest_middleware::Middleware>(self, middleware: M) -> Self {
+ let #builder_name { builder } = self;
+ #builder_name { builder: builder.with(middleware) }
+ }
+
+ pub fn build(self, endpoint: ::url::Url) -> Result<#client_name, CannotBeBase> {
+ let #builder_name { builder } = self;
+
+ let false = endpoint.cannot_be_a_base() else {
+ return Err(CannotBeBase);
+ };
+
+ Ok(#client_name {
+ endpoint,
+ client: ::std::sync::Arc::new(builder.build())
+ })
+ }
+ }
+
+
+ });
+
+ if bindgen {
+ output.extend(generate_bindgen(tokens, &client_name));
+ }
+
+ output
+}
+
+fn generate_client_method(f: &TraitFn) -> TokenStream {
+ let method_name = &f.name;
+ let ok = f.return_type.ok.to_token_stream();
+ let err = f.return_type.err.to_token_stream();
+ let literal = proc_macro2::Literal::string(&f.name.to_string());
+
+ let args = &f.args.content.second;
+
+ // Separate extractor args from JSON args
+ let mut extractor_args = vec![];
+ let mut json_arg = None;
+
+ for arg in args.iter() {
+ if is_associated_type(&arg.value.val) {
+ extractor_args.push(arg);
+ } else {
+ json_arg = Some(arg);
+ }
+ }
+
+ // Generate function signature with all arguments
+ // For extractor args (Self::AssociatedType), use () in the client impl
+ let all_args = args.iter().map(|arg| {
+ let arg_name = &arg.value.name;
+ if is_associated_type(&arg.value.val) {
+ // Extractor argument - use () for client
+ quote! { #arg_name: () }
+ } else {
+ let arg_val = generate_mod_path(&arg.value.val);
+ quote! { #arg_name: #arg_val }
+ }
+ });
+
+ match json_arg {
+ Some(arg) => {
+ // Has JSON body
+ let arg_name = &arg.value.name;
+
+ quote! {
+ async fn #method_name(&self, #(#all_args),*) -> Result<#ok, #err> {
+ let endpoint = self.get_endpoint(#literal);
+ Ok(self.client.post(endpoint).with_inner_builder(|builder| builder.fetch_credentials_include()).json(&#arg_name).send().await?.error_for_status()?.json().await?)
+ }
+ }
+ }
+ None => {
+ // No JSON body (only extractor args or no args at all)
+ if extractor_args.is_empty() {
+ // No arguments at all
+ quote! {
+ async fn #method_name(&self) -> Result<#ok, #err> {
+ let endpoint = self.get_endpoint(#literal);
+ Ok(self.client.post(endpoint).with_inner_builder(|builder| builder.fetch_credentials_include()).send().await?.error_for_status()?.json().await?)
+ }
+ }
+ } else {
+ // Only extractor args (passed but not used in HTTP call)
+ quote! {
+ async fn #method_name(&self, #(#all_args),*) -> Result<#ok, #err> {
+ let endpoint = self.get_endpoint(#literal);
+ Ok(self.client.post(endpoint).with_inner_builder(|builder| builder.fetch_credentials_include()).send().await?.error_for_status()?.json().await?)
+ }
+ }
+ }
+ }
+ }
+}
+
+fn generate_mod_path(path: &ModPath) -> TokenStream {
+ let mut tokens = TokenStream::new();
+
+ // Add optional leading ::
+ if let Some(path_sep) = &path.first {
+ tokens.extend(path_sep.to_token_stream());
+ }
+
+ // Add the path segments (ident :: ident :: ident)
+ tokens.extend(path.second.to_token_stream());
+
+ tokens
+}
+
+/// Generate a mod path, replacing Self with the given type name for use in impl blocks
+fn generate_mod_path_replace_self(path: &ModPath, replacement: &Ident) -> TokenStream {
+ // Check if first segment is "Self" and replace it
+ let segments = &path.second;
+ if let Some(first_seg) = segments.first()
+ && first_seg.value == "Self"
+ {
+ // Build new path with replacement
+ let mut tokens = TokenStream::new();
+
+ // Add optional leading ::
+ if let Some(path_sep) = &path.first {
+ tokens.extend(path_sep.to_token_stream());
+ }
+
+ // Add the replacement for Self
+ tokens.extend(replacement.to_token_stream());
+
+ // Add the rest (::TypeName)
+ // Get the tail of segments after Self
+ for i in 1..segments.len() {
+ tokens.extend(quote! { :: });
+ if let Some(seg) = segments.get(i) {
+ tokens.extend(seg.value.to_token_stream());
+ }
+ }
+
+ return tokens;
+ }
+
+ // No Self to replace, use original
+ generate_mod_path(path)
+}
+
+fn generate_client_methods(tokens: &Trait) -> impl Iterator<Item = TokenStream> + '_ {
+ tokens
+ .body
+ .content
+ .iter()
+ .filter_map(|Delimited { value, .. }| match value {
+ TraitItem::Fn(f) => Some(generate_client_method(f)),
+ TraitItem::AssociatedType(_) => None,
+ })
+}
+
+fn generate_client_associated_types(tokens: &Trait) -> impl Iterator<Item = TokenStream> + '_ {
+ tokens
+ .body
+ .content
+ .iter()
+ .filter_map(|Delimited { value, .. }| match value {
+ TraitItem::AssociatedType(at) => {
+ let type_name = &at.name;
+ Some(quote! {
+ type #type_name = ();
+ })
+ }
+ TraitItem::Fn(_) => None,
+ })
+}
+
+fn generate_router(tokens: &Trait) -> TokenStream {
+ let trait_name = &tokens.name;
+ let name_str = trait_name.to_string();
+ let builder_name = quote::format_ident!("{name_str}RouterBuilder");
+
+ let handlers = generate_handlers(tokens);
+ let handler_fns = generate_handler_fns(tokens);
+ let build_where_bounds = generate_build_where_bounds(tokens);
+
+ quote! {
+
+ pub struct #builder_name<T> {
+ state: T
+ }
+
+
+ #handler_fns
+
+ impl<T: #trait_name + Clone> #builder_name<T> {
+ pub fn new(state: T) -> Self {
+ Self {
+ state
+ }
+
+ }
+
+ pub fn build<S: Send + Sync>(self) -> ::axum::Router<S>
+ where
+ #(#build_where_bounds),*
+ {
+ ::axum::Router::new()#handlers.with_state(self.state)
+ }
+ }
+ }
+}
+
+fn generate_build_where_bounds(tokens: &Trait) -> Vec<TokenStream> {
+ use std::collections::HashSet;
+
+ // Collect all associated types that are actually used as extractors
+ let mut used_extractors = HashSet::new();
+
+ for item in tokens.body.content.iter() {
+ if let TraitItem::Fn(f) = &item.value {
+ let args = &f.args.content.second;
+ for arg in args.iter() {
+ if is_associated_type(&arg.value.val) {
+ // Extract the type name from Self::TypeName
+ if let Some(type_name_ident) = arg.value.val.second.get(1) {
+ used_extractors.insert(type_name_ident.value.to_string());
+ }
+ }
+ }
+ }
+ }
+
+ // Generate where bounds only for used extractors
+ used_extractors
+ .into_iter()
+ .map(|type_name_str| {
+ let type_name = quote::format_ident!("{}", type_name_str);
+ quote! {
+ T::#type_name: ::axum::extract::FromRequestParts<T> + Send
+ }
+ })
+ .collect()
+}
+
+fn generate_handlers(tokens: &Trait) -> TokenStream {
+ tokens
+ .body
+ .content
+ .iter()
+ .filter_map(|Delimited { value, .. }| match value {
+ TraitItem::Fn(f) => {
+ let literal = proc_macro2::Literal::string(&format!("/{}", &f.name));
+ let HandlerName { handler_name } = HandlerName::new(f);
+
+ Some(quote! {
+ .route(#literal, ::axum::routing::post(#handler_name::<T>))
+ })
+ }
+ TraitItem::AssociatedType(_) => None,
+ })
+ .collect()
+}
+
+struct HandlerName {
+ handler_name: Ident,
+}
+
+impl HandlerName {
+ fn new(f: &TraitFn) -> Self {
+ let handler_name = quote::format_ident!("{}_handler", f.name.to_string());
+ HandlerName { handler_name }
+ }
+}
+
+fn generate_handler_fns(tokens: &Trait) -> TokenStream {
+ let trait_name = &tokens.name;
+
+ tokens
+ .body
+ .content
+ .iter()
+ .filter_map(|Delimited { value, .. }| {
+ let f = match value {
+ TraitItem::Fn(f) => f,
+ TraitItem::AssociatedType(_) => return None,
+ };
+
+ let args = &f.args.content.second;
+ let ok = f.return_type.ok.to_token_stream();
+ let err = f.return_type.err.to_token_stream();
+
+ let HandlerName { handler_name } = HandlerName::new(f);
+ let method_name = &f.name;
+
+ // Separate extractor args from JSON args
+ let mut extractor_args = vec![];
+ let mut json_arg = None;
+
+ for arg in args.iter() {
+ if is_associated_type(&arg.value.val) {
+ extractor_args.push(arg);
+ } else {
+ json_arg = Some(arg);
+ }
+ }
+
+ // Generate extractor parameters only for the ones used in this method
+ // Replace Self:: with T:: for use in handler function
+ let t_ident = quote::format_ident!("T");
+ let extractor_params = extractor_args.iter().map(|arg| {
+ let arg_name = &arg.value.name;
+ let arg_val = generate_mod_path_replace_self(&arg.value.val, &t_ident);
+ quote! {
+ #arg_name: #arg_val
+ }
+ });
+
+ // Generate where bounds only for the extractors used in this method
+ let where_bounds = extractor_args.iter().map(|arg| {
+ let arg_val = generate_mod_path_replace_self(&arg.value.val, &t_ident);
+ quote! {
+ #arg_val: ::axum::extract::FromRequestParts<T> + Send
+ }
+ });
+
+ // Generate the argument names to pass to the trait method
+ let method_call_args = args.iter().map(|arg| {
+ let arg_name = &arg.value.name;
+ quote! { #arg_name }
+ });
+
+ match json_arg {
+ Some(arg) => {
+ // Has JSON body
+ let json_arg_name = &arg.value.name;
+ let json_arg_val = generate_mod_path(&arg.value.val);
+
+ if extractor_args.is_empty() {
+ // No extractors, only JSON
+ Some(quote! {
+ async fn #handler_name<T>(
+ state: ::axum::extract::State<T>,
+ ::axum::extract::Json(#json_arg_name): ::axum::extract::Json<#json_arg_val>
+ ) -> Result<::axum::extract::Json<#ok>, #err>
+ where
+ T: #trait_name,
+ #(#where_bounds),*
+ {
+ state.0.#method_name(#(#method_call_args),*).await.map(::axum::extract::Json)
+ }
+ })
+ } else {
+ // Both extractors and JSON
+ Some(quote! {
+ async fn #handler_name<T>(
+ state: ::axum::extract::State<T>,
+ #(#extractor_params,)*
+ ::axum::extract::Json(#json_arg_name): ::axum::extract::Json<#json_arg_val>
+ ) -> Result<::axum::extract::Json<#ok>, #err>
+ where
+ T: #trait_name,
+ #(#where_bounds),*
+ {
+ state.0.#method_name(#(#method_call_args),*).await.map(::axum::extract::Json)
+ }
+ })
+ }
+ }
+ None => {
+ // No JSON body (only extractor args or no args at all)
+ Some(quote! {
+ async fn #handler_name<T>(
+ state: ::axum::extract::State<T>,
+ #(#extractor_params),*
+ ) -> Result<::axum::extract::Json<#ok>, #err>
+ where
+ T: #trait_name,
+ #(#where_bounds),*
+ {
+ state.0.#method_name(#(#method_call_args),*).await.map(::axum::extract::Json)
+ }
+ })
+ }
+ }
+ })
+ .collect()
+}
diff --git a/rust/cloud-storage/rpc/axum_rpc_parse/Cargo.toml b/rust/cloud-storage/rpc/axum_rpc_parse/Cargo.toml
new file mode 100644
index 0000000000..c2e4be5dea
--- /dev/null
+++ b/rust/cloud-storage/rpc/axum_rpc_parse/Cargo.toml
@@ -0,0 +1,12 @@
+[package]
+edition = "2024"
+name = "axum_rpc_parse"
+publish = false
+version = "0.1.0"
+
+[dependencies]
+quote = { workspace = true }
+unsynn = { workspace = true }
+
+[dev-dependencies]
+cool_asserts = "2"
diff --git a/rust/cloud-storage/rpc/axum_rpc_parse/src/lib.rs b/rust/cloud-storage/rpc/axum_rpc_parse/src/lib.rs
new file mode 100644
index 0000000000..20ed8c5e59
--- /dev/null
+++ b/rust/cloud-storage/rpc/axum_rpc_parse/src/lib.rs
@@ -0,0 +1,523 @@
+use unsynn::*;
+
+keyword! {
+ pub KPub = "pub";
+ pub KIn = "in";
+ pub KRepr = "repr";
+ pub KRouter = "router";
+ pub KClient = "client";
+ pub KBindgen = "bindgen";
+ pub KIgnore = "ignore";
+ pub KDoc = "doc";
+ pub KTrait = "trait";
+ pub KWhere = "where";
+ pub KConst = "const";
+ pub KJson = "json";
+ pub KFn = "fn";
+ pub KImpl = "impl";
+ pub KFuture = "Future";
+ pub KOutput = "Output";
+ pub KResult = "Result";
+ pub KSelf = "self";
+ pub KType = "type";
+}
+
+operator! {
+ /// Represents the '=' operator.
+ Eq = "=";
+ /// Represents the ';' operator.
+ Semi = ";";
+ /// Represents the apostrophe '\'' operator.
+ Apostrophe = "'";
+ /// Represents the double semicolon '::' operator.
+ DoubleSemicolon = "::";
+ /// Represents the '&'
+ Ampersand = "&";
+}
+
+/// Represents a module path, consisting of an optional path separator followed by
+/// a path-separator-delimited sequence of identifiers.
+pub type ModPath = Cons<Option<PathSep>, DelimitedVec<Ident, PathSep>>;
+
+/// Represents type bounds, consisting of a colon followed by tokens until
+/// a comma, equals sign, or closing angle bracket is encountered.
+pub type Bounds = Cons<Colon, VerbatimUntil<Either<Comma, Eq, Gt>>>;
+
+/// Parses tokens and groups until `C` is found on the current token tree level.
+pub type VerbatimUntil<C> = Any<Cons<Except<C>, AngleTokenTree>>;
+
+/// Vector of `T` delimited by `;`
+pub type SemicolonDelimitedVec<T> = DelimitedVec<T, Semicolon, TrailingDelimiter::Mandatory>;
+
+unsynn! {
+
+/// Represents visibility modifiers for items.
+enum Vis {
+ /// `pub(in? crate::foo::bar)`/`pub(in? ::foo::bar)`
+ PubIn(Cons<KPub, ParenthesisGroupContaining<Cons<Option<KIn>, ModPath>>>),
+ /// Public visibility, indicated by the "pub" keyword.
+ Pub(KPub),
+}
+
+/// Represents an attribute annotation on a field, typically in the form `#[attr]`.
+pub struct Attribute {
+ /// The pound sign preceding the attribute.
+ pub _pound: Pound,
+ /// The content of the attribute enclosed in square brackets.
+ pub body: BracketGroupContaining<AttributeInner>,
+}
+
+/// Represents the inner content of an attribute annotation.
+pub enum AttributeInner {
+ /// A server attribute that can contain specialized metadata.
+ Router(RouterAttr),
+
+ /// A documentation attribute typically used for generating documentation.
+ Doc(DocInner),
+ /// A representation attribute that specifies how data should be laid out.
+ Repr(ReprInner),
+ /// Any other attribute represented as a sequence of token trees.
+ Any(Vec<TokenTree>),
+}
+
+
+
+pub struct RouterAttr {
+ /// The keyword for the router attribute.
+ _router: KRouter,
+ /// The inner content of the client attribute.
+ pub inner: ParenthesisGroupContaining<CommaDelimitedVec<RouterInner>>,
+}
+
+pub enum RouterInner {
+ ClientDirective(ClientDirective),
+ JsonDirective(KJson),
+}
+
+pub struct ClientDirective {
+ _client: KClient,
+ pub inner: Option<ParenthesisGroupContaining<ClientDirectiveValue>>
+}
+
+pub struct ClientDirectiveValue {
+ bindgen: KBindgen
+}
+
+/// Represents documentation for an item.
+pub struct DocInner {
+ /// The "doc" keyword.
+ pub _kw_doc: KDoc,
+ /// The equality operator.
+ pub _eq: Eq,
+ /// The documentation content as a literal string.
+ pub value: LiteralString,
+}
+
+/// Represents the inner content of a `repr` attribute, typically used for specifying
+/// memory layout or representation hints.
+pub struct ReprInner {
+ /// The "repr" keyword.
+ pub _kw_repr: KRepr,
+ /// The representation attributes enclosed in parentheses.
+ pub attr: ParenthesisGroupContaining<CommaDelimitedVec<Ident>>,
+}
+
+/// Represents an associated type in a trait.
+pub struct AssociatedType {
+ /// Zero or more attributes (including doc comments)
+ pub attributes: Option<Many<Attribute>>,
+ /// The "type" keyword.
+ pub _type: KType,
+ /// The name of the associated type.
+ pub name: Ident,
+ /// Optional bounds and default type.
+ pub rest: VerbatimUntil<Semicolon>,
+}
+
+pub struct TraitFn {
+ /// Zero or more attributes (including doc comments)
+ pub attributes: Option<Many<Attribute>>,
+ pub _fn: KFn,
+ /// the name of the function
+ pub name: Ident,
+ /// Generic parameters for the trait, if any.
+ pub generics: Option<GenericParams>,
+ /// The representation attributes enclosed in parentheses.
+ pub args: ParenthesisGroupContaining<Cons<Receiver, CommaDelimitedVec<FnArg>, Option<Comma>>>,
+ pub return_type: AsyncReturnType,
+}
+
+pub struct AsyncReturnType {
+ _arrow: RArrow,
+ _impl: KImpl,
+ _fut: KFuture,
+ _lt: Lt,
+ _output: KOutput,
+ _eq: Eq,
+ _res: KResult,
+ _lt2: Lt,
+ pub ok: VerbatimUntil<Comma>,
+ _comma: Comma,
+ pub err: AngleTokenTree,
+ _gt: Gt,
+ _gt2: Gt,
+ pub rest: VerbatimUntil<Semicolon>,
+}
+
+pub struct Receiver {
+ _amp: Ampersand,
+ _self: KSelf,
+ _comma: Option<Comma>
+}
+
+pub struct FnArg {
+ pub attr: Option<Many<Attribute>>,
+ pub name: Ident,
+ _colon: Colon,
+ pub val: ModPath
+}
+
+/// Represents an item within a trait body.
+pub enum TraitItem {
+ /// An associated type declaration.
+ AssociatedType(AssociatedType),
+ /// A trait function.
+ Fn(TraitFn),
+}
+
+/// Represents a trait definition.
+pub struct Trait {
+ /// Attributes applied to the struct.
+ pub attributes: Option<Many<Attribute>>,
+ /// The visibility modifier of the struct (e.g., `pub`).
+ pub vis: Option<Vis>,
+ /// The "struct" keyword.
+ pub _kw_struct: KTrait,
+ /// The name of the struct.
+ pub name: Ident,
+ /// Generic parameters for the trait, if any.
+ pub generics: Option<GenericParams>,
+
+ pub super_traits: Option<Cons<Colon, VerbatimUntil<Either<KWhere, BraceGroup>>>>,
+
+ /// Optional where clauses.
+ pub clauses: Option<WhereClauses>,
+ /// The enum variants enclosed in braces `{}`.
+ pub body: BraceGroupContaining<SemicolonDelimitedVec<TraitItem>>,
+}
+
+/// Represents a `where` clause attached to a definition.
+/// e.g., `where T: Trait, 'a: 'b`.
+#[derive(Clone)]
+pub struct WhereClauses {
+ /// The `where` keyword.
+ pub _kw_where: KWhere,
+ /// The comma-delimited list of where clause predicates.
+ pub clauses: CommaDelimitedVec<WhereClause>,
+}
+
+/// Represents a single predicate within a `where` clause.
+/// e.g., `T: Trait` or `'a: 'b`.
+#[derive(Clone)]
+pub struct WhereClause {
+ // FIXME: This likely breaks for absolute `::` paths
+ /// The type or lifetime being constrained (e.g., `T` or `'a`).
+ pub _pred: VerbatimUntil<Colon>,
+ /// The colon separating the constrained item and its bounds.
+ pub _colon: Colon,
+ /// The bounds applied to the type or lifetime (e.g., `Trait` or `'b`).
+ pub bounds: VerbatimUntil<Either<Comma, Semicolon, BraceGroup>>,
+}
+
+/// Represents the generic parameters of a struct or enum definition, enclosed in angle brackets.
+/// e.g., `<'a, T: Trait, const N: usize>`.
+pub struct GenericParams {
+ /// The opening angle bracket `<`.
+ pub _lt: Lt,
+ /// The comma-delimited list of generic parameters.
+ pub params: CommaDelimitedVec<GenericParam>,
+ /// The closing angle bracket `>`.
+ pub _gt: Gt,
+}
+
+/// Represents a single generic parameter within a `GenericParams` list.
+pub enum GenericParam {
+ /// A lifetime parameter, e.g., `'a` or `'a: 'b + 'c`.
+ Lifetime {
+ /// The lifetime identifier (e.g., `'a`).
+ name: Lifetime,
+ /// Optional lifetime bounds (e.g., `: 'b + 'c`).
+ bounds: Option<Cons<Colon, VerbatimUntil<Either<Comma, Gt>>>>,
+ },
+ /// A const generic parameter, e.g., `const N: usize = 10`.
+ Const {
+ /// The `const` keyword.
+ _const: KConst,
+ /// The name of the const parameter (e.g., `N`).
+ name: Ident,
+ /// The colon separating the name and type.
+ _colon: Colon,
+ /// The type of the const parameter (e.g., `usize`).
+ typ: VerbatimUntil<Either<Comma, Gt, Eq>>,
+ /// An optional default value (e.g., `= 10`).
+ default: Option<Cons<Eq, VerbatimUntil<Either<Comma, Gt>>>>,
+ },
+ /// A type parameter, e.g., `T: Trait = DefaultType`.
+ Type {
+ /// The name of the type parameter (e.g., `T`).
+ name: Ident,
+ /// Optional type bounds (e.g., `: Trait`).
+ bounds: Option<Bounds>,
+ /// An optional default type (e.g., `= DefaultType`).
+ default: Option<Cons<Eq, VerbatimUntil<Either<Comma, Gt>>>>,
+ },
+}
+
+/// Represents a lifetime annotation, like `'a`.
+pub struct Lifetime {
+ /// The apostrophe `'` starting the lifetime.
+ pub _apostrophe: PunctJoint<'\''>,
+ /// The identifier name of the lifetime (e.g., `a`).
+ pub name: Ident,
+}
+
+/// Parses either a `TokenTree` or `<...>` grouping (which is not a [`Group`] as far as proc-macros
+/// are concerned).
+#[derive(Clone)]
+pub struct AngleTokenTree(
+ #[allow(clippy::type_complexity)] // look,
+ pub Either<Cons<Lt, Vec<Cons<Except<Gt>, AngleTokenTree>>, Gt>, TokenTree>,
+);
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use cool_asserts::assert_matches;
+ use unsynn::ToTokens;
+
+ static TRAIT_FN: &str = r#"
+ fn hello(
+ &self,
+ arg: Arg,
+ ) -> impl Future<Output = Result<String, MyErr>> + Send;
+ "#;
+
+ #[test]
+ fn it_parses_trait_fn() {
+ let mut token_iter = TRAIT_FN.to_token_iter();
+ let f: Cons<SemicolonDelimitedVec<TraitItem>, EndOfStream> = token_iter.parse().unwrap();
+ assert_matches!(&f.first.first().unwrap().value, TraitItem::Fn(TraitFn { attributes: None, _fn, name: _, generics: None, args: ParenthesisGroupContaining { content: Cons { first: _, second, third: _, .. } }, return_type: _ }) => {
+ let arg = second.first().unwrap();
+ assert_eq!(arg.value.name.to_string(), "arg");
+ dbg!(arg);
+ });
+ }
+
+ #[test]
+ fn it_parses_multiple_trait_fn() {
+ let input = r#"
+ fn method(&self) -> impl Future<Output = Result<String, String>> + Send;
+ fn method2(&self, req: String) -> impl Future<Output = Result<String, String>> + Send;
+ "#;
+ let mut token_iter = input.to_token_iter();
+ let _result: Cons<SemicolonDelimitedVec<TraitItem>, EndOfStream> =
+ token_iter.parse().unwrap();
+ }
+
+ #[test]
+ fn it_parses_mod_path() {
+ let mut token_iter = "axum::http::HeaderMap".to_token_iter();
+ let m: ModPath = token_iter.parse().unwrap();
+ assert_matches!(m, Cons { first: None, second, .. } => {
+ let f = second.first().unwrap().value.to_string();
+ assert_eq!(f, "axum");
+ let f = second.get(1).unwrap().value.to_string();
+ assert_eq!(f, "http");
+ let f = second.get(2).unwrap().value.to_string();
+ assert_eq!(f, "HeaderMap");
+ });
+ }
+
+ #[test]
+ fn it_parses_trait_without_super_traits() {
+ let input = r#"
+ pub trait MyTrait {
+ type ServerContext;
+ fn method(&self) -> impl Future<Output = Result<String, String>> + Send;
+ }
+ "#;
+ let mut token_iter = input.to_token_iter();
+ let result: Result<Cons<Trait, EndOfStream>> = token_iter.parse();
+ if let Err(e) = &result {
+ eprintln!("Parse error: {}", e);
+ }
+ assert!(result.is_ok(), "Failed to parse trait without super traits");
+ }
+
+ #[test]
+ fn it_parses_trait_with_super_traits() {
+ let input = r#"
+ pub trait MyTrait: Send + Sync {
+ type ServerContext: 'static;
+ fn method(&self) -> impl Future<Output = Result<String, String>> + Send;
+ fn method2(&self, req: String) -> impl Future<Output = Result<String, String>> + Send;
+ }
+ "#;
+ let mut token_iter = input.to_token_iter();
+ let result: Result<Cons<Trait, EndOfStream>> = token_iter.parse();
+ if let Err(e) = &result {
+ eprintln!("Parse error with super traits: {}", e);
+ }
+ assert!(result.is_ok(), "Failed to parse trait with super traits");
+ }
+
+ #[test]
+ fn it_parses_associated_type() {
+ let input = r#"
+ type ServerContext: 'static;
+ "#;
+ let mut token_iter = input.to_token_iter();
+ let result: Result<Cons<TraitItem, Semicolon, EndOfStream>> = token_iter.parse();
+ result.unwrap();
+ }
+
+ #[test]
+ fn it_parses_associated_type_directly() {
+ let input = r#"type A;"#;
+ let mut token_iter = input.to_token_iter();
+ let result: Result<Cons<AssociatedType, Semicolon, EndOfStream>> = token_iter.parse();
+ if let Err(e) = &result {
+ eprintln!("Parse error direct: {}", e);
+ }
+ result.unwrap();
+ }
+
+ #[test]
+ fn it_parses_one_associated_type_in_vec() {
+ let input = r#"
+ type A;
+ "#;
+ let mut token_iter = input.to_token_iter();
+ let result: Result<Cons<SemicolonDelimitedVec<TraitItem>, EndOfStream>> =
+ token_iter.parse();
+ if let Err(e) = &result {
+ eprintln!("Parse error: {}", e);
+ }
+ result.unwrap();
+ }
+
+ #[test]
+ fn it_parses_two_associated_types() {
+ let input = r#"
+ type A: 'static;
+ type B;
+ "#;
+ let mut token_iter = input.to_token_iter();
+ let result: Result<Cons<SemicolonDelimitedVec<TraitItem>, EndOfStream>> =
+ token_iter.parse();
+ if let Err(e) = &result {
+ eprintln!("Parse error: {}", e);
+ }
+ result.unwrap();
+ }
+
+ #[test]
+ fn it_parses_trait_body() {
+ let input = r#"
+ {
+ fn method(&self) -> impl Future<Output = Result<String, String>> + Send;
+ fn patch_user_group(
+ &self,
+ req: PatchUserGroupRequest,
+ ) -> impl Future<Output = Result<(), LegacyPermErr>> + Send;
+ }
+ "#;
+
+ let mut token_iter = input.to_token_iter();
+ let result: Result<
+ Cons<BraceGroupContaining<SemicolonDelimitedVec<TraitItem>>, EndOfStream>,
+ > = token_iter.parse();
+ result.unwrap();
+ }
+
+ #[test]
+ fn it_parses_trait_body2() {
+ let input = r#"
+ {
+ fn method(&self) -> impl Future<Output = Result<String, String>> + Send;
+ fn patch_user_group(
+ &self,
+ req: String,
+ ) -> impl Future<Output = Result<String, String>> + Send;
+ }
+ "#;
+
+ let mut token_iter = input.to_token_iter();
+ let result: Result<
+ Cons<BraceGroupContaining<SemicolonDelimitedVec<TraitItem>>, EndOfStream>,
+ > = token_iter.parse();
+ result.unwrap();
+ }
+
+ #[test]
+ fn it_parses_full_trait() {
+ let input = r#"
+ pub trait LegacyGqlRpc: Send + Sync + 'static {
+ type ServerContext: 'static;
+ fn get_legacy_user_permissions(
+ &self,
+ ) -> impl Future<Output = Result<GetLegacyUserPermissionsResponse, LegacyPermErr>> + Send;
+ fn get_user_organization(
+ &self,
+ ) -> impl Future<Output = Result<UserOrganizationResponse, LegacyPermErr>> + Send;
+ fn patch_user_group(
+ &self,
+ req: PatchUserGroupRequest,
+ ) -> impl Future<Output = Result<(), LegacyPermErr>> + Send;
+ fn patch_user_onboarding(
+ &self,
+ req: PatchUserOnboardingRequest,
+ ) -> impl Future<Output = Result<(), LegacyPermErr>> + Send;
+ }
+ "#;
+
+ let mut token_iter = input.to_token_iter();
+ let result: Cons<Trait, EndOfStream> = token_iter.parse().unwrap();
+ }
+
+ #[test]
+ fn it_parses_advanced() {
+ let input = r#"
+
+pub trait LegacyGqlRpc: Send + Sync + 'static {
+ type GetPermsExtractor: 'static;
+
+ fn get_legacy_user_permissions(
+ &self,
+ ctx: Self::GetPermsExtractor,
+ ) -> impl Future<Output = Result<GetLegacyUserPermissionsResponse, LegacyPermErr>> + Send;
+
+ type OrgExtractor: 'static;
+
+ fn get_user_organization(
+ &self,
+ ctx: Self::OrgExtractor,
+ ) -> impl Future<Output = Result<Option<UserOrganizationResponse>, LegacyPermErr>> + Send;
+
+ fn patch_user_group(
+ &self,
+ req: PatchUserGroupRequest,
+ ) -> impl Future<Output = Result<(), LegacyPermErr>> + Send;
+
+ fn patch_user_onboarding(
+ &self,
+ req: PatchUserOnboardingRequest,
+ ) -> impl Future<Output = Result<(), LegacyPermErr>> + Send;
+}
+ "#;
+
+ let mut token_iter = input.to_token_iter();
+ let result: Cons<Trait, EndOfStream> = token_iter.parse().unwrap();
+ }
+}
diff --git a/rust/cloud-storage/unfurl_service/Cargo.toml b/rust/cloud-storage/unfurl_service/Cargo.toml
index 9144e7e4fa..f275799ce4 100644
--- a/rust/cloud-storage/unfurl_service/Cargo.toml
+++ b/rust/cloud-storage/unfurl_service/Cargo.toml
@@ -11,7 +11,7 @@ mock = []
anyhow = { workspace = true }
axum = { workspace = true }
futures = { workspace = true }
-http = "1.3.1"
+http = { workspace = true }
http-body-util = { workspace = true }
macro_cors = { path = "../macro_cors" }
macro_entrypoint = { path = "../macro_entrypoint" }