Files
derive_http/src/lib.rs

227 lines
8.2 KiB
Rust
Raw Normal View History

2025-07-03 15:03:18 -04:00
use proc_macro::TokenStream;
use quote::quote;
2025-07-14 21:21:29 -04:00
use syn::{parse_macro_input, ItemEnum, DeriveInput, Fields, Data};
2025-07-03 15:03:18 -04:00
2025-07-14 20:39:06 -04:00
2025-07-14 21:25:53 -04:00
2025-07-14 20:10:31 -04:00
#[proc_macro_attribute]
pub fn http_response(_attr: TokenStream, item: TokenStream) -> TokenStream {
2025-07-14 20:39:06 -04:00
let item_for_ast = item.clone();
let item_for_quote = item.clone();
2025-07-10 16:34:43 -04:00
2025-07-14 20:10:31 -04:00
let ast: DeriveInput = parse_macro_input!(item_for_ast as DeriveInput);
let name = &ast.ident;
2025-07-03 15:03:18 -04:00
2025-07-14 20:10:31 -04:00
let impl_block = match &ast.data {
Data::Struct(_) => {
2025-07-14 21:25:53 -04:00
// Impl for struct: deserialize entire response body as Self
2025-07-03 15:03:18 -04:00
quote! {
2025-07-14 21:18:57 -04:00
#[async_trait::async_trait]
2025-07-14 20:10:31 -04:00
impl Responsable for #name
2025-07-14 20:01:38 -04:00
where
2025-07-14 21:18:57 -04:00
Self: serde::de::DeserializeOwned + Sized + Send,
2025-07-14 20:01:38 -04:00
{
2025-07-14 21:18:57 -04:00
async fn receive(mut resp: actix_web::ClientResponse) -> Result<Self, Box<dyn std::error::Error>> {
2025-07-14 21:25:53 -04:00
let parsed = resp.json::<Self>().await?;
2025-07-14 20:10:31 -04:00
Ok(parsed)
2025-07-03 15:03:18 -04:00
}
}
}
}
Data::Enum(data_enum) => {
2025-07-14 21:25:53 -04:00
// Impl for enum with tuple variants of length 1 (newtype variants)
2025-07-14 20:10:31 -04:00
let variant_arms = data_enum.variants.iter().filter_map(|variant| {
2025-07-03 15:03:18 -04:00
let vname = &variant.ident;
2025-07-14 21:25:53 -04:00
match &variant.fields {
Fields::Unnamed(fields) if fields.unnamed.len() == 1 => {
let inner_ty = &fields.unnamed.first().unwrap().ty;
Some(quote! {
2025-07-14 21:14:28 -04:00
if let Ok(inner) = serde_json::from_slice::<#inner_ty>(&body) {
2025-07-14 20:10:31 -04:00
return Ok(#name::#vname(inner));
}
})
}
2025-07-14 21:25:53 -04:00
_ => None,
}
});
quote! {
2025-07-14 21:18:57 -04:00
#[async_trait::async_trait]
2025-07-14 21:20:46 -04:00
impl Responsable for #name
where
Self: Sized + Send,
{
2025-07-14 21:18:57 -04:00
async fn receive(mut resp: actix_web::ClientResponse) -> Result<Self, Box<dyn std::error::Error>> {
2025-07-14 21:29:24 -04:00
let body = resp.body().await?; // Bytes, sized!
2025-07-14 20:10:31 -04:00
#(#variant_arms)*
2025-07-14 20:39:06 -04:00
Err(Box::new(std::io::Error::new(
std::io::ErrorKind::Other,
2025-07-14 20:10:31 -04:00
concat!("No matching enum variant in ", stringify!(#name))
2025-07-14 20:39:06 -04:00
)))
}
}
}
}
2025-07-14 20:39:06 -04:00
_ => panic!("#[http_response] only supports structs and tuple-style enum variants"),
2025-07-03 15:03:18 -04:00
};
2025-07-14 20:10:31 -04:00
let original: syn::Item = syn::parse(item_for_quote).expect("Failed to parse item as syn::Item");
2025-07-10 17:10:31 -04:00
2025-07-14 20:10:31 -04:00
let output = quote! {
#original
#impl_block
2025-07-10 17:10:31 -04:00
};
2025-07-14 20:10:31 -04:00
output.into()
2025-07-10 17:10:31 -04:00
}
2025-07-14 21:14:28 -04:00
2025-07-10 17:10:31 -04:00
#[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<Self>.
/// Assumes `Self` implements `DeserializeOwned`.
pub async fn response_vec(
2025-07-13 09:45:30 -04:00
responses: Vec<awc::ClientResponse>,
) -> Result<Vec<Self>, std::error::Error>
2025-07-10 17:10:31 -04:00
where
Self: Sized + serde::de::DeserializeOwned,
{
let mut results = Vec::with_capacity(responses.len());
for resp in responses {
let item = resp.json::<Self>().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<dyn std::error::Error>> {
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
2025-07-13 09:45:30 -04:00
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<dyn Read> = 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<Query>
let queries: Vec<Query> = 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)
}