1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
//! Generate method enum from hub methods
use crate::parse::{AuthPosture, Cardinality, ChildMethodInfo, ChildMethodKind, MethodInfo, MethodRequestOverride, ParsedDeprecation};
use proc_macro2::TokenStream;
use quote::{format_ident, quote, ToTokens};
use syn::Type;
pub fn generate(
struct_name: &syn::Ident,
methods: &[MethodInfo],
child_methods: &[ChildMethodInfo],
crate_path: &syn::Path,
auth_core_path: Option<&syn::Path>,
activation_request_type: Option<&syn::Type>,
// Z2H-2: ident of the per-expansion dependency shim module. serde /
// serde_json / schemars references in the emitted enum + schema code
// resolve relatively through it.
deps: &syn::Ident,
// R-1 (joint AP-1): the activation's DECLARED auth posture. `Some(p)` is
// stamped onto every generated RPC `MethodSchema` via
// `with_auth_posture`; `None` (posture never declared) emits nothing so
// posture-silent activations keep their pre-R-1 wire shape.
auth_posture: Option<AuthPosture>,
// AUTH-3: the activation's namespace — each method's grant is
// `<namespace>.<method>`.
namespace: &str,
) -> TokenStream {
let enum_name = format_ident!("{}Method", struct_name);
// Z2H-2: derives are the one place the relative shim path does NOT work —
// serde/schemars derive expansions emit `use <crate-attr-path> ...` inside
// their own const blocks, which resolves module-relatively and cannot see
// a shim module that lives in a fn body (activations declared inside test
// fns are common). So the derive list + both crates' `crate =` escape
// hatches use the ABSOLUTE umbrella path in umbrella mode, and today's
// bare extern-prelude names (with no `crate =` attrs at all) in direct
// mode — preserving pre-Z2H-2 derive semantics exactly for existing
// consumers.
let umbrella = crate::codegen::umbrella_crate(proc_macro2::Span::call_site());
let (serde_derive_path, schemars_derive_path, derive_crate_attrs) = match &umbrella {
Some(u) => {
let serde_crate_attr = format!("::{}::__deps::serde", u);
let schemars_crate_attr = format!("::{}::__deps::schemars", u);
(
quote! { ::#u::__deps::serde },
quote! { ::#u::__deps::schemars },
quote! {
#[serde(crate = #serde_crate_attr)]
#[schemars(crate = #schemars_crate_attr)]
},
)
}
None => (quote! { serde }, quote! { schemars }, quote! {}),
};
let variants: Vec<TokenStream> = methods
.iter()
.map(|m| {
let variant_name = format_ident!("{}", to_pascal_case(&m.method_name));
let method_name = &m.method_name;
let doc = &m.description;
// Always use struct variants for consistent schema generation.
// This ensures params is always an object with named fields.
// Use serde(rename) to get the exact method name in the schema.
match m.params.len() {
0 => quote! {
#[doc = #doc]
#[serde(rename = #method_name)]
#variant_name
},
_ => {
// Use struct variant for all cases (including single param)
// This produces proper object schema with field names
// Add description for each field from param_docs or fallback to name
// Add #[serde(default, deserialize_with = "...")] for Option<T> fields
// to make them truly optional and accept explicit null values
let fields: Vec<TokenStream> = m
.params
.iter()
.map(|p| {
let name = &p.name;
let ty = &p.ty;
let desc = p.description.clone()
.unwrap_or_else(|| format!("The {} parameter", name));
// Check if type is Option<T> - if so, add serde attributes
// that handle both missing fields AND explicit null values
let is_option = is_option_type(ty);
if is_option {
let serde_helpers_path = format!("{}::serde_helpers::deserialize_null_as_none",
crate_path.segments.iter().map(|s| s.ident.to_string()).collect::<Vec<_>>().join("::"));
quote! {
#[schemars(description = #desc)]
#[serde(default, deserialize_with = #serde_helpers_path)]
#name: #ty
}
} else {
quote! {
#[schemars(description = #desc)]
#name: #ty
}
}
})
.collect();
quote! {
#[doc = #doc]
#[serde(rename = #method_name)]
#variant_name { #(#fields),* }
}
}
}
})
.collect();
let method_names: Vec<&str> = methods.iter().map(|m| m.method_name.as_str()).collect();
let method_descriptions: Vec<&str> = methods.iter().map(|m| m.description.as_str()).collect();
// AUTH-3: per-method grant (always), target and long description.
let method_grants: Vec<String> =
methods.iter().map(|m| format!("{}.{}", namespace, m.method_name)).collect();
let schema_grant = format!("{}.schema", namespace);
let method_targets: Vec<TokenStream> = methods
.iter()
.map(|m| match &m.target {
Some(t) => quote! { ::std::option::Option::Some(#t) },
None => quote! { ::std::option::Option::None },
})
.collect();
// BIDIR-8: who may answer each method's questions (absent: the caller).
let method_answer_bys: Vec<TokenStream> = methods
.iter()
.map(|m| match &m.answer_by {
Some(a) => quote! { ::std::option::Option::Some(#a) },
None => quote! { ::std::option::Option::None },
})
.collect();
let method_long_descriptions: Vec<TokenStream> = methods
.iter()
.map(|m| match &m.long_description {
Some(t) => quote! { ::std::option::Option::Some(#t) },
None => quote! { ::std::option::Option::None },
})
.collect();
// RETURNS-8: each method's contract, read from its signature — `returns`
// is `schema_for!(T)`, `error` `schema_for!(E)` when the item is a
// `Result`, `progress` `schema_for!(P)` when it is a `Progress`, and the
// cardinality one or many (RETURNS-5's `MethodSchema` 0.7 fields).
let vocabulary: syn::Path = syn::parse_quote!(#crate_path::plexus);
let returns_exprs: Vec<TokenStream> = methods
.iter()
.map(|m| {
let ok_ty = &m.ok_ty;
quote! { #deps::schemars::schema_for!(#ok_ty) }
})
.collect();
let error_exprs: Vec<TokenStream> = methods
.iter()
.map(|m| match &m.err_ty {
Some(err_ty) => quote! { Some(#deps::schemars::schema_for!(#err_ty)) },
None => quote! { None },
})
.collect();
let progress_exprs: Vec<TokenStream> = methods
.iter()
.map(|m| match &m.progress_ty {
Some(p) => {
let p_ty = p.to_type(&vocabulary);
quote! { Some(#deps::schemars::schema_for!(#p_ty)) }
}
None => quote! { None },
})
.collect();
let cardinality_exprs: Vec<TokenStream> = methods
.iter()
.map(|m| match m.cardinality {
Cardinality::One => quote! { #crate_path::plexus::schema::Cardinality::One },
Cardinality::Many => quote! { #crate_path::plexus::schema::Cardinality::Many },
})
.collect();
// AUTHZ-CRED-MACRO-3: per-method credential-decl-vector expression.
//
// For each method, derive the "credential probe type" (the inner success
// / yielded type of the return signature), then emit a call site that
// walks the macro-emitted marker registry through the autoref-specialized
// `CredentialsRegistryProbe`. Types that derive `#[derive(Credentials)]`
// produce a populated `Vec<CredentialFieldDecl>`; types that don't,
// produce an empty vec via the trait-default fallback.
//
// When `auth_core_path` is `None`, the consuming crate does not depend on
// `plexus-auth-core`, so we skip emitting the call site — the runtime
// match falls through to the `_ => Vec::new()` arm and the schema's
// `credentials` field is unchanged (pre-ticket behavior preserved).
let (credential_decls_indices, credential_decls_exprs): (Vec<_>, Vec<_>) = methods
.iter()
.enumerate()
.filter_map(|(idx, m)| {
let auth_path = auth_core_path?;
let probe_ty = effective_credential_probe_type(m)?;
let idx_lit = proc_macro2::Literal::usize_suffixed(idx);
let method_name = &m.method_name;
// Build the issuer placeholder. At schema-build time we don't
// know the runtime origin URL, so we synthesize origin "plexus"
// plus the method's name as the MethodPath. The runtime can
// re-stamp these at mint time; for schema introspection (IR,
// CLI, codegen) the issuer is descriptive, not authoritative.
//
// `MethodPath::try_new` enforces "namespace.method" grammar
// (>= 2 dot-separated segments). The method name alone often
// fails that grammar (e.g. "echo" has no dot), so we fall back
// to "plexus.<name>" — never panics, always at least 2
// segments. Activation-level namespace prefixing is a follow-up
// (see RUN-NOTES "schema issuer fidelity").
let expr = quote! {
{
// Bring the `CredentialsRegistryFallback` trait into
// scope so its empty-slice `marker_slice` resolves via
// autoref when the return type does NOT implement
// `HasCredentialMarkers`. For return types that DO
// implement `HasCredentialMarkers` (via the macro-emitted
// `impl` from `#[derive(Credentials)]`), the specialized
// inherent `marker_slice` on
// `CredentialsRegistryProbe<T: HasCredentialMarkers>`
// wins via inherent-first method resolution.
use #auth_path::CredentialsRegistryFallback as _;
// Autoref-specialization call site (per
// AUTHZ-CRED-MACRO-3): the inherent `marker_slice`
// emitted by `#[derive(Credentials)]` wins over the
// blanket trait default for types that derive, and
// falls back to `&[]` otherwise.
let __plexus_markers: &'static [#auth_path::CredentialFieldMarker] =
(&#auth_path::CredentialsRegistryProbe::<#probe_ty>::new())
.marker_slice();
let __plexus_method_path = #auth_path::MethodPath::try_new(#method_name)
.or_else(|_| #auth_path::MethodPath::try_new(
concat!("plexus.", #method_name)
))
.unwrap_or_else(|_| #auth_path::MethodPath::try_new("plexus.unknown")
.expect("placeholder MethodPath always parses"));
let __plexus_issuer = #auth_path::CredentialIssuer::new(
#auth_path::Origin::new("plexus"),
__plexus_method_path,
);
__plexus_markers
.iter()
.map(|m| #crate_path::plexus::schema::CredentialFieldDecl::from_marker(
m, &[], __plexus_issuer.clone()
))
.collect::<::std::vec::Vec<#crate_path::plexus::schema::CredentialFieldDecl>>()
}
};
Some((quote! { #idx_lit }, expr))
})
.unzip();
// Generate HTTP method enum values for each method (defaults to POST if not specified)
let http_methods: Vec<TokenStream> = methods
.iter()
.map(|m| {
match m.http_method.as_deref() {
Some("GET") => quote! { #crate_path::plexus::schema::HttpMethod::Get },
Some("POST") => quote! { #crate_path::plexus::schema::HttpMethod::Post },
Some("PUT") => quote! { #crate_path::plexus::schema::HttpMethod::Put },
Some("DELETE") => quote! { #crate_path::plexus::schema::HttpMethod::Delete },
Some("PATCH") => quote! { #crate_path::plexus::schema::HttpMethod::Patch },
None => quote! { #crate_path::plexus::schema::HttpMethod::Post }, // Default
_ => quote! { #crate_path::plexus::schema::HttpMethod::Post }, // Fallback (should not happen due to validation)
}
})
.collect();
// IR-3: per-method deprecation token streams. For methods with no
// `#[deprecated]` / `#[plexus_macros::removed_in]` annotation, we emit
// nothing (the schema's `deprecation` field defaults to `None`).
let (deprecation_index, deprecation_schema_calls): (Vec<_>, Vec<_>) = methods
.iter()
.enumerate()
.filter_map(|(idx, m)| {
let idx_lit = proc_macro2::Literal::usize_suffixed(idx);
m.deprecation.as_ref().map(|dep| {
(
quote! { #idx_lit },
deprecation_call(dep, crate_path),
)
})
})
.unzip();
// IR-5: per-method `params_meta` token streams, carrying per-parameter
// deprecation info. Only methods with at least one parameter that has a
// non-`None` `ParsedDeprecation` emit a call; the rest leave the default
// empty `Vec<ParamSchema>`.
let (params_meta_index, params_meta_schema_calls): (Vec<_>, Vec<_>) = methods
.iter()
.enumerate()
.filter_map(|(idx, m)| {
let idx_lit = proc_macro2::Literal::usize_suffixed(idx);
params_meta_call(m, crate_path).map(|call| (quote! { #idx_lit }, call))
})
.unzip();
// SYNAPSE-13: per-method group, examples and param values.
let method_groups: Vec<TokenStream> = methods
.iter()
.map(|m| match &m.group {
Some(g) => quote! { ::std::option::Option::Some(#g) },
None => quote! { ::std::option::Option::None },
})
.collect();
let method_examples: Vec<TokenStream> = methods
.iter()
.map(|m| {
let entries: Vec<TokenStream> = m
.examples
.iter()
.map(|ex| {
let json = &ex.params_json;
let note = match &ex.note {
Some(n) => quote! { ::std::option::Option::Some(#n) },
None => quote! { ::std::option::Option::None },
};
quote! { (#json, #note) }
})
.collect();
quote! { &[#(#entries),*] as &[(&str, ::std::option::Option<&str>)] }
})
.collect();
let method_values: Vec<TokenStream> = methods
.iter()
.map(|m| {
let entries: Vec<TokenStream> = m
.values
.iter()
.map(|(p, vals)| quote! { (#p, &[#(#vals),*] as &[&str]) })
.collect();
quote! { &[#(#entries),*] as &[(&str, &[&str])] }
})
.collect();
// IR-3: child-method schema entries. `#[child]` methods are NOT emitted as
// RPC variants on the method enum (they don't take an RPC dispatch path),
// but they DO contribute `MethodSchema` entries with `role = StaticChild`
// / `DynamicChild { .. }` so `PluginSchema::is_hub_by_role()` returns
// `true` for hubs whose children are declared via `#[child]`.
let child_schema_entries: Vec<TokenStream> = child_methods
.iter()
.map(|c| child_schema_entry(c, crate_path))
.collect();
// REQ-6: per-method auth resolver entries — ((param_name, resolver_expr_string)).
// Used at runtime to inject `x-plexus-source: { from: "auth", resolver: "..." }`
// properties into the method's params schema.
let auth_entries_per_method: Vec<TokenStream> = methods
.iter()
.map(|m| {
let entries: Vec<TokenStream> = m.auth_resolvers
.iter()
.map(|r| {
let name = r.param_name.to_string();
let expr_str = r.resolver_expr.to_token_stream().to_string();
quote! { (#name, #expr_str) }
})
.collect();
quote! { &[#(#entries),*] as &[(&str, &str)] }
})
.collect();
// REQ-6: per-method override flag — `true` means `request = ()`, skip activation-level merge.
let method_override_is_skip: Vec<bool> = methods
.iter()
.map(|m| matches!(m.request_override, Some(MethodRequestOverride::Skip)))
.collect();
// BIDIR-6: `.with_input(T's schema)` for each method with an `Input`,
// its parameter's doc as the schema's description.
let input_arms: Vec<TokenStream> = methods
.iter()
.enumerate()
.filter_map(|(i, m)| {
let input = m.input.as_ref()?;
let item = &input.item;
let i = syn::Index::from(i);
let describe = input.description.as_ref().map(|d| {
quote! { __input.insert("description".to_string(), #deps::serde_json::Value::String(#d.to_string())); }
});
Some(quote! {
#i => {
#[allow(unused_mut)]
let mut __input = #crate_path::plexus::input::item_schema::<#item>(#deps::schemars::schema_for!(#item));
#describe
schema = schema.with_input(__input);
}
})
})
.collect();
let input_schema = if input_arms.is_empty() {
quote! {}
} else {
quote! { match i { #(#input_arms)* _ => {} } }
};
// REQ-6: activation-level request schema token — `Some(schemars::schema_for!(T))` or `None`.
let activation_request_schema_expr: TokenStream = match activation_request_type {
Some(ty) => quote! { Some(#deps::schemars::schema_for!(#ty)) },
None => quote! { None },
};
// R-1 (AUTHZ-CORE-2): per-method explicit-scope emission. Methods that
// declare `scope = "..."` (one or more) get a populated
// `MethodSchema.requires_credential`:
//
// - one scope → `RequiredCredential::from_method_scope(Scope::new(s))`
// - N scopes → `RequiredCredential::from_method_scopes(vec![..])`
// (conjunction — the caller must satisfy ALL)
//
// Methods with no `scope = "..."` emit nothing: the implicit
// `<activation>.<method>` rule is resolved by AUTHZ-CORE-4's
// `ScopeRegistry` at registry-build time, not carried in the IR
// (superseding AUTHZ-CORE-7's `resolved_implicit_scope` — clients can
// compute it from `activation.method` themselves).
//
// `Scope` is reached through plexus-core's re-export
// (`#crate_path::plexus::schema::Scope`) so consumers don't need a
// direct plexus-auth-core dependency, and umbrella-only consumers
// resolve it through `::plexus_rpc::core` (Z2H-2).
let (authz_scope_index, authz_scope_calls): (Vec<_>, Vec<_>) = methods
.iter()
.enumerate()
.filter_map(|(idx, m)| {
if m.scopes.is_empty() {
return None;
}
let idx_lit = proc_macro2::Literal::usize_suffixed(idx);
let call = if m.scopes.len() == 1 {
let s = &m.scopes[0];
quote! {
schema = schema.with_requires_credential(
#crate_path::plexus::schema::RequiredCredential::from_method_scope(
#crate_path::plexus::schema::Scope::new(#s),
),
);
}
} else {
let scope_news = m
.scopes
.iter()
.map(|s| quote! { #crate_path::plexus::schema::Scope::new(#s) });
quote! {
schema = schema.with_requires_credential(
#crate_path::plexus::schema::RequiredCredential::from_method_scopes(
vec![#(#scope_news),*],
),
);
}
};
Some((quote! { #idx_lit }, call))
})
.unzip();
// R-1: per-method `public` flags. Only `true` entries change the wire
// (plexus-core skips serializing `public: false`), so pre-R-1 methods
// keep their exact wire shape.
let public_flags: Vec<bool> = methods.iter().map(|m| m.public).collect();
// KEEL-31: per-method `everywhere` flags.
let everywhere_flags: Vec<bool> = methods.iter().map(|m| m.everywhere).collect();
// R-1 (joint AP-1): activation-declared posture stamp, applied to every
// generated RPC method schema. Undeclared posture emits nothing.
// Framework-injected entries (the auto `schema` method, `#[child]`
// entries) are NOT stamped — the declaration describes the activation's
// RPC enforcement surface.
let posture_call: TokenStream = match auth_posture {
Option::None => quote! {},
Option::Some(p) => {
let variant = match p {
AuthPosture::Required => quote! { Required },
AuthPosture::Optional => quote! { Optional },
AuthPosture::Mixed => quote! { Mixed },
AuthPosture::None => quote! { None },
};
quote! {
schema = schema.with_auth_posture(
#crate_path::plexus::schema::AuthPosture::#variant,
);
}
}
};
quote! {
/// Auto-generated method enum for schema extraction
#[derive(Debug, Clone, #serde_derive_path::Serialize, #serde_derive_path::Deserialize, #schemars_derive_path::JsonSchema)]
#[serde(tag = "method", content = "params", rename_all = "snake_case")]
#derive_crate_attrs
pub enum #enum_name {
#(#variants),*
}
impl #enum_name {
pub fn all_method_names() -> &'static [&'static str] {
&[#(#method_names),*]
}
/// Cached schema value - computed once on first access
fn cached_schema() -> &'static #deps::serde_json::Value {
static SCHEMA_CACHE: std::sync::OnceLock<#deps::serde_json::Value> = std::sync::OnceLock::new();
SCHEMA_CACHE.get_or_init(|| {
#deps::serde_json::to_value(#deps::schemars::schema_for!(#enum_name)).expect("Schema should serialize")
})
}
}
impl #crate_path::plexus::MethodEnumSchema for #enum_name {
fn method_names() -> &'static [&'static str] {
&[#(#method_names),*]
}
fn schema_with_consts() -> #deps::serde_json::Value {
// Return cached schema (cloned since caller may mutate)
Self::cached_schema().clone()
}
}
impl #enum_name {
/// Get per-method schema info including params, return types, and content hashes
///
/// Note: This method has O(1) schema lookup cost after first call due to caching.
/// RETURNS-10: each schema's `hash` is its content hash, computed
/// once, inside that cache.
pub fn method_schemas() -> Vec<#crate_path::plexus::MethodSchema> {
// Cache the computed method schemas for O(1) subsequent calls
static METHOD_SCHEMAS_CACHE: std::sync::OnceLock<Vec<#crate_path::plexus::MethodSchema>> = std::sync::OnceLock::new();
METHOD_SCHEMAS_CACHE.get_or_init(|| {
Self::compute_method_schemas()
}).clone()
}
/// Internal: compute method schemas (called once, then cached)
fn compute_method_schemas() -> Vec<#crate_path::plexus::MethodSchema> {
// NEST-5: while this enum's schemas are computed, a slot whose
// type is this one again is published untyped, not recursed.
let __plexus_building = #crate_path::plexus::slots::building(::std::any::type_name::<Self>());
let method_names: &[&str] = &[#(#method_names),*];
let descriptions: &[&str] = &[#(#method_descriptions),*];
let http_methods: Vec<#crate_path::plexus::schema::HttpMethod> = vec![#(#http_methods),*];
// RETURNS-8: per-method T / E / P schemas and cardinality.
let returns_schemas: Vec<#deps::schemars::Schema> = vec![#(#returns_exprs),*];
let error_schemas: Vec<Option<#deps::schemars::Schema>> = vec![#(#error_exprs),*];
let progress_schemas: Vec<Option<#deps::schemars::Schema>> = vec![#(#progress_exprs),*];
let cardinalities: &[#crate_path::plexus::schema::Cardinality] = &[#(#cardinality_exprs),*];
// REQ-6 runtime data: per-method auth resolvers, override flags, activation request schema.
let auth_entries_per_method: Vec<&[(&str, &str)]> = vec![#(#auth_entries_per_method),*];
let method_override_is_skip: &[bool] = &[#(#method_override_is_skip),*];
// R-1: per-method explicit-public flags (AUTHZ-CORE-2).
let public_flags: &[bool] = &[#(#public_flags),*];
let everywhere_flags: &[bool] = &[#(#everywhere_flags),*];
// AUTH-3: grants, targets, long descriptions.
let grants: &[&str] = &[#(#method_grants),*];
let targets: &[::std::option::Option<&str>] = &[#(#method_targets),*];
let answer_bys: &[::std::option::Option<&str>] = &[#(#method_answer_bys),*];
let long_descriptions: &[::std::option::Option<&str>] = &[#(#method_long_descriptions),*];
// SYNAPSE-13: groups, examples (params JSON, note), param values.
let groups: &[::std::option::Option<&str>] = &[#(#method_groups),*];
let examples: Vec<&[(&str, ::std::option::Option<&str>)]> = vec![#(#method_examples),*];
let param_values: Vec<&[(&str, &[&str])]> = vec![#(#method_values),*];
let activation_request_schema: Option<#deps::schemars::Schema> = #activation_request_schema_expr;
let activation_request_props: Option<#deps::serde_json::Map<String, #deps::serde_json::Value>> =
activation_request_schema
.as_ref()
.and_then(|s| #deps::serde_json::to_value(s).ok())
.and_then(|v| v.get("properties").cloned())
.and_then(|v| match v { #deps::serde_json::Value::Object(m) => Some(m), _ => None });
// Get the cached full enum schema
let schema_value = Self::cached_schema();
// Extract $defs from the root schema - these need to be merged into each method's params
// because types like ConeIdentifier are defined at the root level but referenced via $ref
let root_defs = schema_value.get("$defs").cloned();
// Extract oneOf variants from the schema
let one_of = schema_value
.get("oneOf")
.and_then(|v| v.as_array())
.cloned()
.unwrap_or_default();
let mut methods: Vec<_> = method_names
.iter()
.zip(descriptions.iter())
.zip(http_methods.into_iter())
.zip(returns_schemas.into_iter())
.zip(error_schemas.into_iter().zip(progress_schemas.into_iter()))
.enumerate()
.map(|(i, ((((name, desc), http_method), returns), (error, progress)))| {
// Get this variant's schema from oneOf, then extract just the "params" portion
// The variant looks like: { properties: { method: {...}, params: {...} }, ... }
// We want just the params schema, but we need to merge in $defs from the root
let params = one_of.get(i).and_then(|variant| {
variant
.get("properties")
.and_then(|props| props.get("params"))
.cloned()
.and_then(|mut p| {
// Merge root $defs into the params schema so $ref references resolve
if let (Some(params_obj), Some(defs)) = (p.as_object_mut(), &root_defs) {
params_obj.insert("$defs".to_string(), defs.clone());
}
#deps::serde_json::from_value::<#deps::schemars::Schema>(p).ok()
})
});
// REQ-6: augment the method's params schema with:
// (a) #[from_auth(expr)] properties tagged x-plexus-source: { from: "auth", resolver: ... }
// (b) activation-level request struct properties (when the activation declared `request = X`
// and this method does NOT have `request = ()` override)
// Properties added here are NOT marked required — they are server-extracted.
let params = params.map(|p| {
let mut p_val: #deps::serde_json::Value = #deps::serde_json::to_value(&p).unwrap_or_default();
if let Some(obj) = p_val.as_object_mut() {
// Ensure properties object exists
let properties = obj
.entry("properties".to_string())
.or_insert_with(|| #deps::serde_json::Value::Object(#deps::serde_json::Map::new()));
if let #deps::serde_json::Value::Object(props_map) = properties {
// (a) auth resolvers
for (pname, rexpr) in auth_entries_per_method[i].iter() {
props_map.insert(
(*pname).to_string(),
#deps::serde_json::json!({
"x-plexus-source": {
"from": "auth",
"resolver": rexpr,
}
}),
);
}
// (b) activation-level request fields (if present and not overridden)
if !method_override_is_skip[i] {
if let Some(req_props) = activation_request_props.as_ref() {
for (fname, fschema) in req_props.iter() {
// Don't clobber existing properties (e.g., an auth resolver
// param happening to share a name).
if !props_map.contains_key(fname) {
props_map.insert(fname.clone(), fschema.clone());
}
}
}
}
}
}
#deps::serde_json::from_value::<#deps::schemars::Schema>(p_val).unwrap_or(p)
});
// RETURNS-10: `hash` is set last, from the finished
// schema (`with_content_hash` below).
let mut schema = #crate_path::plexus::MethodSchema::new(
name.to_string(),
desc.to_string(),
::std::string::String::new(),
);
if let Some(p) = params {
schema = schema.with_params(p);
}
schema = schema.with_returns(returns);
if let Some(e) = error {
schema = schema.with_error(e);
}
if let Some(p) = progress {
schema = schema.with_progress(p);
}
schema = schema.with_cardinality(cardinalities[i]);
schema = schema.with_http_method(http_method);
// R-1 (joint AP-1): stamp the activation-declared
// auth posture (no-op when undeclared).
#posture_call
// R-1: explicit-public flag (AUTHZ-CORE-2). Only
// `true` reaches the wire (serde skips false).
if public_flags[i] {
schema = schema.with_public(true);
}
// KEEL-31: acts on the whole service (only `true`
// reaches the wire).
if everywhere_flags[i] {
schema = schema.with_everywhere(true);
}
// AUTH-3: the inherent grant; the target param; the
// doc comment beyond the description.
schema = schema.with_grant(grants[i]);
if let ::std::option::Option::Some(t) = targets[i] {
schema = schema.with_target(t);
}
// BIDIR-8: who may answer (only when declared).
if let ::std::option::Option::Some(a) = answer_bys[i] {
schema = schema.with_answer_by(a);
}
// BIDIR-6: what the caller streams in.
#input_schema
if let ::std::option::Option::Some(l) = long_descriptions[i] {
schema = schema.with_long_description(l);
}
// SYNAPSE-13: the listing group, the worked calls
// (checked to be JSON objects at expansion), and the
// values each param is meant to take.
if let ::std::option::Option::Some(g) = groups[i] {
schema = schema.with_group(g);
}
for (json, note) in examples[i].iter() {
let params: #deps::serde_json::Value = #deps::serde_json::from_str(json)
.expect("example params were checked to be JSON at expansion");
schema = schema.with_example(#crate_path::plexus::MethodExample {
params,
note: note.map(|n| n.to_string()),
});
}
for (param, vals) in param_values[i].iter() {
schema = schema.with_param_values(param, vals.iter().copied());
}
// R-1: explicit `scope = "..."` requirements →
// `requires_credential` (AUTHZ-CORE-2). Compile-time
// per-index match.
match i {
#(
#authz_scope_index => {
#authz_scope_calls
}
)*
_ => {}
}
// IR-3: apply deprecation metadata per-method. Emitted
// only for methods that carry `#[deprecated]` (see
// `parse_deprecation_attrs` for the contract).
match i {
#(
#deprecation_index => {
#deprecation_schema_calls
}
)*
_ => {}
}
// IR-5: apply per-parameter deprecation metadata via
// `with_params_meta(..)`. Only methods with at least one
// parameter carrying `#[deprecated]` emit a call.
match i {
#(
#params_meta_index => {
#params_meta_schema_calls
}
)*
_ => {}
}
// AUTHZ-CRED-MACRO-3: apply credential decls projected
// from the return type's `CredentialFieldMarker`
// registry (see `credential_decls_per_method` above).
//
// Like the scope match above, this is a per-index
// compile-time match so that type-level calls (here,
// `CredentialsRegistryProbe::<RT>::new()`) resolve at
// macro-expansion time against each method's concrete
// return type.
let __plexus_cred_decls: ::std::vec::Vec<#crate_path::plexus::schema::CredentialFieldDecl> = match i {
#(
#credential_decls_indices => #credential_decls_exprs,
)*
_ => ::std::vec::Vec::new(),
};
if !__plexus_cred_decls.is_empty() {
schema = schema.with_credentials(__plexus_cred_decls);
}
schema
})
.collect::<Vec<_>>();
// Add the auto-generated schema method. SYNAPSE-CC-9 (as
// RETURNS-26 on 0.7): it declares its params `{method?:
// string}` and its return, a `SchemaResult` — this
// `PluginSchema`, or one `MethodSchema` when called with
// `{"method": …}`.
let schema_method = #crate_path::plexus::MethodSchema::auto_schema()
.with_grant(#schema_grant);
methods.push(schema_method);
// IR-3: append `#[child]` method entries. Each entry's role is
// derived from the child method's signature: no extra arg →
// `StaticChild`; `name: &str` arg → `DynamicChild { list_method,
// search_method }` with values threaded through from
// `#[child(list = …, search = …)]`.
#(methods.push(#child_schema_entries);)*
// RETURNS-10: the last step — every entry (the methods, the
// `schema` method, the `#[child]` entries) gets its content
// hash: SHA-256 of its finished schema as canonical JSON, so
// the hash moves with anything a client is generated from,
// down to a field inside T, E or P. Once per process: this
// runs inside `method_schemas()`'s cache.
methods
.into_iter()
.map(#crate_path::plexus::MethodSchema::with_content_hash)
.collect()
}
}
}
}
fn to_pascal_case(s: &str) -> String {
s.split('_')
.map(|word| {
let mut chars = word.chars();
match chars.next() {
None => String::new(),
Some(first) => first.to_uppercase().chain(chars).collect(),
}
})
.collect()
}
/// IR-3: generate the `schema = schema.with_deprecation(DeprecationInfo { .. });`
/// token stream for a method whose `#[deprecated]` / `#[plexus_macros::removed_in]`
/// attributes have been folded into `ParsedDeprecation`.
fn deprecation_call(dep: &ParsedDeprecation, crate_path: &syn::Path) -> TokenStream {
let since = &dep.since;
let removed_in = &dep.removed_in;
let message = &dep.message;
quote! {
schema = schema.with_deprecation(#crate_path::plexus::DeprecationInfo {
since: ::std::string::String::from(#since),
removed_in: ::std::string::String::from(#removed_in),
message: ::std::string::String::from(#message),
});
}
}
/// IR-5: build the `schema = schema.with_params_meta(vec![ParamSchema { .. }, ..]);`
/// token stream for a method whose parameters carry per-param `#[deprecated]`
/// metadata. Returns `None` when no parameter on this method is deprecated —
/// the emitted schema leaves `params_meta` at its default empty `Vec`.
fn params_meta_call(m: &MethodInfo, crate_path: &syn::Path) -> Option<TokenStream> {
let entries: Vec<TokenStream> = m
.params
.iter()
.filter_map(|p| {
let dep = p.deprecation.as_ref()?;
let name = p.name.to_string();
let since = &dep.since;
let removed_in = &dep.removed_in;
let message = &dep.message;
Some(quote! {
#crate_path::plexus::ParamSchema {
name: ::std::string::String::from(#name),
deprecation: ::std::option::Option::Some(
#crate_path::plexus::DeprecationInfo {
since: ::std::string::String::from(#since),
removed_in: ::std::string::String::from(#removed_in),
message: ::std::string::String::from(#message),
}
),
}
})
})
.collect();
if entries.is_empty() {
None
} else {
Some(quote! {
schema = schema.with_params_meta(::std::vec![
#(#entries,)*
]);
})
}
}
/// IR-3: build a `MethodSchema::new(name, description, hash).with_role(..)
/// [.with_deprecation(..)]` expression for a `#[plexus_macros::child]` method.
///
/// The generated schema carries just enough metadata for downstream consumers
/// (synapse CLI, schema introspection) to recognize it as a child-routing
/// entry — the full RPC-method surface (params, returns, cardinality, http_method)
/// doesn't apply to child methods.
fn child_schema_entry(child: &ChildMethodInfo, crate_path: &syn::Path) -> TokenStream {
let name = child.fn_name.to_string();
let description = &child.description;
// Static children emit `MethodRole::StaticChild`; dynamic children emit
// `MethodRole::DynamicChild { list_method, search_method }` with the
// optional sibling-method names threaded through from the attribute.
let role_expr = match child.kind {
ChildMethodKind::Static => quote! { #crate_path::plexus::MethodRole::StaticChild },
ChildMethodKind::Dynamic => {
let list_expr = match &child.list_fn {
Some(ident) => {
let s = ident.to_string();
quote! { ::std::option::Option::Some(::std::string::String::from(#s)) }
}
None => quote! { ::std::option::Option::None },
};
let search_expr = match &child.search_fn {
Some(ident) => {
let s = ident.to_string();
quote! { ::std::option::Option::Some(::std::string::String::from(#s)) }
}
None => quote! { ::std::option::Option::None },
};
// NEST-7: a peer slot — its interface, or none (untyped).
if let Some(shape) = &child.peer {
let interface = crate::codegen::peer::interface_expr(shape, crate_path);
quote! {
#crate_path::plexus::MethodRole::Peer {
list_method: #list_expr,
search_method: #search_expr,
interface: #interface,
}
}
} else {
// NEST-5: the slot's type — the child type's own schema
// (`Option<Planet>`: `Planet`'s), unless `#[child(opaque)]` or
// the type is no activation the macro wrote (a hand-written
// router), which leaves the slot untyped.
let child_expr = match (child.opaque, option_inner(&child.return_ty)) {
(false, Some(inner)) => slot_type_expr(inner, crate_path),
_ => quote! { ::std::option::Option::None },
};
quote! {
#crate_path::plexus::MethodRole::DynamicChild {
list_method: #list_expr,
search_method: #search_expr,
child: #child_expr,
}
}
}
}
};
// The `hash` is left empty here: `compute_method_schemas` gives every
// entry, this one included, its content hash as its last step
// (RETURNS-10) — of the entry itself (name, description, role,
// deprecation). The child's own schema is not this entry's to cover: it
// belongs in the parent's `ChildSummary.hash` / `children_hash`.
let deprecation_application = if let Some(dep) = &child.deprecation {
let call = deprecation_call(dep, crate_path);
quote! { #call }
} else {
quote! {}
};
quote! {
{
let mut schema = #crate_path::plexus::MethodSchema::new(
::std::string::String::from(#name),
::std::string::String::from(#description),
::std::string::String::new(),
);
schema = schema.with_role(#role_expr);
#deprecation_application
schema
}
}
}
/// Check if a type is Option<T>
///
/// This is used to determine if a field should have #[serde(default)]
/// so that it can be omitted from the JSON input.
pub fn is_option_type(ty: &syn::Type) -> bool {
if let syn::Type::Path(type_path) = ty {
if let Some(segment) = type_path.path.segments.last() {
return segment.ident == "Option";
}
}
false
}
/// AUTHZ-CRED-MACRO-3: derive the "credential probe type" for a method —
/// the type that should be probed for `#[derive(Credentials)]` markers.
///
/// RETURNS-8: that is the method's item `T` — the return type minus its
/// `impl Stream`, `Result` and `Progress` wrappers — whatever the signature
/// form. A type that does not derive `Credentials` falls through the
/// autoref probe to the trait's empty-slice default, so the schema's
/// `credentials` field stays empty.
fn effective_credential_probe_type(m: &MethodInfo) -> Option<Type> {
Some(m.ok_ty.clone())
}
/// NEST-5: `T` of `Option<T>` (the last path segment named `Option`).
pub(crate) fn option_inner(ty: &syn::Type) -> Option<&syn::Type> {
let syn::Type::Path(tp) = ty else { return None };
let seg = tp.path.segments.last()?;
if seg.ident != "Option" {
return None;
}
let syn::PathArguments::AngleBracketed(args) = &seg.arguments else { return None };
match args.args.first()? {
syn::GenericArgument::Type(t) => Some(t),
_ => None,
}
}
/// NEST-5: the slot type of a child of type `inner`, as an expression:
/// `slot_type::<inner>()` when `inner` is an `Activation`, else `None` —
/// chosen by autoref (a concrete type here), so a hand-written router that
/// is no activation still compiles, as an untyped slot.
pub(crate) fn slot_type_expr(inner: &syn::Type, crate_path: &syn::Path) -> TokenStream {
quote! {
{
struct __PlexusSlotProbe<__T>(::core::marker::PhantomData<__T>);
trait __PlexusSlotTyped {
fn __plexus_slot(&self) -> ::std::option::Option<::std::boxed::Box<#crate_path::plexus::PluginSchema>>;
}
impl<__T: #crate_path::plexus::Activation> __PlexusSlotTyped for __PlexusSlotProbe<__T> {
fn __plexus_slot(&self) -> ::std::option::Option<::std::boxed::Box<#crate_path::plexus::PluginSchema>> {
#crate_path::plexus::slots::slot_type::<__T>()
}
}
trait __PlexusSlotUntyped {
fn __plexus_slot(&self) -> ::std::option::Option<::std::boxed::Box<#crate_path::plexus::PluginSchema>>;
}
impl<__T> __PlexusSlotUntyped for &__PlexusSlotProbe<__T> {
fn __plexus_slot(&self) -> ::std::option::Option<::std::boxed::Box<#crate_path::plexus::PluginSchema>> {
::std::option::Option::None
}
}
(&__PlexusSlotProbe::<#inner>(::core::marker::PhantomData)).__plexus_slot()
}
}
}