hyprstream_rpc_derive/lib.rs
1//! Derive macros for Cap'n Proto serialization.
2//!
3//! Provides `#[derive(ToCapnp)]` and `#[derive(FromCapnp)]` for automatic
4//! serialization/deserialization between Rust types and Cap'n Proto messages.
5//!
6//! # Example
7//!
8//! ```ignore
9//! use hyprstream_rpc::prelude::*;
10//!
11//! #[derive(ToCapnp)]
12//! #[capnp(my_schema_capnp::my_request)]
13//! pub struct MyRequest {
14//! pub name: String,
15//! pub count: u32,
16//! }
17//!
18//! #[derive(FromCapnp)]
19//! #[capnp(my_schema_capnp::my_response)]
20//! pub struct MyResponse {
21//! pub result: String,
22//! pub success: bool,
23//! }
24//! ```
25
26use proc_macro::TokenStream;
27use quote::{format_ident, quote};
28use syn::{parse_macro_input, Attribute, Data, DeriveInput, Expr, ExprPath, Fields, Meta};
29
30mod codegen;
31mod resolve;
32mod schema;
33mod util;
34
35/// Derive macro for serializing Rust types to Cap'n Proto.
36///
37/// Generates an implementation of `ToCapnp` trait that writes struct fields
38/// to a Cap'n Proto builder.
39///
40/// # Attributes
41///
42/// - `#[capnp(path::to::schema)]` - Required. Specifies the Cap'n Proto schema path.
43/// - `#[capnp(skip)]` on field - Skip this field during serialization.
44/// - `#[capnp(rename = "other_name")]` on field - Use a different name for the setter.
45///
46/// # Example
47///
48/// ```ignore
49/// #[derive(ToCapnp)]
50/// #[capnp(registry_capnp::clone_request)]
51/// pub struct CloneRequest {
52/// pub url: String,
53/// pub name: String,
54/// pub shallow: bool,
55/// #[capnp(rename = "maxDepth")]
56/// pub depth: u32,
57/// }
58/// ```
59#[proc_macro_derive(ToCapnp, attributes(capnp))]
60pub fn derive_to_capnp(input: TokenStream) -> TokenStream {
61 let input = parse_macro_input!(input as DeriveInput);
62
63 let name = &input.ident;
64 let generics = &input.generics;
65 let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
66
67 // Parse #[capnp(path::to::schema)] attribute
68 let schema_path = match parse_capnp_attr(&input.attrs) {
69 Some(path) => path,
70 None => {
71 return syn::Error::new_spanned(
72 &input,
73 "ToCapnp requires #[capnp(path::to::schema)] attribute",
74 )
75 .to_compile_error()
76 .into();
77 }
78 };
79
80 // Generate field setters
81 let field_setters = match &input.data {
82 Data::Struct(data) => {
83 match &data.fields {
84 Fields::Named(fields) => {
85 fields
86 .named
87 .iter()
88 .filter_map(|f| {
89 let field_name = f.ident.as_ref()?;
90
91 // Check for enum_type (must come before skip check)
92 if let Some(capnp_enum_path) = get_enum_type(&f.attrs) {
93 let capnp_name = get_rename(&f.attrs)
94 .unwrap_or_else(|| to_accessor_name(&field_name.to_string()));
95 let setter = format_ident!("set_{}", capnp_name);
96 let ty = &f.ty;
97 return Some(generate_enum_setter(
98 field_name,
99 &setter,
100 ty,
101 &capnp_enum_path,
102 ));
103 }
104
105 // Check for skip
106 if has_skip_attr(&f.attrs) {
107 return None;
108 }
109
110 // Check for rename, otherwise use field name as-is
111 let capnp_name = get_rename(&f.attrs)
112 .unwrap_or_else(|| to_accessor_name(&field_name.to_string()));
113
114 let setter = format_ident!("set_{}", capnp_name);
115 let ty = &f.ty;
116
117 // Generate setter based on type
118 Some(generate_setter(field_name, &setter, ty))
119 })
120 .collect::<Vec<_>>()
121 }
122 _ => {
123 return syn::Error::new_spanned(
124 &input,
125 "ToCapnp only supports structs with named fields",
126 )
127 .to_compile_error()
128 .into();
129 }
130 }
131 }
132 _ => {
133 return syn::Error::new_spanned(&input, "ToCapnp only supports structs")
134 .to_compile_error()
135 .into();
136 }
137 };
138
139 let builder_path = quote! { #schema_path::Builder<'a> };
140
141 let expanded = quote! {
142 impl #impl_generics hyprstream_rpc::capnp::ToCapnp for #name #ty_generics #where_clause {
143 type Builder<'a> = #builder_path;
144
145 fn write_to(&self, builder: &mut Self::Builder<'_>) {
146 #(#field_setters)*
147 }
148 }
149 };
150
151 expanded.into()
152}
153
154/// Derive macro for deserializing Cap'n Proto to Rust types.
155///
156/// Generates an implementation of `FromCapnp` trait that reads struct fields
157/// from a Cap'n Proto reader.
158///
159/// # Attributes
160///
161/// - `#[capnp(path::to::schema)]` - Required. Specifies the Cap'n Proto schema path.
162/// - `#[capnp(skip)]` on field - Skip this field, use Default::default().
163/// - `#[capnp(rename = "other_name")]` on field - Use a different name for the getter.
164/// - `#[capnp(optional)]` on field - Field is Option<T>, handle missing gracefully.
165///
166/// # Example
167///
168/// ```ignore
169/// #[derive(FromCapnp)]
170/// #[capnp(registry_capnp::health_status)]
171/// pub struct HealthStatus {
172/// pub status: String,
173/// pub repository_count: u32,
174/// #[capnp(optional)]
175/// pub message: Option<String>,
176/// }
177/// ```
178#[proc_macro_derive(FromCapnp, attributes(capnp))]
179pub fn derive_from_capnp(input: TokenStream) -> TokenStream {
180 let input = parse_macro_input!(input as DeriveInput);
181
182 let name = &input.ident;
183 let generics = &input.generics;
184 let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
185
186 // Parse #[capnp(path::to::schema)] attribute
187 let schema_path = match parse_capnp_attr(&input.attrs) {
188 Some(path) => path,
189 None => {
190 return syn::Error::new_spanned(
191 &input,
192 "FromCapnp requires #[capnp(path::to::schema)] attribute",
193 )
194 .to_compile_error()
195 .into();
196 }
197 };
198
199 // Generate field readers
200 let field_readers = match &input.data {
201 Data::Struct(data) => {
202 match &data.fields {
203 Fields::Named(fields) => {
204 fields
205 .named
206 .iter()
207 .filter_map(|f| {
208 let field_name = f.ident.as_ref()?;
209
210 // Check for enum_type (must come before skip check)
211 if let Some(_capnp_enum_path) = get_enum_type(&f.attrs) {
212 let capnp_name = get_rename(&f.attrs)
213 .unwrap_or_else(|| to_accessor_name(&field_name.to_string()));
214 let getter = format_ident!("get_{}", capnp_name);
215 return Some(generate_enum_getter(field_name, &getter));
216 }
217
218 // Check for skip - use Default
219 if has_skip_attr(&f.attrs) {
220 return Some(quote! {
221 #field_name: Default::default(),
222 });
223 }
224
225 // Check for rename, otherwise use field name as-is
226 let capnp_name = get_rename(&f.attrs)
227 .unwrap_or_else(|| to_accessor_name(&field_name.to_string()));
228
229 let getter = format_ident!("get_{}", capnp_name);
230 let ty = &f.ty;
231 let is_optional = has_optional_attr(&f.attrs) || is_option_type(ty);
232
233 // Generate getter based on type
234 Some(generate_getter(field_name, &getter, ty, is_optional))
235 })
236 .collect::<Vec<_>>()
237 }
238 _ => {
239 return syn::Error::new_spanned(
240 &input,
241 "FromCapnp only supports structs with named fields",
242 )
243 .to_compile_error()
244 .into();
245 }
246 }
247 }
248 _ => {
249 return syn::Error::new_spanned(&input, "FromCapnp only supports structs")
250 .to_compile_error()
251 .into();
252 }
253 };
254
255 let reader_path = quote! { #schema_path::Reader<'a> };
256
257 let expanded = quote! {
258 impl #impl_generics hyprstream_rpc::capnp::FromCapnp for #name #ty_generics #where_clause {
259 type Reader<'a> = #reader_path;
260
261 fn read_from(reader: Self::Reader<'_>) -> anyhow::Result<Self> {
262 Ok(Self {
263 #(#field_readers)*
264 })
265 }
266 }
267 };
268
269 expanded.into()
270}
271
272/// Parse the #[capnp(path::to::schema)] attribute
273fn parse_capnp_attr(attrs: &[Attribute]) -> Option<ExprPath> {
274 for attr in attrs {
275 if attr.path().is_ident("capnp") {
276 if let Meta::List(list) = &attr.meta {
277 if let Ok(path) = syn::parse2::<ExprPath>(list.tokens.clone()) {
278 return Some(path);
279 }
280 }
281 }
282 }
283 None
284}
285
286/// Check if field has #[capnp(skip)] attribute
287fn has_skip_attr(attrs: &[Attribute]) -> bool {
288 for attr in attrs {
289 if attr.path().is_ident("capnp") {
290 if let Meta::List(list) = &attr.meta {
291 let tokens = list.tokens.to_string();
292 if tokens == "skip" {
293 return true;
294 }
295 }
296 }
297 }
298 false
299}
300
301/// Check if field has #[capnp(optional)] attribute
302fn has_optional_attr(attrs: &[Attribute]) -> bool {
303 for attr in attrs {
304 if attr.path().is_ident("capnp") {
305 if let Meta::List(list) = &attr.meta {
306 let tokens = list.tokens.to_string();
307 if tokens == "optional" {
308 return true;
309 }
310 }
311 }
312 }
313 false
314}
315
316/// Get rename value from #[capnp(rename = "name")] attribute
317fn get_rename(attrs: &[Attribute]) -> Option<String> {
318 for attr in attrs {
319 if attr.path().is_ident("capnp") {
320 if let Meta::List(list) = &attr.meta {
321 // Parse as key = value
322 if let Ok(Expr::Assign(assign)) = syn::parse2::<Expr>(list.tokens.clone()) {
323 if let Expr::Path(path) = &*assign.left {
324 if path.path.is_ident("rename") {
325 if let Expr::Lit(syn::ExprLit {
326 lit: syn::Lit::Str(s),
327 ..
328 }) = &*assign.right
329 {
330 return Some(s.value());
331 }
332 }
333 }
334 }
335 }
336 }
337 }
338 None
339}
340
341/// Get enum_type path from #[capnp(enum_type = "path::to::CapnpEnum")] attribute.
342///
343/// When present on a field, the derive macros generate enum conversion code
344/// using `Into` trait instead of skipping the field. Requires the user to
345/// implement `From<RustEnum> for CapnpEnum` and `From<CapnpEnum> for RustEnum`.
346fn get_enum_type(attrs: &[Attribute]) -> Option<syn::Path> {
347 for attr in attrs {
348 if attr.path().is_ident("capnp") {
349 if let Meta::List(list) = &attr.meta {
350 if let Ok(Expr::Assign(assign)) = syn::parse2::<Expr>(list.tokens.clone()) {
351 if let Expr::Path(path) = &*assign.left {
352 if path.path.is_ident("enum_type") {
353 if let Expr::Lit(syn::ExprLit {
354 lit: syn::Lit::Str(s),
355 ..
356 }) = &*assign.right
357 {
358 if let Ok(p) = syn::parse_str::<syn::Path>(&s.value()) {
359 return Some(p);
360 }
361 }
362 }
363 }
364 }
365 }
366 }
367 }
368 None
369}
370
371/// Cap'n Proto Rust uses snake_case for accessors.
372/// This function simply returns the name as-is.
373fn to_accessor_name(s: &str) -> String {
374 s.to_owned()
375}
376
377/// Check if type is Option<T>
378fn is_option_type(ty: &syn::Type) -> bool {
379 if let syn::Type::Path(type_path) = ty {
380 if let Some(segment) = type_path.path.segments.last() {
381 return segment.ident == "Option";
382 }
383 }
384 false
385}
386
387// ═══════════════════════════════════════════════════════════════════════════════
388// Type detection helpers
389// ═══════════════════════════════════════════════════════════════════════════════
390
391/// Check if type is String
392fn is_string_type(ty: &syn::Type) -> bool {
393 if let syn::Type::Path(type_path) = ty {
394 if let Some(segment) = type_path.path.segments.last() {
395 return segment.ident == "String";
396 }
397 }
398 false
399}
400
401/// Check if type is PathBuf
402fn is_pathbuf_type(ty: &syn::Type) -> bool {
403 if let syn::Type::Path(type_path) = ty {
404 if let Some(segment) = type_path.path.segments.last() {
405 return segment.ident == "PathBuf";
406 }
407 }
408 false
409}
410
411/// Check if type is DateTime (from chrono::DateTime<Utc>)
412fn is_datetime_type(ty: &syn::Type) -> bool {
413 if let syn::Type::Path(type_path) = ty {
414 if let Some(segment) = type_path.path.segments.last() {
415 return segment.ident == "DateTime";
416 }
417 }
418 false
419}
420
421/// Check if type is Vec<T>
422fn is_vec_type(ty: &syn::Type) -> bool {
423 if let syn::Type::Path(type_path) = ty {
424 if let Some(segment) = type_path.path.segments.last() {
425 return segment.ident == "Vec";
426 }
427 }
428 false
429}
430
431/// Check if type is Vec<String>
432fn is_vec_string_type(ty: &syn::Type) -> bool {
433 if let syn::Type::Path(type_path) = ty {
434 if let Some(segment) = type_path.path.segments.last() {
435 if segment.ident == "Vec" {
436 if let syn::PathArguments::AngleBracketed(args) = &segment.arguments {
437 if let Some(syn::GenericArgument::Type(inner)) = args.args.first() {
438 return is_string_type(inner);
439 }
440 }
441 }
442 }
443 }
444 false
445}
446
447/// Check if type is Vec<u8> (maps to Cap'n Proto Data)
448fn is_vec_u8_type(ty: &syn::Type) -> bool {
449 if let syn::Type::Path(type_path) = ty {
450 if let Some(segment) = type_path.path.segments.last() {
451 if segment.ident == "Vec" {
452 if let syn::PathArguments::AngleBracketed(args) = &segment.arguments {
453 if let Some(syn::GenericArgument::Type(syn::Type::Path(inner_path))) =
454 args.args.first()
455 {
456 if let Some(inner_seg) = inner_path.path.segments.last() {
457 return inner_seg.ident == "u8";
458 }
459 }
460 }
461 }
462 }
463 }
464 false
465}
466
467/// Extract the inner type from Vec<T> or Option<T>
468fn extract_inner_type(ty: &syn::Type) -> Option<&syn::Type> {
469 if let syn::Type::Path(type_path) = ty {
470 if let Some(segment) = type_path.path.segments.last() {
471 if segment.ident == "Vec" || segment.ident == "Option" {
472 if let syn::PathArguments::AngleBracketed(args) = &segment.arguments {
473 if let Some(syn::GenericArgument::Type(inner)) = args.args.first() {
474 return Some(inner);
475 }
476 }
477 }
478 }
479 }
480 None
481}
482
483/// Check if type is a known primitive (not a struct requiring FromCapnp/ToCapnp)
484fn is_known_primitive(ty: &syn::Type) -> bool {
485 if let syn::Type::Path(type_path) = ty {
486 if let Some(segment) = type_path.path.segments.last() {
487 let name = segment.ident.to_string();
488 return matches!(
489 name.as_str(),
490 "String"
491 | "bool"
492 | "u8"
493 | "u16"
494 | "u32"
495 | "u64"
496 | "i8"
497 | "i16"
498 | "i32"
499 | "i64"
500 | "f32"
501 | "f64"
502 | "PathBuf"
503 );
504 }
505 }
506 false
507}
508
509// ═══════════════════════════════════════════════════════════════════════════════
510// Code generation: setters (ToCapnp) and getters (FromCapnp)
511// ═══════════════════════════════════════════════════════════════════════════════
512
513/// Generate setter code for a field (ToCapnp)
514///
515/// Dispatch order:
516/// 1. String → set_field(&str)
517/// 2. PathBuf → set_field(path.to_str())
518/// 3. DateTime<Utc> → init Timestamp, set seconds + nanos
519/// 4. Vec<String> → init list, set text items
520/// 5. Option<String> → if let Some, set_field
521/// Option<DateTime> → if let Some, init Timestamp
522/// 6. Option<T> (struct) → if let Some, init + write_to
523/// 7. Vec<T> (struct) → init list, loop write_to
524/// 8. Vec<T> (primitive) → init list, loop set
525/// 9. Known primitive → direct set_field(value)
526/// 10. Fallback (struct) → init + write_to
527fn generate_setter(
528 field_name: &syn::Ident,
529 setter: &syn::Ident,
530 ty: &syn::Type,
531) -> proc_macro2::TokenStream {
532 // Derive init_field ident from set_field ident
533 let setter_str = setter.to_string();
534 let field_suffix = &setter_str["set_".len()..];
535 let initter = format_ident!("init_{}", field_suffix);
536
537 // 1. String
538 if is_string_type(ty) {
539 return quote! {
540 builder.#setter(&self.#field_name);
541 };
542 }
543
544 // 2. PathBuf
545 if is_pathbuf_type(ty) {
546 return quote! {
547 if let Some(s) = self.#field_name.to_str() {
548 builder.#setter(s);
549 }
550 };
551 }
552
553 // 3. DateTime<Utc> → Timestamp struct (seconds + nanos)
554 if is_datetime_type(ty) {
555 return quote! {
556 {
557 let mut ts = builder.reborrow().#initter();
558 ts.set_seconds(self.#field_name.timestamp());
559 ts.set_nanos(self.#field_name.timestamp_subsec_nanos() as i32);
560 }
561 };
562 }
563
564 // 4. Vec<String>
565 if is_vec_string_type(ty) {
566 return quote! {
567 {
568 let mut list = builder.reborrow().#initter(self.#field_name.len() as u32);
569 for (i, item) in self.#field_name.iter().enumerate() {
570 list.set(i as u32, item);
571 }
572 }
573 };
574 }
575
576 // 4b. Vec<u8> → Data (capnp set_field takes &[u8])
577 if is_vec_u8_type(ty) {
578 return quote! {
579 builder.#setter(&self.#field_name);
580 };
581 }
582
583 // 5. Option<T>
584 if is_option_type(ty) {
585 if let Some(inner) = extract_inner_type(ty) {
586 if is_string_type(inner) {
587 // Option<String>
588 return quote! {
589 if let Some(ref v) = self.#field_name {
590 builder.#setter(v);
591 }
592 };
593 } else if is_datetime_type(inner) {
594 // Option<DateTime<Utc>> → Timestamp pointer (null = not set)
595 return quote! {
596 if let Some(ref dt) = self.#field_name {
597 let mut ts = builder.reborrow().#initter();
598 ts.set_seconds(dt.timestamp());
599 ts.set_nanos(dt.timestamp_subsec_nanos() as i32);
600 }
601 };
602 } else if is_known_primitive(inner) {
603 // Option<primitive> — set if Some
604 return quote! {
605 if let Some(v) = self.#field_name {
606 builder.#setter(v);
607 }
608 };
609 } else {
610 // Option<struct> — init + write_to
611 return quote! {
612 if let Some(ref v) = self.#field_name {
613 hyprstream_rpc::capnp::ToCapnp::write_to(v, &mut builder.reborrow().#initter());
614 }
615 };
616 }
617 }
618 // Fallback for Option without extractable inner type
619 return quote! {
620 if let Some(ref v) = self.#field_name {
621 builder.#setter(v);
622 }
623 };
624 }
625
626 // 7 & 8. Vec<T>
627 if is_vec_type(ty) {
628 if let Some(inner) = extract_inner_type(ty) {
629 if is_known_primitive(inner) {
630 // 8. Vec<primitive> — init list, set items
631 return quote! {
632 {
633 let mut list = builder.reborrow().#initter(self.#field_name.len() as u32);
634 for (i, item) in self.#field_name.iter().enumerate() {
635 list.set(i as u32, *item);
636 }
637 }
638 };
639 } else {
640 // 7. Vec<struct> — init list, write_to items
641 return quote! {
642 {
643 let mut list = builder.reborrow().#initter(self.#field_name.len() as u32);
644 for (i, item) in self.#field_name.iter().enumerate() {
645 hyprstream_rpc::capnp::ToCapnp::write_to(item, &mut list.reborrow().get(i as u32));
646 }
647 }
648 };
649 }
650 }
651 }
652
653 // 9. Known primitive — direct set
654 if is_known_primitive(ty) {
655 return quote! {
656 builder.#setter(self.#field_name);
657 };
658 }
659
660 // 10. Fallback: nested struct — init + write_to
661 quote! {
662 hyprstream_rpc::capnp::ToCapnp::write_to(&self.#field_name, &mut builder.reborrow().#initter());
663 }
664}
665
666/// Generate setter code for a field with `#[capnp(enum_type)]` (ToCapnp).
667///
668/// Converts the Rust enum to the capnp enum via `Into`, then calls the setter.
669/// For `Option<Enum>`, only sets if `Some`.
670fn generate_enum_setter(
671 field_name: &syn::Ident,
672 setter: &syn::Ident,
673 ty: &syn::Type,
674 _capnp_enum_path: &syn::Path,
675) -> proc_macro2::TokenStream {
676 if is_option_type(ty) {
677 quote! {
678 if let Some(ref v) = self.#field_name {
679 builder.#setter((*v).into());
680 }
681 }
682 } else {
683 quote! {
684 builder.#setter(self.#field_name.into());
685 }
686 }
687}
688
689/// Generate getter code for a field with `#[capnp(enum_type)]` (FromCapnp).
690///
691/// Reads the capnp enum and converts to the Rust enum via `Into`.
692/// Falls back to `Default::default()` if the enum value is not recognized.
693fn generate_enum_getter(field_name: &syn::Ident, getter: &syn::Ident) -> proc_macro2::TokenStream {
694 quote! {
695 #field_name: reader.#getter().ok().map(Into::into).unwrap_or_default(),
696 }
697}
698
699/// Generate getter code for a field (FromCapnp)
700///
701/// Dispatch order:
702/// 1. String → reader.get_field()?.to_str()?.to_string()
703/// 2. PathBuf → PathBuf::from(reader.get_field()?.to_str()?)
704/// 3. DateTime<Utc> → read Timestamp struct → from_timestamp
705/// 4. Vec<String> → iterate text list
706/// 5. Option<String> → empty string → None
707/// Option<DateTime> → has_field() check + Timestamp read
708/// 6. Option<T> (struct) → has_field() check + read_from
709/// 7. Vec<T> (struct) → iterate struct list with read_from
710/// 8. Vec<T> (primitive) → iterate primitive list
711/// 9. Known primitive → direct reader.get_field()
712/// 10. Fallback (struct) → read_from
713fn generate_getter(
714 field_name: &syn::Ident,
715 getter: &syn::Ident,
716 ty: &syn::Type,
717 is_optional: bool,
718) -> proc_macro2::TokenStream {
719 // Derive has_field ident from get_field ident
720 let getter_str = getter.to_string();
721 let field_suffix = &getter_str["get_".len()..];
722 let has_ident = format_ident!("has_{}", field_suffix);
723
724 // 1. String
725 if is_string_type(ty) {
726 return quote! {
727 #field_name: reader.#getter()?.to_str()?.to_string(),
728 };
729 }
730
731 // 2. PathBuf
732 if is_pathbuf_type(ty) {
733 return quote! {
734 #field_name: std::path::PathBuf::from(reader.#getter()?.to_str()?),
735 };
736 }
737
738 // 3. DateTime<Utc> → read Timestamp struct (seconds + nanos)
739 if is_datetime_type(ty) {
740 return quote! {
741 #field_name: {
742 let ts = reader.#getter()?;
743 chrono::DateTime::from_timestamp(ts.get_seconds(), ts.get_nanos() as u32)
744 .unwrap_or_default()
745 },
746 };
747 }
748
749 // 4. Vec<String>
750 if is_vec_string_type(ty) {
751 return quote! {
752 #field_name: {
753 let list = reader.#getter()?;
754 let mut v = Vec::with_capacity(list.len() as usize);
755 for i in 0..list.len() {
756 v.push(list.get(i)?.to_str()?.to_string());
757 }
758 v
759 },
760 };
761 }
762
763 // 4b. Vec<u8> → Data (capnp get_field returns Result<&[u8]>)
764 if is_vec_u8_type(ty) {
765 return quote! {
766 #field_name: reader.#getter()?.to_vec(),
767 };
768 }
769
770 // 5 & 6. Option<T>
771 if is_option_type(ty) || is_optional {
772 if let Some(inner) = extract_inner_type(ty) {
773 if is_string_type(inner) {
774 // Option<String> — empty string → None
775 return quote! {
776 #field_name: {
777 let s = reader.#getter()?.to_str()?;
778 if s.is_empty() { None } else { Some(s.to_string()) }
779 },
780 };
781 } else if is_datetime_type(inner) {
782 // Option<DateTime<Utc>> — has_field() check + Timestamp read
783 return quote! {
784 #field_name: if reader.#has_ident() {
785 let ts = reader.#getter()?;
786 Some(chrono::DateTime::from_timestamp(ts.get_seconds(), ts.get_nanos() as u32)
787 .unwrap_or_default())
788 } else {
789 None
790 },
791 };
792 } else if is_known_primitive(inner) {
793 // Option<primitive> — treat 0/false/default as None
794 return quote! {
795 #field_name: {
796 let s = reader.#getter()?.to_str()?;
797 if s.is_empty() { None } else { Some(s.to_string()) }
798 },
799 };
800 } else {
801 // Option<struct> — has_field() check + read_from
802 return quote! {
803 #field_name: if reader.#has_ident() {
804 Some(hyprstream_rpc::capnp::FromCapnp::read_from(reader.#getter()?)?)
805 } else {
806 None
807 },
808 };
809 }
810 }
811 // Fallback for #[capnp(optional)] on non-Option type
812 return quote! {
813 #field_name: {
814 let s = reader.#getter()?.to_str()?;
815 if s.is_empty() { None } else { Some(s.to_string()) }
816 },
817 };
818 }
819
820 // 7 & 8. Vec<T>
821 if is_vec_type(ty) {
822 if let Some(inner) = extract_inner_type(ty) {
823 if is_known_primitive(inner) {
824 // 8. Vec<primitive> — iterate primitive list
825 return quote! {
826 #field_name: {
827 let list = reader.#getter()?;
828 let mut v = Vec::with_capacity(list.len() as usize);
829 for i in 0..list.len() {
830 v.push(list.get(i));
831 }
832 v
833 },
834 };
835 } else {
836 // 7. Vec<struct> — iterate struct list with read_from
837 return quote! {
838 #field_name: {
839 let list = reader.#getter()?;
840 let mut v = Vec::with_capacity(list.len() as usize);
841 for i in 0..list.len() {
842 v.push(hyprstream_rpc::capnp::FromCapnp::read_from(list.get(i))?);
843 }
844 v
845 },
846 };
847 }
848 }
849 }
850
851 // 9. Known primitive — direct get (no ? needed, returns value directly)
852 if is_known_primitive(ty) {
853 return quote! {
854 #field_name: reader.#getter(),
855 };
856 }
857
858 // 10. Fallback: nested struct — read_from
859 quote! {
860 #field_name: hyprstream_rpc::capnp::FromCapnp::read_from(reader.#getter()?)?,
861 }
862}
863
864// ═══════════════════════════════════════════════════════════════════════════════
865// Authorization Macros - #[authorize] and #[register_scopes]
866// ═══════════════════════════════════════════════════════════════════════════════
867
868/// Attribute macro for method-level authorization with structured scopes.
869///
870/// Generates a wrapper that validates JWT tokens and checks structured scopes
871/// before calling the original method. This provides compile-time enforcement
872/// of authorization requirements.
873///
874/// # Attributes
875///
876/// - `action` - The action being performed (e.g., "infer", "read", "write")
877/// - `resource` - The resource type (e.g., "model", "stream", "policy")
878/// - `identifier_field` - Field name in request containing the resource ID
879///
880/// # Example
881///
882/// ```ignore
883/// impl InferenceService {
884/// #[authorize(action = "infer", resource = "model", identifier_field = "model_name")]
885/// fn handle_generate(&self, ctx: &EnvelopeContext, request: GenerateRequest) -> Result<Vec<u8>> {
886/// // Authorization already validated - just implement business logic
887/// // ctx.user_claims is guaranteed to exist here
888/// }
889/// }
890/// ```
891///
892/// # Generated Code
893///
894/// The macro generates:
895/// 1. JWT token validation via `ctx.validate_jwt()`
896/// 2. Structured scope construction: `Scope::new(action, resource, request.identifier_field)`
897/// 3. Casbin policy check (single source of truth for authorization)
898/// 4. Original method call if all checks pass
899///
900/// # Security
901///
902/// Defense-in-depth with three validation layers:
903/// - Layer 1: Envelope signature (service identity)
904/// - Layer 2: Casbin policy (RBAC/ABAC)
905/// - Layer 3: JWT scope (structured, least privilege)
906#[proc_macro_attribute]
907pub fn authorize(attr: TokenStream, item: TokenStream) -> TokenStream {
908 let args = parse_macro_input!(attr as AuthorizeArgs);
909 let input = parse_macro_input!(item as syn::ItemFn);
910
911 let action = &args.action;
912 let resource = &args.resource;
913 let identifier_field = format_ident!("{}", &args.identifier_field);
914
915 let fn_vis = &input.vis;
916 let fn_sig = &input.sig;
917 let fn_block = &input.block;
918 let fn_attrs = &input.attrs;
919
920 // The function signature should have (self, ctx: &EnvelopeContext, request: RequestType)
921 // We generate a wrapper that validates before calling the original
922
923 let expanded = quote! {
924 #(#fn_attrs)*
925 #fn_vis #fn_sig {
926 // Extract claims from envelope (already verified by envelope signature)
927 let claims = ctx.claims()
928 .ok_or_else(|| anyhow::anyhow!("Unauthorized: Missing claims in envelope"))?;
929
930 // Build structured scope from request
931 let required_scope = hyprstream_rpc::auth::Scope::new(
932 #action.to_string(),
933 #resource.to_string(),
934 request.#identifier_field.clone(),
935 );
936
937 // Check Casbin policy (scope used as resource)
938 let subject = claims.sub.clone();
939 let allowed = tokio::task::block_in_place(|| {
940 let handle = tokio::runtime::Handle::current();
941 handle.block_on(self.policy_manager.check(
942 &subject,
943 &required_scope.to_string(),
944 crate::auth::Operation::Infer,
945 ))
946 })?;
947
948 if !allowed {
949 return Err(anyhow::anyhow!(
950 "Forbidden: Casbin policy denied for scope '{}'",
951 required_scope.to_string()
952 ));
953 }
954
955 // Authorization passed (Casbin is the single source of truth)
956 // JWT scope checks removed - Casbin enforces all authorization
957 #fn_block
958 }
959 };
960
961 expanded.into()
962}
963
964/// Arguments for the #[authorize] attribute
965struct AuthorizeArgs {
966 action: String,
967 resource: String,
968 identifier_field: String,
969}
970
971impl syn::parse::Parse for AuthorizeArgs {
972 fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> {
973 let mut action = None;
974 let mut resource = None;
975 let mut identifier_field = None;
976
977 while !input.is_empty() {
978 let ident: syn::Ident = input.parse()?;
979 input.parse::<syn::Token![=]>()?;
980
981 match ident.to_string().as_str() {
982 "action" => {
983 let lit: syn::LitStr = input.parse()?;
984 action = Some(lit.value());
985 }
986 "resource" => {
987 let lit: syn::LitStr = input.parse()?;
988 resource = Some(lit.value());
989 }
990 "identifier_field" => {
991 let lit: syn::LitStr = input.parse()?;
992 identifier_field = Some(lit.value());
993 }
994 other => {
995 return Err(syn::Error::new(
996 ident.span(),
997 format!("unknown attribute: {other}"),
998 ))
999 }
1000 }
1001
1002 if input.peek(syn::Token![,]) {
1003 input.parse::<syn::Token![,]>()?;
1004 }
1005 }
1006
1007 Ok(AuthorizeArgs {
1008 action: action.ok_or_else(|| syn::Error::new(input.span(), "missing 'action'"))?,
1009 resource: resource
1010 .ok_or_else(|| syn::Error::new(input.span(), "missing 'resource'"))?,
1011 identifier_field: identifier_field
1012 .ok_or_else(|| syn::Error::new(input.span(), "missing 'identifier_field'"))?,
1013 })
1014 }
1015}
1016
1017/// Attribute macro for automatic scope registration.
1018///
1019/// Scans all `#[authorize]` attributes in the impl block and generates
1020/// inventory::submit! statements for each unique (action, resource) pair.
1021///
1022/// This ensures that all scopes are automatically registered at compile-time,
1023/// making it impossible to forget scope registration.
1024///
1025/// # Example
1026///
1027/// ```ignore
1028/// #[register_scopes]
1029/// impl InferenceService {
1030/// #[authorize(action = "infer", resource = "model", identifier_field = "model")]
1031/// fn handle_generate(...) { }
1032///
1033/// #[authorize(action = "read", resource = "model", identifier_field = "model")]
1034/// fn handle_config(...) { }
1035/// }
1036///
1037/// // Automatically generates:
1038/// // inventory::submit! {
1039/// // hyprstream_rpc::auth::ScopeDefinition::new("infer", "model", "infer:model:*", "infer on model")
1040/// // }
1041/// // inventory::submit! {
1042/// // hyprstream_rpc::auth::ScopeDefinition::new("read", "model", "read:model:*", "read on model")
1043/// // }
1044/// ```
1045///
1046/// # Benefits
1047///
1048/// - ✅ DRY: Scopes declared once in #[authorize], auto-registered
1049/// - ✅ Impossible to forget: Missing #[authorize] = no registration = compile error
1050/// - ✅ Self-documenting: Scopes visible via `inventory::iter::<ScopeDefinition>()`
1051/// - ✅ Zero boilerplate: No manual inventory::submit! needed
1052#[proc_macro_attribute]
1053pub fn register_scopes(_attr: TokenStream, item: TokenStream) -> TokenStream {
1054 let input = parse_macro_input!(item as syn::ItemImpl);
1055
1056 // Collect all unique (action, resource) pairs from #[authorize] attributes
1057 let mut scopes = std::collections::HashSet::new();
1058
1059 for item in &input.items {
1060 if let syn::ImplItem::Fn(method) = item {
1061 for attr in &method.attrs {
1062 if attr.path().is_ident("authorize") {
1063 if let Ok(args) = attr.parse_args::<AuthorizeArgs>() {
1064 scopes.insert((args.action.clone(), args.resource.clone()));
1065 }
1066 }
1067 }
1068 }
1069 }
1070
1071 // Generate inventory submissions.
1072 //
1073 // Native-only (#1305): inventory's linker-section registration doesn't
1074 // resolve on wasm32, so each submit is gated off there.
1075 let registrations: Vec<_> = scopes
1076 .iter()
1077 .map(|(action, resource)| {
1078 let example = format!("{action}:{resource}:*");
1079 let description = format!("{action} on {resource}");
1080
1081 quote! {
1082 #[cfg(not(target_arch = "wasm32"))]
1083 inventory::submit! {
1084 hyprstream_rpc::auth::ScopeDefinition::new(
1085 #action,
1086 #resource,
1087 #example,
1088 #description
1089 )
1090 }
1091 }
1092 })
1093 .collect();
1094
1095 // Output original impl + registrations
1096 let expanded = quote! {
1097 #input
1098
1099 #(#registrations)*
1100 };
1101
1102 expanded.into()
1103}
1104
1105// ═══════════════════════════════════════════════════════════════════════════════
1106// Service Factory Macro - #[service_factory]
1107// ═══════════════════════════════════════════════════════════════════════════════
1108
1109/// Attribute macro for service factory registration.
1110///
1111/// Automatically registers a service factory function with the inventory system,
1112/// following the same pattern as `#[register_scopes]` for authorization scopes
1113/// and `DriverFactory` for storage drivers.
1114///
1115/// # Usage
1116///
1117/// ```ignore
1118/// use hyprstream_service::ServiceContext;
1119/// use hyprstream_rpc::service::Spawnable;
1120/// use hyprstream_rpc_derive::service_factory;
1121///
1122/// #[service_factory("policy")]
1123/// fn create_policy_service(ctx: &ServiceContext) -> anyhow::Result<Box<dyn Spawnable>> {
1124/// // Services include infrastructure and are directly Spawnable
1125/// let policy = PolicyService::new(
1126/// ...,
1127/// ctx.zmq_context(),
1128/// ctx.transport("policy", SocketKind::Rep),
1129/// ctx.verifying_key(),
1130/// );
1131/// Ok(Box::new(policy))
1132/// }
1133/// ```
1134///
1135/// # Generated Code
1136///
1137/// The macro generates:
1138/// ```ignore
1139/// fn create_policy_service(ctx: &ServiceContext) -> anyhow::Result<Box<dyn Spawnable>> {
1140/// // ... original function body ...
1141/// }
1142///
1143/// inventory::submit! {
1144/// hyprstream_service::ServiceFactory::new(
1145/// "policy",
1146/// create_policy_service
1147/// )
1148/// }
1149/// ```
1150///
1151/// # Benefits
1152///
1153/// - ✅ DRY: Service factory declared once, auto-registered
1154/// - ✅ Decentralized: Services own their registration (not in main.rs)
1155/// - ✅ Self-documenting: All services discoverable via `list_factories()`
1156/// - ✅ Matches existing patterns: Same as `#[register_scopes]` and `DriverFactory`
1157#[proc_macro_attribute]
1158pub fn service_factory(attr: TokenStream, item: TokenStream) -> TokenStream {
1159 let args = parse_macro_input!(attr as ServiceFactoryArgs);
1160 let func = parse_macro_input!(item as syn::ItemFn);
1161 let func_name = &func.sig.ident;
1162 let name = &args.name;
1163
1164 let deps = &args.depends_on;
1165 let depends_on_chain = if deps.is_empty() {
1166 quote! {}
1167 } else {
1168 quote! { .with_depends_on(&[#(#deps),*]) }
1169 };
1170
1171 // The `submit!` registrations are native-only (#1305): inventory's
1172 // linker-section registration doesn't resolve on wasm32. All current
1173 // `#[service_factory]` consumers are native (the daemon); the factory fn
1174 // itself is re-emitted ungated.
1175 let expanded = match (&args.schema, &args.metadata) {
1176 (Some(schema_path), Some(metadata_path)) => {
1177 quote! {
1178 #func
1179
1180 #[cfg(not(target_arch = "wasm32"))]
1181 inventory::submit! {
1182 hyprstream_service::ServiceFactory::with_metadata(
1183 #name,
1184 #func_name,
1185 include_bytes!(#schema_path),
1186 #metadata_path
1187 )#depends_on_chain
1188 }
1189 }
1190 }
1191 (Some(schema_path), None) => {
1192 quote! {
1193 #func
1194
1195 #[cfg(not(target_arch = "wasm32"))]
1196 inventory::submit! {
1197 hyprstream_service::ServiceFactory::with_schema(
1198 #name,
1199 #func_name,
1200 include_bytes!(#schema_path)
1201 )#depends_on_chain
1202 }
1203 }
1204 }
1205 _ => {
1206 quote! {
1207 #func
1208
1209 #[cfg(not(target_arch = "wasm32"))]
1210 inventory::submit! {
1211 hyprstream_service::ServiceFactory::new(
1212 #name,
1213 #func_name
1214 )#depends_on_chain
1215 }
1216 }
1217 }
1218 };
1219
1220 expanded.into()
1221}
1222
1223/// Arguments for the #[service_factory] attribute.
1224///
1225/// Supports:
1226/// - `#[service_factory("name")]` — no schema
1227/// - `#[service_factory("name", schema = "path/to/schema.capnp")]` — with schema
1228/// - `#[service_factory("name", schema = "...", metadata = path::to::schema_metadata)]` — with metadata
1229/// - `#[service_factory("name", depends_on = ["policy", "registry"])]` — with dependencies
1230struct ServiceFactoryArgs {
1231 name: syn::LitStr,
1232 schema: Option<syn::LitStr>,
1233 metadata: Option<syn::Path>,
1234 depends_on: Vec<syn::LitStr>,
1235}
1236
1237impl syn::parse::Parse for ServiceFactoryArgs {
1238 fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> {
1239 let name: syn::LitStr = input.parse()?;
1240 let mut schema = None;
1241 let mut metadata = None;
1242 let mut depends_on = Vec::new();
1243
1244 while input.peek(syn::Token![,]) {
1245 input.parse::<syn::Token![,]>()?;
1246 if input.is_empty() {
1247 break;
1248 }
1249 let ident: syn::Ident = input.parse()?;
1250 input.parse::<syn::Token![=]>()?;
1251 match ident.to_string().as_str() {
1252 "schema" => {
1253 schema = Some(input.parse::<syn::LitStr>()?);
1254 }
1255 "metadata" => {
1256 metadata = Some(input.parse::<syn::Path>()?);
1257 }
1258 "depends_on" => {
1259 let content;
1260 syn::bracketed!(content in input);
1261 let deps = content.parse_terminated(
1262 |input: syn::parse::ParseStream<'_>| input.parse::<syn::LitStr>(),
1263 syn::Token![,],
1264 )?;
1265 depends_on = deps.into_iter().collect();
1266 }
1267 other => {
1268 return Err(syn::Error::new(
1269 ident.span(),
1270 format!("unknown attribute: {other}"),
1271 ));
1272 }
1273 }
1274 }
1275
1276 Ok(ServiceFactoryArgs {
1277 name,
1278 schema,
1279 metadata,
1280 depends_on,
1281 })
1282 }
1283}
1284
1285// ═══════════════════════════════════════════════════════════════════════════════
1286// RPC Service Code Generation Macro
1287// ═══════════════════════════════════════════════════════════════════════════════
1288
1289/// Proc macro that generates a complete RPC client + handler + metadata from a Cap'n Proto schema.
1290///
1291/// Reads the schema file from `$CARGO_MANIFEST_DIR/schema/{name}.capnp`, parses it,
1292/// and generates all client code using `quote!` AST generation.
1293///
1294/// # Usage
1295///
1296/// ```ignore
1297/// pub mod policy_client {
1298/// #![allow(dead_code, unused_imports, unused_variables)]
1299/// #![allow(clippy::all)]
1300/// hyprstream_rpc_derive::generate_rpc_service!("policy");
1301/// }
1302/// ```
1303/// Arguments for `generate_rpc_service!` macro.
1304///
1305/// Supports:
1306/// - `generate_rpc_service!("name")` — standard (server-side, handler included)
1307/// - `generate_rpc_service!("name", types_crate = some_crate)` — client-only, domain types from external crate
1308/// - `generate_rpc_service!("name", scope_handlers)` — generate typed scope sub-traits for inner dispatch
1309struct RpcServiceArgs {
1310 name: syn::LitStr,
1311 types_crate: Option<syn::Path>,
1312 scope_handlers: bool,
1313}
1314
1315impl syn::parse::Parse for RpcServiceArgs {
1316 fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> {
1317 let name: syn::LitStr = input.parse()?;
1318 let mut types_crate = None;
1319 let mut scope_handlers = false;
1320
1321 while input.peek(syn::Token![,]) {
1322 input.parse::<syn::Token![,]>()?;
1323 if input.is_empty() {
1324 break;
1325 }
1326 let ident: syn::Ident = input.parse()?;
1327 if ident == "types_crate" {
1328 input.parse::<syn::Token![=]>()?;
1329 types_crate = Some(input.parse::<syn::Path>()?);
1330 } else if ident == "scope_handlers" {
1331 scope_handlers = true;
1332 } else {
1333 return Err(syn::Error::new(
1334 ident.span(),
1335 format!("unknown option: {ident}"),
1336 ));
1337 }
1338 }
1339
1340 Ok(RpcServiceArgs {
1341 name,
1342 types_crate,
1343 scope_handlers,
1344 })
1345 }
1346}
1347
1348#[proc_macro]
1349pub fn generate_rpc_service(input: TokenStream) -> TokenStream {
1350 let args: RpcServiceArgs = match syn::parse(input) {
1351 Ok(a) => a,
1352 Err(e) => return e.to_compile_error().into(),
1353 };
1354 let service_name = &args.name;
1355 let name = service_name.value();
1356 let types_crate = args.types_crate.as_ref();
1357
1358 // Parse from CGR (binary CodeGeneratorRequest produced by build.rs).
1359 // CGR includes full cross-schema type resolution and annotations.
1360 let parsed = match schema::parse_from_cgr(&name) {
1361 Ok(p) => p,
1362 Err(e) => {
1363 return syn::Error::new(
1364 service_name.span(),
1365 format!(
1366 "CGR parse failed for '{name}': {e}. Ensure build.rs compiles this schema."
1367 ),
1368 )
1369 .to_compile_error()
1370 .into()
1371 }
1372 };
1373
1374 codegen::generate_service(&name, &parsed, types_crate, args.scope_handlers).into()
1375}
1376
1377/// Proc macro that generates only the server implementation surface for a
1378/// schema whose contracts live in another crate.
1379///
1380/// The contract crate must export `{name}_client` and `{name}_capnp` modules
1381/// (as `hyprstream-rpc-std` does). The expansion imports those types privately
1382/// and emits handler traits, dispatch, request decoding, schema metadata, and
1383/// the VFS projection. It does **not** emit a second client, response enum, or
1384/// data-struct implementation, which keeps AGPL service crates from becoming
1385/// the distribution home for public clients.
1386///
1387/// # Usage
1388///
1389/// ```ignore
1390/// pub mod worker_server {
1391/// hyprstream_rpc_derive::generate_rpc_server!(
1392/// "worker",
1393/// types_crate = hyprstream_rpc_std,
1394/// scope_handlers,
1395/// );
1396/// }
1397/// ```
1398#[proc_macro]
1399pub fn generate_rpc_server(input: TokenStream) -> TokenStream {
1400 let args: RpcServiceArgs = match syn::parse(input) {
1401 Ok(a) => a,
1402 Err(e) => return e.to_compile_error().into(),
1403 };
1404 let service_name = &args.name;
1405 let name = service_name.value();
1406 let types_crate = match args.types_crate.as_ref() {
1407 Some(path) => path,
1408 None => {
1409 return syn::Error::new_spanned(
1410 service_name,
1411 "generate_rpc_server! requires types_crate = <contract_crate>",
1412 )
1413 .to_compile_error()
1414 .into();
1415 }
1416 };
1417
1418 let parsed = match schema::parse_from_cgr(&name) {
1419 Ok(p) => p,
1420 Err(e) => {
1421 return syn::Error::new(
1422 service_name.span(),
1423 format!("CGR parse failed for '{name}': {e}. Ensure the contract crate exports its CGR via build.rs."),
1424 )
1425 .to_compile_error()
1426 .into();
1427 }
1428 };
1429
1430 codegen::generate_server(&name, &parsed, types_crate, args.scope_handlers).into()
1431}
1432
1433/// Generate client-only code from a Cap'n Proto service schema.
1434///
1435/// Like `generate_rpc_service!` but emits only the portable data, client,
1436/// client-trait, JSON-dispatch, and metadata surface — no server handlers or
1437/// service implementation code. Compiles to all targets including wasm32.
1438///
1439/// # Usage
1440///
1441/// ```ignore
1442/// pub mod model_client {
1443/// hyprstream_rpc_derive::generate_rpc_client!("model");
1444/// }
1445/// ```
1446#[proc_macro]
1447pub fn generate_rpc_client(input: TokenStream) -> TokenStream {
1448 let args: RpcServiceArgs = match syn::parse(input) {
1449 Ok(a) => a,
1450 Err(e) => return e.to_compile_error().into(),
1451 };
1452 let service_name = &args.name;
1453 let name = service_name.value();
1454 let types_crate = args.types_crate.as_ref();
1455
1456 let parsed = match schema::parse_from_cgr(&name) {
1457 Ok(p) => p,
1458 Err(e) => {
1459 return syn::Error::new(
1460 service_name.span(),
1461 format!(
1462 "CGR parse failed for '{name}': {e}. Ensure build.rs compiles this schema."
1463 ),
1464 )
1465 .to_compile_error()
1466 .into()
1467 }
1468 };
1469
1470 codegen::generate_client_only(&name, &parsed, types_crate).into()
1471}