use crate::parse::{MethodInfo, ParamInfo};
use proc_macro2::{Span, TokenStream};
use proc_macro_crate::{crate_name, FoundCrate};
use quote::{format_ident, quote};
use syn::Type;
pub(crate) fn resolve_client_path(err_span: Span) -> syn::Result<syn::Path> {
match crate_name("plexus-client") {
Ok(FoundCrate::Itself) => Ok(syn::parse_quote!(crate)),
Ok(FoundCrate::Name(name)) => {
let ident = syn::Ident::new(&name, err_span);
Ok(syn::parse_quote!(::#ident))
}
Err(e) => Err(syn::Error::new(
err_span,
format!(
"#[plexus_macros::activation(client)] could not locate the \
`plexus-client` dependency in Cargo.toml ({e}). The generated \
client links against it. Add `plexus-client` as a dependency, \
or remove the `client` flag."
),
)),
}
}
fn is_option_type(ty: &Type) -> bool {
let Type::Path(p) = ty else { return false };
p.qself.is_none()
&& p.path
.segments
.last()
.is_some_and(|s| s.ident == "Option" && matches!(s.arguments, syn::PathArguments::AngleBracketed(_)))
}
fn param_insert(param: &ParamInfo, client: &syn::Path) -> TokenStream {
let ident = ¶m.name;
let wire_name = param.name.to_string();
if is_option_type(¶m.ty) {
quote! {
if let ::core::option::Option::Some(__v) = #ident {
match #client::__rt::serde_json::to_value(__v) {
::core::result::Result::Ok(__json) => {
__params.insert(#wire_name.to_string(), __json);
}
::core::result::Result::Err(__e) => {
return #client::error_stream(#client::ClientError::Encode {
param: #wire_name,
message: __e.to_string(),
});
}
}
}
}
} else {
quote! {
match #client::__rt::serde_json::to_value(#ident) {
::core::result::Result::Ok(__json) => {
__params.insert(#wire_name.to_string(), __json);
}
::core::result::Result::Err(__e) => {
return #client::error_stream(#client::ClientError::Encode {
param: #wire_name,
message: __e.to_string(),
});
}
}
}
}
}
fn method_const_ident(m: &MethodInfo) -> syn::Ident {
format_ident!("METHOD_{}", m.method_name.to_uppercase().replace(['.', '-'], "_"))
}
pub(crate) fn generate(
struct_name: &syn::Ident,
namespace: &str,
methods: &[MethodInfo],
client_path: &syn::Path,
) -> syn::Result<TokenStream> {
let client_ty = format_ident!("{}Client", struct_name);
let mut method_items: Vec<TokenStream> = Vec::new();
let mut consts: Vec<TokenStream> = Vec::new();
for m in methods {
let Some(event_ty) = &m.stream_item_type else {
return Err(syn::Error::new(
m.fn_name.span(),
format!(
"#[plexus_macros::activation(client)]: method `{}` does not return \
`impl Stream<Item = ..>`, so the generated client has no event type \
for it. Give it a stream return type, or remove the `client` flag \
from the activation.",
m.method_name
),
));
};
let fn_ident = &m.fn_name;
let all_ident = format_ident!("{}_all", m.fn_name);
let const_ident = method_const_ident(m);
let wire_method = &m.method_name;
let sig_params: Vec<TokenStream> = m
.params
.iter()
.map(|p| {
let name = &p.name;
let ty = &p.ty;
quote! { #name: #ty }
})
.collect();
let arg_names: Vec<&syn::Ident> = m.params.iter().map(|p| &p.name).collect();
let inserts: Vec<TokenStream> = m
.params
.iter()
.map(|p| param_insert(p, client_path))
.collect();
let doc = if m.description.is_empty() {
format!("Calls `{namespace}.{wire_method}`.")
} else {
format!("{}\n\nCalls `{namespace}.{wire_method}`.", m.description)
};
let doc_all = format!(
"{doc}\n\nDrives the stream to completion and collects every data event."
);
consts.push(quote! {
#[doc = #doc]
pub const #const_ident: #client_path::MethodRef =
#client_path::MethodRef::new(#namespace, #wire_method);
});
method_items.push(quote! {
#[allow(clippy::too_many_arguments)]
#[doc = #doc]
pub fn #fn_ident(&self #(, #sig_params)*)
-> #client_path::EventStream<'_, #event_ty>
{
let mut __params = #client_path::__rt::serde_json::Map::new();
#(#inserts)*
#client_path::decode::<#event_ty>(
#client_path::Transport::call(
&self.transport,
Self::#const_ident,
#client_path::__rt::serde_json::Value::Object(__params),
)
)
}
#[allow(clippy::too_many_arguments)]
#[doc = #doc_all]
pub async fn #all_ident(&self #(, #sig_params)*)
-> ::core::result::Result<
::std::vec::Vec<#event_ty>,
#client_path::ClientError,
>
{
#client_path::collect_data(self.#fn_ident(#(#arg_names),*)).await
}
});
}
let struct_doc = format!(
"Typed client for the `{namespace}` activation, generated by \
`#[plexus_macros::activation(client)]`.\n\n\
Generic over the transport: construct it with any \
`plexus_client::Transport` — in-process for tests, WebSocket \
JSON-RPC or REST + SSE against a server.\n\n\
The parameter and event types are the activation's own, so a change \
to a method or an event is a compile error here, not a runtime \
surprise."
);
Ok(quote! {
#[doc = #struct_doc]
#[derive(Debug, Clone, Copy, Default)]
pub struct #client_ty<T> {
transport: T,
}
impl<T> #client_ty<T> {
pub const NAMESPACE: &'static str = #namespace;
pub fn new(transport: T) -> Self {
Self { transport }
}
pub fn transport(&self) -> &T {
&self.transport
}
pub fn into_transport(self) -> T {
self.transport
}
}
impl<T: #client_path::Transport> #client_ty<T> {
#(#consts)*
#(#method_items)*
}
})
}