export.rs

cdk-rsx/crates/cdk-rsx-macros/src/export.rs

export.rs876 lines← SDK documentation
1use proc_macro2::{Ident, Span, TokenStream};2use quote::{format_ident, quote};3use std::fmt::Formatter;4use syn::spanned::Spanned;5use syn::{Error, FnArg, ItemFn, Pat, PatIdent, PatType, Path, ReturnType, Signature, Type};67#[derive(Default)]8struct ExportAttributes {9    name: Option<String>,10    guard: Vec<Path>,11    manual_reply: bool,12    composite: bool,13    raw: bool,14    tripwire: bool,15    evolve_reply: bool,16    max_arg_bytes: Option<syn::Expr>,17    request_limits: Option<syn::Expr>,18    response_limits: Option<syn::Expr>,19}20impl syn::parse::Parse for ExportAttributes {21    fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> {22        use syn::ext::IdentExt;23        let mut out = Self::default();24        let mut seen = std::collections::BTreeSet::new();25        while !input.is_empty() {26            let key = input.call(Ident::parse_any)?;27            let name = key.to_string();28            if name != "guard" && !seen.insert(name.clone()) {29                return Err(Error::new(key.span(), "duplicate endpoint option"));30            }31            match name.as_str() {32                "manual_reply" | "composite" | "raw" | "tripwire" | "evolve_reply" => {33                    let value = if input.peek(syn::Token![=]) {34                        input.parse::<syn::Token![=]>()?;35                        input.parse::<syn::LitBool>()?.value()36                    } else {37                        true38                    };39                    if name == "manual_reply" {40                        out.manual_reply = value;41                    } else if name == "raw" {42                        out.raw = value;43                    } else if name == "tripwire" {44                        out.tripwire = value;45                    } else if name == "evolve_reply" {46                        out.evolve_reply = value;47                    } else {48                        out.composite = value;49                    }50                }51                "request_limits" | "response_limits" => {52                    input.parse::<syn::Token![=]>()?;53                    let limits = Some(input.parse()?);54                    if name == "request_limits" {55                        out.request_limits = limits;56                    } else {57                        out.response_limits = limits;58                    }59                }60                "max_arg_bytes" => {61                    input.parse::<syn::Token![=]>()?;62                    out.max_arg_bytes = Some(input.parse()?);63                }64                "name" => {65                    input.parse::<syn::Token![=]>()?;66                    out.name = Some(input.parse::<syn::LitStr>()?.value());67                }68                "guard" => {69                    input.parse::<syn::Token![=]>()?;70                    if input.peek(syn::LitStr) {71                        return Err(input.error("expected a Rust path, without quotes"));72                    }73                    let path: Path = input.parse()?;74                    out.guard.push(path);75                }76                _ => return Err(Error::new(key.span(), "Unknown field in endpoint options")),77            }78            if input.is_empty() {79                break;80            }81            input.parse::<syn::Token![,]>()?;82        }83        Ok(out)84    }85}8687#[derive(Copy, Clone, Debug, Eq, PartialEq)]88enum MethodType {89    Update,90    Query,91    Heartbeat,92    InspectMessage,93    OnLowWasmMemory,94}9596impl MethodType {97    fn is_lifecycle(&self) -> bool {98        !matches!(self, Self::Update | Self::Query)99    }100    fn can_have_args(&self) -> bool {101        !self.is_lifecycle()102    }103    fn is_state_persistent(&self) -> bool {104        !matches!(self, Self::Query | Self::InspectMessage)105    }106}107impl std::fmt::Display for MethodType {108    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {109        f.write_str(match self {110            Self::Query => "query",111            Self::Update => "update",112            Self::Heartbeat => "heartbeat",113            Self::InspectMessage => "inspect_message",114            Self::OnLowWasmMemory => "on_low_wasm_memory",115        })116    }117}118119fn get_args(method: MethodType, signature: &Signature) -> Result<Vec<(Ident, Box<Type>)>, Error> {120    // We only need the tuple of arguments, not their types. Magic of type inference.121    let mut args = vec![];122    for (i, arg) in signature.inputs.iter().enumerate() {123        let (ident, ty) = match arg {124            FnArg::Receiver(r) => {125                return Err(Error::new(126                    r.span(),127                    format!("#[{method}] cannot be above functions with `self` as a parameter."),128                ));129            }130            FnArg::Typed(PatType { pat, ty, .. }) => {131                let ident = if let Pat::Ident(PatIdent { ident, .. }) = pat.as_ref() {132                    // If the argument is named the same as the function, we need to rename it.133                    if ident == &signature.ident {134                        format_ident!("__arg_{}", ident, span = pat.span())135                    } else {136                        ident.clone()137                    }138                } else {139                    format_ident!("__unnamed_arg_{i}", span = pat.span())140                };141                (ident, ty.clone())142            }143        };144145        args.push((ident, ty));146    }147148    Ok(args)149}150151fn dfn_macro(152    method: MethodType,153    attr: TokenStream,154    item: TokenStream,155) -> Result<TokenStream, Error> {156    let attr_span = attr.span();157    let attrs: ExportAttributes = syn::parse2(attr)?;158    let raw_protocol = attrs.raw || attrs.tripwire;159    if attrs.raw && attrs.tripwire {160        return Err(Error::new(161            attr_span,162            "raw and tripwire are mutually exclusive",163        ));164    }165    if (raw_protocol || method.is_lifecycle())166        && (attrs.request_limits.is_some() || attrs.response_limits.is_some())167    {168        return Err(Error::new(169            attr_span,170            "Wire limits apply only to typed query/update endpoints",171        ));172    }173    if attrs.composite && method != MethodType::Query {174        return Err(Error::new(attr_span, "composite is only valid on queries"));175    }176    if attrs.manual_reply && method.is_lifecycle() {177        return Err(Error::new(178            attr_span,179            "manual_reply cannot be combined with lifecycle hooks",180        ));181    }182    if raw_protocol && (method.is_lifecycle() || attrs.manual_reply) {183        return Err(Error::new(184            attr_span,185            "raw and tripwire endpoints cannot use lifecycle, manual_reply or typed codec options",186        ));187    }188    let typed_method = !raw_protocol && !method.is_lifecycle();189    if (!typed_method || attrs.manual_reply) && attrs.evolve_reply {190        return Err(Error::new(191            attr_span,192            "evolve_reply requires an automatically replied typed endpoint",193        ));194    }195    if raw_protocol != attrs.max_arg_bytes.is_some() {196        return Err(Error::new(197            attr_span,198            "raw and tripwire endpoints require max_arg_bytes; max_arg_bytes is only valid with raw or tripwire",199        ));200    }201202    let mut fun: ItemFn = syn::parse2::<syn::ItemFn>(item.clone()).map_err(|e| {203        Error::new(204            item.span(),205            format!("#[{method}] must be above a function. \n{e}"),206        )207    })?;208    let mut evolving_args = Vec::new();209    for arg in &mut fun.sig.inputs {210        let FnArg::Typed(arg) = arg else { continue };211        let mut markers = arg212            .attrs213            .iter()214            .filter(|attr| attr.path().is_ident("evolve"));215        let marker = markers.next();216        if let Some(marker) = marker {217            if !typed_method218                || markers.next().is_some()219                || !matches!(marker.meta, syn::Meta::Path(_))220            {221                return Err(Error::new_spanned(222                    marker,223                    "one #[evolve] argument marker is allowed on a typed Wire endpoint",224                ));225            }226        }227        evolving_args.push(marker.is_some());228        arg.attrs.retain(|attr| !attr.path().is_ident("evolve"));229    }230    let signature = &fun.sig;231    if attrs.tripwire && signature.asyncness.is_some() {232        return Err(Error::new(233            signature.span(),234            "tripwire endpoints must be synchronous; request handles cannot cross await",235        ));236    }237    if raw_protocol {238        let args = get_args(method, signature)?;239        let byte_vec = |ty: &Type| {240            match ty {241            Type::Path(path) => path.path.segments.last().is_some_and(|segment| {242                segment.ident == "Vec" && matches!(&segment.arguments, syn::PathArguments::AngleBracketed(args)243                    if args.args.len() == 1 && matches!(args.args.first(), Some(syn::GenericArgument::Type(Type::Path(t))) if t.path.is_ident("u8")))244            }),245            _ => false,246        }247        };248        let output_bytes = matches!(&signature.output, ReturnType::Type(_, ty) if byte_vec(ty));249        if attrs.raw && (args.len() != 1 || !byte_vec(&args[0].1) || !output_bytes) {250            return Err(Error::new(251                signature.span(),252                "raw endpoint signature must be exactly one Vec<u8> argument and a Vec<u8> return",253            ));254        }255        if attrs.tripwire {256            let message = args.first().is_some_and(|(_, ty)| match ty.as_ref() {257                Type::Path(path) if path.qself.is_none() => path.path.segments.last().is_some_and(|segment| {258                    matches!(&segment.arguments, syn::PathArguments::AngleBracketed(arguments)259                        if arguments.args.len() == 1260                        && matches!(arguments.args.first(), Some(syn::GenericArgument::Lifetime(lifetime)) if lifetime.ident == "_"))261                }),262                _ => false,263            });264            if args.len() != 1 || !message || matches!(&signature.output, ReturnType::Default) {265                return Err(Error::new(266                    signature.span(),267                    "tripwire endpoints require one Message<'_> argument and an explicit return type implementing AsRef<[u8]>",268                ));269            }270        }271    }272    let generics = &signature.generics;273274    if !generics.params.is_empty() {275        return Err(Error::new(276            generics.span(),277            format!("#[{method}] must be above a function with no generic parameters."),278        ));279    }280    let cratename: Path = syn::parse_str("::cdk_rsx")?;281282    // 1. function name(s)283    let name = &signature.ident;284    let outer_function_ident = format_ident!("__canister_method_{name}");285    let function_name = if let Some(custom_name) = attrs.name {286        if method.is_lifecycle() {287            return Err(Error::new(288                attr_span,289                format!("#[{method}] cannot have a custom name"),290            ));291        }292        if custom_name.starts_with("<cdk-rsx internal>") {293            return Err(Error::new(294                attr_span,295                "Functions starting with `<cdk-rsx internal>` are reserved for CDK internal use.",296            ));297        }298        custom_name299    } else {300        name.to_string()301    };302    let export_name = if method.is_lifecycle() {303        format!("canister_{method}")304    } else if method == MethodType::Query && attrs.composite {305        format!("canister_composite_query {function_name}",)306    } else {307        format!("canister_{method} {function_name}")308    };309    if raw_protocol && (function_name.contains(['\t', '\n', '\r']) || function_name.is_empty()) {310        return Err(Error::new(311            attr_span,312            "raw method names must be nonempty and contain no line separators",313        ));314    }315316    // 2. guard(s)317    if !attrs.guard.is_empty() && method.is_lifecycle() {318        return Err(Error::new(319            attr_span,320            format!("#[{method}] cannot have guard function(s)."),321        ));322    }323    let guards = attrs324        .guard325        .iter()326        .map(|guard_name| -> Result<_, Error> {327            let guard_path = guard_name;328            Ok(quote! {329                let r: ::core::result::Result<(), ::std::string::String> = #guard_path ();330                if let ::core::result::Result::Err(e) = r {331                    #cratename::api::msg_reject(&e);332                    return;333                }334            })335        })336        .collect::<Result<Vec<_>, Error>>()?;337    let guard = quote! {338        #(#guards)*339    };340341    let request_limits = attrs342        .request_limits343        .as_ref()344        .map(|x| quote!(#x))345        .unwrap_or_else(|| quote!(#cratename::wire::DEFAULT_LIMITS));346    let response_limits = attrs347        .response_limits348        .as_ref()349        .map(|x| quote!(#x))350        .unwrap_or_else(|| quote!(#cratename::wire::DEFAULT_LIMITS));351    // 3. decode arguments352    let (arg_tuple, arg_types): (Vec<Ident>, Vec<Box<Type>>) =353        get_args(method, signature)?.iter().cloned().unzip();354    let ret_type = match &signature.output {355        ReturnType::Default => quote!(()),356        ReturnType::Type(_, ty) => quote!(#ty),357    };358    let evolution_types = typed_method.then(|| {359        let wire_types = arg_types.iter().zip(&evolving_args).map(|(ty, evolving)| {360            if *evolving {361                quote!(#ty)362            } else {363                quote!(#cratename::wire::evolve::Fixed<#ty>)364            }365        });366        let reply_type = if attrs.evolve_reply {367            ret_type.clone()368        } else {369            quote!(#cratename::wire::evolve::Fixed<#ret_type>)370        };371        let reply = (!attrs.manual_reply).then(|| {372            quote! {373                #[cfg(target_family = "wasm")]374                #[derive(#cratename::wire::upstream::Wire)]375                #[wire(crate = "::cdk_rsx::wire::upstream")]376                struct __CdkRsxEvolvingReply(#reply_type);377            }378        });379        quote! {380            #[cfg(target_family = "wasm")]381            #[derive(#cratename::wire::upstream::Wire)]382            #[wire(crate = "::cdk_rsx::wire::upstream")]383            struct __CdkRsxEvolvingRequest(#(#wire_types,)*);384            #reply385        }386    });387    if !method.can_have_args() {388        if !arg_tuple.is_empty() {389            return Err(Error::new(390                Span::call_site(),391                format!("#[{method}] function cannot have arguments."),392            ));393        }394    }395    let arg_decode = if attrs.raw {396        let arg = &arg_tuple[0];397        let max = attrs.max_arg_bytes.as_ref().unwrap();398        quote! {399            const __CDK_RSX_MAX_ARG_BYTES: usize = #max;400            let #arg = #cratename::argument_bytes_with_limit(__CDK_RSX_MAX_ARG_BYTES);401        }402    } else if attrs.tripwire || method.is_lifecycle() {403        quote! {}404    } else {405        let bindings = arg_tuple.iter().zip(&evolving_args).map(|(arg, evolving)| {406            if *evolving {407                quote!(#arg)408            } else {409                quote!(#cratename::wire::evolve::Fixed(#arg))410            }411        });412        quote! {413            const __CDK_RSX_REQUEST_LIMITS: #cratename::wire::Limits = #cratename::wire::assert_limits(#request_limits);414            let __CdkRsxEvolvingRequest(#(#bindings,)*) =415                #cratename::__argument_evolving(__CDK_RSX_REQUEST_LIMITS);416        }417    };418419    // 4. function call420    let function_call = if attrs.tripwire {421        let arg = &arg_tuple[0];422        let request = &arg_types[0];423        let max = attrs.max_arg_bytes.as_ref().unwrap();424        quote! {{425            const __CDK_RSX_MAX_ARG_BYTES: usize = {426                let max: usize = #max;427                assert!(max > 0, "Tripwire byte limit must be positive");428                max429            };430            <#request>::with_current(__CDK_RSX_MAX_ARG_BYTES, |#arg| #name(#arg))431                .unwrap_or_else(|error| #cratename::tripwire::__reject_request(error))432        }}433    } else if signature.asyncness.is_some() {434        quote! { #name ( #(#arg_tuple),* ) .await }435    } else {436        quote! { #name ( #(#arg_tuple),* ) }437    };438439    // 5. return440    let return_length = match &signature.output {441        ReturnType::Default => 0,442        ReturnType::Type(_, ty) => match ty.as_ref() {443            Type::Tuple(tuple) => tuple.elems.len(),444            _ => 1,445        },446    };447    if method.is_lifecycle() {448        if return_length > 0 {449            return Err(Error::new(450                Span::call_site(),451                format!("#[{method}] function cannot have a return value."),452            ));453        }454    }455    let return_encode = if raw_protocol {456        quote! { #cratename::api::msg_reply(result); }457    } else if method.is_lifecycle() || attrs.manual_reply {458        quote! {}459    } else {460        let value = if attrs.evolve_reply {461            quote!(result)462        } else {463            quote!(#cratename::wire::evolve::Fixed(result))464        };465        quote! {466            const __CDK_RSX_RESPONSE_LIMITS: #cratename::wire::Limits = #cratename::wire::assert_limits(#response_limits);467            #cratename::__reply_evolving(468                __CdkRsxEvolvingReply(#value), __CDK_RSX_RESPONSE_LIMITS,469            )470            .unwrap_or_else(|error| #cratename::api::trap(format!("Wire reply rejected: {error}")));471        }472    };473474    // 7. exported function body475    let async_context_name = if method.is_state_persistent() {476        format_ident!("in_executor_context")477    } else {478        format_ident!("in_query_executor_context")479    };480    let body = if signature.asyncness.is_some() {481        quote! {482            #cratename::futures::internals::#async_context_name(|| {483                #guard484                #[allow(clippy::disallowed_methods)]485                #cratename::futures::spawn(async {486                    #arg_decode487                    let result = #function_call;488                    #return_encode489                });490            });491        }492    } else {493        quote! {494            #cratename::futures::internals::#async_context_name(|| {495                #guard496                #arg_decode497                let result = #function_call;498                #return_encode499            });500        }501    };502503    let cfg_attrs: Vec<_> = fun504        .attrs505        .iter()506        .filter(|a| a.path().is_ident("cfg") || a.path().is_ident("cfg_attr"))507        .collect();508    let descriptor = if raw_protocol {509        let section_ident = format_ident!("__CDK_RSX_RAW_METHOD_{name}");510        let mode = if method == MethodType::Query && attrs.composite {511            "composite_query"512        } else if method == MethodType::Query {513            "query"514        } else {515            "update"516        };517        let data =518            proc_macro2::Literal::byte_string(format!("{mode}\t{function_name}\n").as_bytes());519        let len = format!("{mode}\t{function_name}\n").len();520        quote! {521            #[cfg(target_family = "wasm")]522            #(#cfg_attrs)*523            #[used]524            #[unsafe(link_section = "cdk-rsx:raw-methods")]525            static #section_ident: [u8; #len] = *#data;526        }527    } else if method.is_lifecycle() {528        quote!()529    } else {530        let arg_types: Vec<_> = signature531            .inputs532            .iter()533            .filter_map(|arg| match arg {534                FnArg::Typed(arg) => Some(&arg.ty),535                _ => None,536            })537            .collect();538        let mode = if method == MethodType::Query {539            if attrs.composite {540                "composite_query"541            } else {542                "query"543            }544        } else {545            "update"546        };547        let signature = {548            let request = arg_types.iter().zip(&evolving_args).map(|(ty, evolving)| {549                if *evolving {550                    quote!(#cratename::wire::evolve::schema_for::<#ty>(registry))551                } else {552                    quote!(<#ty as #cratename::wire::WireType>::wire_type(registry))553                }554            });555            let reply = if attrs.evolve_reply {556                quote!(#cratename::wire::evolve::schema_for::<#ret_type>(registry))557            } else {558                quote!(<#ret_type as #cratename::wire::WireType>::wire_type(registry))559            };560            quote! {561                (562                    #cratename::interface::evolution_tuple(vec![#(#request,)*]),563                    #cratename::interface::evolution_tuple(vec![#reply]),564                )565            }566        };567        let assert_arguments = {568            let checks = arg_types.iter().zip(&evolving_args).map(|(ty, evolving)| {569                if *evolving {570                    quote!(let _ = #cratename::assert_evolving_argument::<#ty>;)571                } else {572                    quote!(let _ = #cratename::assert_arguments::<#ty>;)573                }574            });575            quote!(#(#checks)*)576        };577        quote! {578            #[cfg(not(target_family = "wasm"))]579            #(#cfg_attrs)*580            #cratename::interface::inventory::submit! {581                #cratename::interface::Method {582                    package: concat!(env!("CARGO_PKG_NAME"), "@", env!("CARGO_PKG_VERSION"), ":", env!("CARGO_MANIFEST_DIR")),583                    name: #function_name,584                    mode: #mode,585                    request_limits: #cratename::wire::assert_limits(#request_limits),586                    response_limits: #cratename::wire::assert_limits(#response_limits),587                    signature: |registry| {588                        #assert_arguments589                        #signature590                    },591                }592            }593        }594    };595    let expanded = quote! {596        #descriptor597        #[cfg(target_family = "wasm")]598        #(#cfg_attrs)*599        #[unsafe(export_name = #export_name)]600        fn #outer_function_ident() {601            #body602        }603604    };605    let expanded = if let Some(evolution_types) = evolution_types {606        quote! {607            #(#cfg_attrs)*608            const _: () = {609                #evolution_types610                #expanded611            };612        }613    } else {614        expanded615    };616    Ok(quote! {617        #expanded618        #[cfg(target_family = "wasm")]619        #fun620    })621}622623pub(crate) fn ic_query(attr: TokenStream, item: TokenStream) -> Result<TokenStream, Error> {624    dfn_macro(MethodType::Query, attr, item)625}626627pub(crate) fn ic_update(attr: TokenStream, item: TokenStream) -> Result<TokenStream, Error> {628    dfn_macro(MethodType::Update, attr, item)629}630631pub(crate) fn ic_heartbeat(attr: TokenStream, item: TokenStream) -> Result<TokenStream, Error> {632    dfn_macro(MethodType::Heartbeat, attr, item)633}634635pub(crate) fn ic_inspect_message(636    attr: TokenStream,637    item: TokenStream,638) -> Result<TokenStream, Error> {639    dfn_macro(MethodType::InspectMessage, attr, item)640}641642pub(crate) fn ic_on_low_wasm_memory(643    attr: TokenStream,644    item: TokenStream,645) -> Result<TokenStream, Error> {646    dfn_macro(MethodType::OnLowWasmMemory, attr, item)647}648649#[cfg(test)]650mod tests {651    use super::*;652    #[test]653    fn paths_are_rust_syntax_and_contradictions_fail() {654        let item = quote!(655            fn endpoint(value: u64) -> u64 {656                value657            }658        );659        assert!(ic_update(quote!(guard = crate::guard), item.clone()).is_ok());660        assert!(661            ic_update(quote!(guard = "crate::guard"), item.clone())662                .unwrap_err()663                .to_string()664                .contains("without quotes")665        );666        assert!(ic_update(quote!(composite = true), item.clone()).is_err());667        assert!(668            ic_update(669                quote!(manual_reply = true, encode_with = crate::encode),670                item671            )672            .is_err()673        );674    }675    #[test]676    fn tuple_and_scalar_replies_use_declared_wire_type() {677        let scalar = ic_query(678            quote!(),679            quote!(680                fn f() -> u64 {681                    7682                }683            ),684        )685        .unwrap()686        .to_string();687        let singleton = ic_query(688            quote!(),689            quote!(690                fn f() -> (u64,) {691                    (7,)692                }693            ),694        )695        .unwrap()696        .to_string();697        let pair = ic_query(698            quote!(),699            quote!(700                fn f() -> (u64, bool) {701                    (7, true)702                }703            ),704        )705        .unwrap()706        .to_string();707        assert!(scalar.contains("__reply_evolving"));708        assert!(singleton.contains("__reply_evolving"));709        assert!(pair.contains("__reply_evolving"));710    }711    #[test]712    fn conditions_cover_the_export_and_native_descriptor() {713        let out = ic_query(714            quote!(),715            quote!(716                #[cfg(feature = "enabled")]717                fn f() -> u64 {718                    7719                }720            ),721        )722        .unwrap()723        .to_string();724        assert_eq!(out.matches("cfg (feature = \"enabled\")").count(), 4);725        assert!(out.contains("inventory :: submit"));726    }727    #[test]728    fn raw_endpoints_have_no_wire_descriptor_and_require_owned_bytes() {729        let item = quote!(730            fn wire(bytes: Vec<u8>) -> Vec<u8> {731                bytes732            }733        );734        let expanded = ic_update(quote!(raw, max_arg_bytes = crate::MAX), item.clone())735            .unwrap()736            .to_string();737        assert!(expanded.contains("argument_bytes_with_limit"));738        assert!(expanded.contains("cdk-rsx:raw-methods"));739        assert!(!expanded.contains("inventory"));740        assert!(!expanded.contains("encode_reply"));741        assert!(!expanded.contains(":: argument ()"));742        assert!(ic_query(quote!(raw, max_arg_bytes = 128), item).is_ok());743        for item in [744            quote!(745                fn bad() -> Vec<u8> {746                    vec![]747                }748            ),749            quote!(750                fn bad(v: Vec<u8>) -> bool {751                    true752                }753            ),754            quote!(755                fn bad(v: &[u8]) -> Vec<u8> {756                    vec![]757                }758            ),759        ] {760            assert!(ic_update(quote!(raw, max_arg_bytes = 128), item).is_err());761        }762        assert!(763            ic_update(764                quote!(raw),765                quote!(766                    fn bad(v: Vec<u8>) -> Vec<u8> {767                        v768                    }769                )770            )771            .is_err()772        );773        assert!(774            ic_update(775                quote!(max_arg_bytes = 128),776                quote!(777                    fn bad() {}778                )779            )780            .is_err()781        );782    }783784    #[test]785    fn tripwire_keeps_executor_guards_and_raw_metadata_without_copying_arguments() {786        let expanded = ic_update(787            quote!(tripwire, max_arg_bytes = crate::MAX, guard = crate::guard),788            quote!(789                fn submit(request: crate::Submit<'_>) -> [u8; 8] {790                    request.reply()791                }792            ),793        )794        .unwrap()795        .to_string();796        assert!(expanded.contains("in_executor_context"));797        assert!(expanded.contains(":: guard ()"));798        assert!(expanded.contains(":: with_current (__CDK_RSX_MAX_ARG_BYTES"));799        assert!(expanded.contains("| request | submit (request)"));800        assert!(expanded.contains("msg_reply (result)"));801        assert!(expanded.contains("tripwire :: __reject_request (error)"));802        assert!(!expanded.contains("Tripwire request rejected"));803        assert!(expanded.contains("assert ! (max > 0"));804        assert!(expanded.contains("cdk-rsx:raw-methods"));805        assert!(!expanded.contains("argument_bytes"));806        assert!(!expanded.contains("argument_with_limits"));807        assert!(!expanded.contains("inventory"));808        assert!(!expanded.contains("spawn"));809        assert!(expanded.find(":: guard ()").unwrap() < expanded.find(":: with_current").unwrap());810    }811812    #[test]813    fn tripwire_rejects_async_owned_or_unbounded_request_contracts() {814        let valid = quote!(815            fn submit(request: Submit<'_>) -> Vec<u8> {816                vec![]817            }818        );819        for options in [820            quote!(tripwire),821            quote!(tripwire, raw, max_arg_bytes = 128),822            quote!(tripwire, manual_reply, max_arg_bytes = 128),823            quote!(tripwire, request_limits = LIMITS, max_arg_bytes = 128),824            quote!(tripwire, response_limits = LIMITS, max_arg_bytes = 128),825            quote!(tripwire, tripwire, max_arg_bytes = 128),826        ] {827            assert!(ic_update(options, valid.clone()).is_err());828        }829        for item in [830            quote!(831                async fn submit(request: Submit<'_>) -> Vec<u8> {832                    vec![]833                }834            ),835            quote!(836                fn submit(request: Submit<'static>) -> Vec<u8> {837                    vec![]838                }839            ),840            quote!(841                fn submit(request: Vec<u8>) -> Vec<u8> {842                    request843                }844            ),845            quote!(846                fn submit(request: &Submit<'_>) -> Vec<u8> {847                    vec![]848                }849            ),850            quote!(851                fn submit() -> Vec<u8> {852                    vec![]853                }854            ),855            quote!(856                fn submit(request: Submit<'_>, other: u8) -> Vec<u8> {857                    vec![]858                }859            ),860            quote!(861                fn submit(request: Submit<'_>) {}862            ),863        ] {864            assert!(ic_update(quote!(tripwire, max_arg_bytes = 128), item).is_err());865        }866        assert!(867            ic_heartbeat(868                quote!(tripwire, max_arg_bytes = 128),869                quote!(870                    fn tick() {}871                )872            )873            .is_err()874        );875    }876}