root.rs
cdk-rsx/crates/cdk-rsx-macros/src/root.rs
1//! Lifecycle authoring over the one SDK implementation. Persistent schemas and2//! typed root construction/binding remain in the application memory owner.3use proc_macro2::TokenStream;4use quote::quote;5use syn::{6 Expr, Ident, ItemMod, Path, Token, Type, bracketed,7 parse::{Parse, ParseStream},8 punctuated::Punctuated,9};1011struct Options {12 init: Path,13 restore: Path,14 check: Option<Path>,15 shutdown: Option<Path>,16 arguments: Type,17 request_limits: Expr,18 state: Option<Type>,19 transients: Vec<Path>,20 view: Option<Path>,21 error: Type,22 policies: Vec<Expr>,23 previous: Vec<Type>,24}25impl Parse for Options {26 fn parse(input: ParseStream<'_>) -> syn::Result<Self> {27 let (mut init, mut restore, mut check, mut shutdown, mut arguments) =28 (None, None, None, None, None);29 let (mut state, mut transients, mut view, mut error) = (None, None, None, None);30 let (mut policies, mut previous, mut request_limits) = (None, None, None);31 while !input.is_empty() {32 let name: Ident = input.parse()?;33 input.parse::<Token![=]>()?;34 match name.to_string().as_str() {35 "init" if init.is_none() => init = Some(input.parse()?),36 "restore" if restore.is_none() => restore = Some(input.parse()?),37 "check" if check.is_none() => check = Some(input.parse()?),38 "shutdown" if shutdown.is_none() => shutdown = Some(input.parse()?),39 "arguments" if arguments.is_none() => arguments = Some(input.parse()?),40 "request_limits" if request_limits.is_none() => {41 request_limits = Some(input.parse()?)42 }43 "state" if state.is_none() => state = Some(input.parse()?),44 "view" if view.is_none() => view = Some(input.parse()?),45 "error" if error.is_none() => error = Some(input.parse()?),46 "policies" if policies.is_none() => {47 let content;48 bracketed!(content in input);49 policies = Some(50 Punctuated::<Expr, Token![,]>::parse_terminated(&content)?51 .into_iter()52 .collect(),53 );54 }55 "previous" if previous.is_none() => {56 let content;57 bracketed!(content in input);58 previous = Some(59 Punctuated::<Type, Token![,]>::parse_terminated(&content)?60 .into_iter()61 .collect(),62 );63 }64 "transients" if transients.is_none() => {65 let content;66 bracketed!(content in input);67 transients = Some(68 Punctuated::<Path, Token![,]>::parse_terminated(&content)?69 .into_iter()70 .collect(),71 );72 }73 _ => {74 return Err(syn::Error::new(75 name.span(),76 "unknown or duplicate root option",77 ));78 }79 }80 if input.is_empty() {81 break;82 }83 input.parse::<Token![,]>()?;84 }85 let required = |name| syn::Error::new(input.span(), format!("root requires `{name}`"));86 if state.is_none() {87 if check.is_none() {88 return Err(required("check"));89 }90 if shutdown.is_none() {91 return Err(required("shutdown"));92 }93 if transients.is_some() {94 return Err(input.error("transients requires state"));95 }96 if view.is_some() {97 return Err(input.error("view requires state"));98 }99 if error.is_some() {100 return Err(input.error("error requires state"));101 }102 if policies.is_some() || previous.is_some() {103 return Err(input.error("policies and previous require state"));104 }105 }106 let arguments = match arguments {107 Some(arguments) => arguments,108 None if state.is_some() => syn::parse_quote!(()),109 None => return Err(required("arguments")),110 };111 Ok(Self {112 init: init.ok_or_else(|| required("init"))?,113 restore: restore.ok_or_else(|| required("restore"))?,114 check,115 shutdown,116 arguments,117 request_limits: request_limits118 .unwrap_or_else(|| syn::parse_quote!(::cdk_rsx::wire::DEFAULT_LIMITS)),119 state,120 transients: transients.unwrap_or_default(),121 view,122 error: error.unwrap_or_else(|| syn::parse_quote!(::cdk_rsx_store::Error)),123 policies: policies.unwrap_or_default(),124 previous: previous.unwrap_or_default(),125 })126 }127}128129pub fn expand(attr: TokenStream, item: TokenStream) -> syn::Result<TokenStream> {130 let Options {131 init,132 restore,133 check,134 shutdown,135 arguments,136 request_limits,137 state,138 transients,139 view,140 error,141 policies,142 previous,143 } = syn::parse2(attr)?;144 let declaration: ItemMod = syn::parse2(item)?;145 if !matches!(declaration.vis, syn::Visibility::Public(_)) {146 return Err(syn::Error::new_spanned(147 &declaration,148 "root memory module must be public",149 ));150 }151 if declaration.ident != "memory" {152 return Err(syn::Error::new_spanned(153 &declaration.ident,154 "root must mark `pub mod memory`",155 ));156 }157 let (lifecycle, init, restore, check, shutdown) = if let Some(state) = state {158 let view = match view {159 Some(view) => view,160 None => {161 let Type::Path(path) = &state else {162 return Err(syn::Error::new_spanned(163 &state,164 "state requires a named application type or explicit view",165 ));166 };167 let mut view = path.path.clone();168 let last = view.segments.last_mut().ok_or_else(|| {169 syn::Error::new_spanned(&state, "state requires a named application type")170 })?;171 last.ident = quote::format_ident!("{}View", last.ident);172 view173 }174 };175 let custom_check = check.map(|check| quote!(#check()?;));176 let custom_shutdown = shutdown.map(|shutdown| quote!(#shutdown()?;));177 let policy_list = quote!(__CDK_RSX_POLICIES);178 let source_names = (0..previous.len())179 .map(|index| quote::format_ident!("__CDK_RSX_SOURCE_CATALOG_{index}"))180 .collect::<Vec<_>>();181 let source_catalogs = source_names.iter().zip(&previous).map(|(name, memory)| {182 quote! {183 const #name: ::cdk_rsx_store::Catalog = ::cdk_rsx_store::catalog::<#memory>();184 }185 });186 let source_matches = source_names187 .iter()188 .map(|name| quote!(|| saved == #name.digest(#policy_list)));189 let names = (0..transients.len())190 .map(|index| quote::format_ident!("__cdk_rsx_clear_transient_{index}"))191 .collect::<Vec<_>>();192 let inspections = (0..transients.len())193 .map(|index| quote::format_ident!("__cdk_rsx_transient_clear_{index}"))194 .collect::<Vec<_>>();195 let extra_callbacks = transients.iter().zip(&names).zip(&inspections).map(|((root, clear), inspect)| quote! {196 fn #clear() { drop(::cdk_rsx::transient::ReclaimableKey::take(&#root)); }197 fn #inspect() -> bool { ::cdk_rsx::transient::ReclaimableKey::inspect(&#root, |slot| slot.is_none()) }198 });199 let extra_roots = transients.iter().zip(&names).zip(&inspections).map(|((root, clear), inspect)| quote! {200 ::cdk_rsx::transient::TransientRoot { name: stringify!(#root), clear: #clear, is_clear: #inspect },201 });202 let generated = quote! {203 const __CDK_RSX_POLICIES: &[[u8; 32]] = &[204 ::cdk_rsx::transient::__ROOT_POLICY,205 #(#policies),*206 ];207 const __CDK_RSX_TARGET_CATALOG: ::cdk_rsx_store::Catalog = ::cdk_rsx_store::catalog::<<#state as ::cdk_rsx_store::binding::RootService>::Memory>();208 #(#source_catalogs)*209 ::std::thread_local! { static __CDK_RSX_ADMITTED: ::std::cell::Cell<bool> = const { ::std::cell::Cell::new(false) }; }210 fn __cdk_rsx_catalog_digest() -> [u8; 32] { __CDK_RSX_TARGET_CATALOG.digest(#policy_list) }211 fn __cdk_rsx_admit_digest(is_upgrade: i32, saved: [u8; 32]) -> bool {212 let accepted = match is_upgrade {213 0 => true,214 1 => saved == __cdk_rsx_catalog_digest() #(#source_matches)*,215 _ => false,216 };217 __CDK_RSX_ADMITTED.set(accepted);218 accepted219 }220 #[cfg(target_family = "wasm")]221 #[unsafe(export_name = "__cdk_rsx_memory_abi_admit")]222 pub extern "C" fn __cdk_rsx_admit(is_upgrade: i32) -> i32 {223 let saved = if is_upgrade == 1 {224 // SAFETY: the canonical checked startup calls this only225 // after admitting the fixed bootstrap, before any pointer.226 unsafe { ::cdk_rsx_store::__private::read_saved_digest() }227 } else { [0; 32] };228 if !__cdk_rsx_admit_digest(is_upgrade, saved) {229 ::cdk_rsx::trap("root catalog rejected");230 }231 1232 }233 fn __cdk_rsx_require_admission() {234 assert!(__CDK_RSX_ADMITTED.get(), "root catalog not admitted");235 }236 #[cfg(target_family = "wasm")]237 static APP: ::cdk_rsx::transient::HotRoot<#state> = {238 // SAFETY: this expansion also defines the unique canister init239 // and memory-admission exports. Duplicate generated roots fail240 // the final link. APP is private and fixes one App type for the241 // executable lifetime; registered teardown clears it before KEEP.242 unsafe { ::cdk_rsx::transient::HotRoot::new() }243 };244 #[cfg(not(target_family = "wasm"))]245 ::std::thread_local! { static APP: ::cdk_rsx::transient::Reclaimable<Option<#state>> = const { ::cdk_rsx::transient::Reclaimable::new() }; }246 fn __cdk_rsx_clear_app() { ::cdk_rsx::transient::RootKey::clear(&APP); }247 fn __cdk_rsx_app_clear() -> bool { ::cdk_rsx::transient::RootKey::is_empty(&APP) }248 #(#extra_callbacks)*249 static __CDK_RSX_ROOTS: &[::cdk_rsx::transient::TransientRoot] = &[250 ::cdk_rsx::transient::TransientRoot { name: concat!(module_path!(), "::APP"), clear: __cdk_rsx_clear_app, is_clear: __cdk_rsx_app_clear },251 #(#extra_roots)*252 ];253 fn save(app: #state) {254 ::cdk_rsx::transient::RootKey::install(&APP, app);255 }256 fn __cdk_rsx_publish_root() {257 __cdk_rsx_require_admission();258 assert!(!::cdk_rsx::transient::RootKey::is_empty(&APP), "root callback did not install app");259 #[cfg(target_family = "wasm")]260 // SAFETY: admission preceded the callback; its successful261 // construction/conversion installed the typed target app.262 unsafe { ::cdk_rsx_store::__private::write_saved_digest(__cdk_rsx_catalog_digest()) };263 }264 fn __cdk_rsx_initialize_root(arguments: #arguments) -> ::core::result::Result<(), #error> {265 __cdk_rsx_require_admission();266 #init(arguments)?;267 __cdk_rsx_publish_root();268 Ok(())269 }270 fn __cdk_rsx_restore_root() -> ::core::result::Result<(), #error> {271 __cdk_rsx_require_admission();272 #restore()?;273 __cdk_rsx_publish_root();274 Ok(())275 }276 fn __cdk_rsx_check_root() -> ::core::result::Result<(), #error> {277 ::cdk_rsx_store::assert_quiescent();278 #custom_check279 Ok(())280 }281 fn __cdk_rsx_shutdown_root() -> ::core::result::Result<(), #error> {282 #custom_shutdown283 ::cdk_rsx::transient::run_registered(__CDK_RSX_ROOTS);284 Ok(())285 }286 fn __cdk_rsx_checked<R>(result: ::core::result::Result<R, #error>) -> R {287 result.unwrap_or_else(|error| ::cdk_rsx::trap(format!("root memory: {error:?}")))288 }289 pub(crate) fn read<R>(f: impl for<'a, 's> FnOnce(#view<'a, ::cdk_rsx_store::ReadScope<'s>>) -> ::core::result::Result<R, #error>) -> R {290 __cdk_rsx_checked(::cdk_rsx::transient::RootKey::with(&APP, |app| app.read(f)))291 }292 pub(crate) fn with<R>(f: impl for<'a, 's> FnOnce(#view<'a, ::cdk_rsx_store::Scope<'s>>) -> ::core::result::Result<R, #error>) -> R {293 __cdk_rsx_checked(::cdk_rsx::transient::RootKey::with(&APP, |app| app.with(f)))294 }295 };296 (297 generated,298 quote!(__cdk_rsx_initialize_root),299 quote!(__cdk_rsx_restore_root),300 quote!(__cdk_rsx_check_root),301 quote!(__cdk_rsx_shutdown_root),302 )303 } else {304 (305 quote!(),306 quote!(#init),307 quote!(#restore),308 quote!(#check),309 quote!(#shutdown),310 )311 };312 Ok(quote! {313 #declaration314 #lifecycle315 ::cdk_rsx::static_canister! {316 init = #init,317 restore = #restore,318 check = #check,319 shutdown = #shutdown,320 arguments = #arguments,321 request_limits = #request_limits322 }323 })324}325326#[cfg(test)]327mod tests {328 use super::*;329330 #[test]331 fn state_mode_declares_one_inventory_and_preserves_domain_hooks() {332 let output = expand(333 quote!(334 state = App,335 init = install,336 restore = reopen,337 check = domain_check,338 shutdown = domain_shutdown,339 transients = [CACHE]340 ),341 quote!(342 pub mod memory;343 ),344 )345 .unwrap()346 .to_string();347 assert_eq!(output.matches("run_registered").count(), 1);348 assert!(output.contains("domain_check () ?"));349 assert!(output.contains("domain_shutdown () ?"));350 assert!(output.contains("take (& CACHE)"));351 assert!(output.contains("AppView"));352 assert!(output.contains("transient :: __ROOT_POLICY"));353 assert!(!output.contains("COLLECTIONS_POLICY"));354 assert!(!output.contains("WIRE_POLICY"));355 assert!(output.contains("RootService > :: Memory"));356 assert!(output.contains("HotRoot < App >"));357 assert!(output.contains("RootKey :: install"));358 assert!(output.contains("RootKey :: clear"));359 }360361 #[test]362 fn lifecycle_attribute_delegates_to_the_single_hidden_hook_implementation() {363 let expanded = expand(364 quote!(365 init = install,366 restore = reopen,367 check = drained,368 shutdown = clear,369 arguments = (u64,)370 ),371 quote!(372 pub mod memory;373 ),374 )375 .unwrap()376 .to_string();377 assert!(expanded.contains("static_canister"));378 for path in ["install", "reopen", "drained", "clear"] {379 assert!(expanded.contains(path));380 }381 assert!(!expanded.contains("HostedStore"));382 assert!(!expanded.contains("initialize_actor"));383 }384385 #[test]386 fn every_lifecycle_stage_is_required_and_unknown_options_are_rejected() {387 for options in [388 quote!(init = a, restore = b, check = c, shutdown = d),389 quote!(init = a, restore = b, check = c, arguments = ()),390 quote!(init = a, restore = b, shutdown = d, arguments = ()),391 quote!(init = a, check = c, shutdown = d, arguments = ()),392 quote!(restore = b, check = c, shutdown = d, arguments = ()),393 quote!(394 init = a,395 restore = b,396 check = c,397 shutdown = d,398 arguments = (),399 bindings = Service400 ),401 quote!(402 init = a,403 init = z,404 restore = b,405 check = c,406 shutdown = d,407 arguments = ()408 ),409 ] {410 assert!(411 expand(412 options,413 quote!(414 pub mod memory;415 )416 )417 .is_err()418 );419 }420 }421422 #[test]423 fn root_marks_the_public_memory_owner() {424 let options = quote!(425 init = a,426 restore = b,427 check = c,428 shutdown = d,429 arguments = ()430 );431 assert!(432 expand(433 options.clone(),434 quote!(435 mod memory;436 )437 )438 .is_err()439 );440 assert!(441 expand(442 options,443 quote!(444 pub mod state;445 )446 )447 .is_err()448 );449 }450}