use proc_macro::TokenStream; use quote::quote; use syn::{parse_macro_input, ItemEnum, DeriveInput, Fields, Data}; #[proc_macro_attribute] pub fn http_response(_attr: TokenStream, item: TokenStream) -> TokenStream { let item_for_ast = item.clone(); let item_for_quote = item.clone(); let ast: DeriveInput = parse_macro_input!(item_for_ast as DeriveInput); let name = &ast.ident; let impl_block = match &ast.data { Data::Struct(_) => { // Impl for struct: deserialize entire response body as Self quote! { #[async_trait::async_trait] impl Responsable for #name where Self: serde::de::DeserializeOwned + Sized + Send, { async fn receive(mut resp: actix_web::ClientResponse) -> Result> { let parsed = resp.json::().await?; Ok(parsed) } } } } Data::Enum(data_enum) => { // Impl for enum with tuple variants of length 1 (newtype variants) let variant_arms = data_enum.variants.iter().filter_map(|variant| { let vname = &variant.ident; match &variant.fields { Fields::Unnamed(fields) if fields.unnamed.len() == 1 => { let inner_ty = &fields.unnamed.first().unwrap().ty; Some(quote! { if let Ok(inner) = serde_json::from_slice::<#inner_ty>(&body) { return Ok(#name::#vname(inner)); } }) } _ => None, } }); quote! { #[async_trait::async_trait] impl Responsable for #name where Self: Sized + Send, { async fn receive(mut resp: actix_web::ClientResponse) -> Result> { let body = resp.body().await?; #(#variant_arms)* Err(Box::new(std::io::Error::new( std::io::ErrorKind::Other, concat!("No matching enum variant in ", stringify!(#name)) ))) } } } } _ => panic!("#[http_response] only supports structs and tuple-style enum variants"), }; let original: syn::Item = syn::parse(item_for_quote).expect("Failed to parse item as syn::Item"); let output = quote! { #original #impl_block }; output.into() } #[proc_macro_derive(ResponseVec)] pub fn derive_response_vec(input: TokenStream) -> TokenStream { let input = parse_macro_input!(input as DeriveInput); let name = &input.ident; let expanded = quote! { impl #name { /// Deserializes all responses sequentially into a Vec. /// Assumes `Self` implements `DeserializeOwned`. pub async fn response_vec( responses: Vec, ) -> Result, std::error::Error> where Self: Sized + serde::de::DeserializeOwned, { let mut results = Vec::with_capacity(responses.len()); for resp in responses { let item = resp.json::().await?; results.push(item); } Ok(results) } } }; TokenStream::from(expanded) } #[proc_macro_attribute] pub fn alpaca_cli(_attr: TokenStream, item: TokenStream) -> TokenStream { let input_enum = parse_macro_input!(item as ItemEnum); let enum_name = &input_enum.ident; let variants = &input_enum.variants; // Match arms for regular command variants (Single, Asset, etc.) let regular_arms = variants.iter().filter_map(|v| { let v_name = &v.ident; // Skip Bulk variant — we handle it separately if v_name == "Bulk" { return None; } Some(quote! { #enum_name::#v_name(req) => { let res = req.send(client.clone(), &api_key).await?; let body = res.body().await?; println!("{}", std::str::from_utf8(&body)?); } }) }); let expanded = quote! { #[derive(structopt::StructOpt, Debug)] #input_enum #[tokio::main] async fn main() -> Result<(), Box> { use structopt::StructOpt; use std::fs::File; use std::io::{BufReader, Read}; use std::sync::Arc; use std::thread; const THREADS: usize = 4; // Initialize shared HTTP client and API key let client = Arc::new(awc::Client::default()); let api_key = std::env::var("APCA_API_KEY_ID")?; let cmd = #enum_name::from_args(); match cmd { #(#regular_arms)* #enum_name::Bulk { input } => { // Choose input source: file or stdin let mut reader: Box = match input { Some(path) => Box::new(File::open(path)?), None => Box::new(std::io::stdin()), }; // Read input JSON into buffer let mut buf = String::new(); reader.read_to_string(&mut buf)?; // Deserialize into Vec let queries: Vec = serde_json::from_str(&buf)?; let total = queries.len(); if total == 0 { eprintln!("No queries provided."); return Ok(()); } let shared_queries = Arc::new(queries); let shared_key = Arc::new(api_key); let per_thread = total / THREADS; let mut handles = Vec::with_capacity(THREADS); for i in 0..THREADS { let queries_clone = Arc::clone(&shared_queries); let client_clone = Arc::clone(&client); let key_clone = Arc::clone(&shared_key); let start_index = i * per_thread; let end_index = if i == THREADS - 1 { total // Last thread gets the remainder } else { start_index + per_thread }; let handle = thread::spawn(move || { let rt = tokio::runtime::Runtime::new().expect("Failed to create runtime"); for idx in start_index..end_index { let query = &queries_clone[idx]; let send_result = rt.block_on(query.send(client_clone.clone(), &key_clone)); match send_result { Ok(response) => { let body_result = rt.block_on(response.body()); match body_result { Ok(body) => println!("{}", String::from_utf8_lossy(&body)), Err(e) => eprintln!("Error reading response body: {:?}", e), } } Err(e) => { eprintln!("Request failed: {:?}", e); } } } }); handles.push(handle); } // Wait for all threads to complete for handle in handles { handle.join().expect("A thread panicked"); } } } Ok(()) } }; TokenStream::from(expanded) }