|
| 1 | +# `ic-cdk-executor` |
| 2 | + |
| 3 | +An async executor for [`ic-cdk`](https://docs.rs/ic-cdk). Most users should not use this crate directly. It is useful primarily for those who are writing their own CDK or a runtime host for non-Rust languages. |
| 4 | + |
| 5 | +## Contexts |
| 6 | + |
| 7 | +The expected boilerplate for a canister method or other entrypoint (*not* including callbacks) looks like this: |
| 8 | + |
| 9 | +```rust |
| 10 | +pub extern "C" fn function() { |
| 11 | + in_tracking_executor_context(|| { |
| 12 | + // method goes here |
| 13 | + }); |
| 14 | +} |
| 15 | +``` |
| 16 | + |
| 17 | +The `in_tracking_executor_context` function permits you to call `spawn_*` functions. As little code as possible |
| 18 | +should exist outside the block, because `in_tracking_executor_context` additionally sets up the panic handler. |
| 19 | + |
| 20 | +The above applies to update contexts. Query contexts, including `inspect_message`, should use |
| 21 | +`in_tracking_query_executor_context`. |
| 22 | + |
| 23 | +The expected boilerplate for an inter-canister call callback looks like this: |
| 24 | + |
| 25 | +```rust |
| 26 | +unsafe extern "C" fn callback(env: usize) { |
| 27 | + let method = unpack_env(env); |
| 28 | + in_callback_executor_context_for(method, || { |
| 29 | + // wake the call future |
| 30 | + }); |
| 31 | +} |
| 32 | +unsafe extern "C" fn cleanup(env: usize) { |
| 33 | + let method = unpack_env(env); |
| 34 | + in_trap_recovery_context_for(method, || { |
| 35 | + cancel_all_tasks_attached_to_current_method(); |
| 36 | + }); |
| 37 | +} |
| 38 | +``` |
| 39 | + |
| 40 | +In async contexts, all scheduled tasks are run *after* the closure passed to the context function |
| 41 | +returns, but *before* the context function itself returns. |
| 42 | + |
| 43 | +The `method` parameter must be retrieved *before* making inter-canister calls via the `extend_current_method_context` |
| 44 | +function. Calling this function from the callback instead will trap. |
| 45 | + |
| 46 | +## Protection |
| 47 | + |
| 48 | +Tasks can be either *protected* or *migratory*. Protected tasks are attached to the method that spawned them, |
| 49 | +when awoken will not resume until that method continues, and will be canceled if the method returns before they complete. |
| 50 | +Migratory tasks are not attached to any method, and will resume in whatever method wakes them. |
0 commit comments