momento_functions/macros/
function_spawn.rs

1/// Create a handler for a momento::host::spawn::spawn_function.
2///
3/// You can use raw bytes, or json-marshalled types.
4///
5/// **Raw:**
6/// ```rust
7/// momento_functions::spawn!(triggered);
8/// fn triggered(payload: Vec<u8>) -> FunctionResult<()> {
9///     Ok(())
10/// }
11/// ```
12///
13/// **Typed JSON:**
14/// ```rust
15/// #[derive(serde::Deserialize)]
16/// struct Request {
17///     name: String,
18/// }
19///
20/// momento_functions::spawn!(greet, Request);
21/// fn greet(request: Request) -> FunctionResult<()> {
22///     Ok(())
23/// }
24/// ```
25#[macro_export]
26macro_rules! spawn {
27    ($spawn_handler: ident) => {
28        use momento_functions_host::FunctionResult;
29        struct SpawnFunction;
30        momento_functions_wit::function_spawn::export_spawn_function!(SpawnFunction);
31
32        #[automatically_derived]
33        impl momento_functions_wit::function_spawn::exports::momento::functions::guest_function_spawn::Guest for SpawnFunction {
34            fn spawned(payload: Vec<u8>) -> Result<(), momento_functions_wit::function_spawn::momento::functions::types::InvocationError> {
35                $spawn_handler(payload).map_err(Into::into)
36            }
37        }
38    };
39
40    ($post_handler: ident, $request: ident) => {
41        use momento_functions_host::FunctionResult;
42        struct SpawnFunction;
43        momento_functions_wit::function_spawn::export_spawn_function!(SpawnFunction);
44
45        #[automatically_derived]
46        impl momento_functions_wit::function_spawn::exports::momento::functions::guest_function_spawn::Guest for SpawnFunction {
47            fn spawned(payload: Vec<u8>) -> Result<(), momento_functions_wit::function_spawn::momento::functions::types::InvocationError> {
48                let payload: $request = serde_json::from_slice(&payload)
49                    .map_err(|e| momento_functions_wit::function_spawn::momento::functions::types::InvocationError::RequestError(format!("could not deserialize json: {e:?}")))?;
50                $post_handler(payload).map_err(Into::into)
51            }
52        }
53    }
54}