Endpoints: Typed Messages, Refusals and Await

Audience task and outcome

  • Task Expose an item lookup to clients, protect an admin method, and call another canister from an update.
  • Observable outcome The viewer can declare a typed endpoint and its message type, choose where an access check goes, return a typed refusal or trap on purpose, and write an awaited call that opens a fresh scope afterward. On PocketIC, roundtrip(peer, 11) returns ok 11 with counters started 1, completed 1, and a trapped update leaves those counters unchanged.
  • Starting point Lesson 3 called services inside one scope. Lesson 4 chose saved types.
  • Handoff Lesson 6 upgrades the canister, which first needs every awaited call to have finished.
  • Pacing Four minutes.

The worked example

The first half stays in the Shop. Its item query returns an api::Item message, and Inventory copies the saved item into that message. The second half uses the Async scope probe, a small canister whose roundtrip(target, value) records a counter, ends its scope, awaits the target's echo method, then records the outcome in a new scope. The lifecycle check calls roundtrip(peer, 11), reads {started: 1, completed: 1, rejected: 0, value: 11}, calls trap_after_increment, and reads the same counters again. Shop message type · Shop endpoints · Async scope probe · Probe endpoints · Lifecycle check

Endpoints use the bounded Wire format. The Wire guide defines message types, limits, calls and the generated client files. Bounded Wire interfaces · Keep endpoint data typed

The story in one pass

Declare a message type and return it from a query. Show that the saved type and the message type are separate. Protect a method with a guard and compare it with a check inside the method. Return a refusal, then trap on purpose and watch the change disappear. Finally make an awaited call and see the scope close before the call leaves and a new one open when the answer arrives.

Views and visual objects

Use the shared visual language. A canister boundary appears in this film because calls now cross it. Draw the client outside at left. The public edge of the canister lists endpoint names. A ReceiptCard is the typed value that crosses back.

The second half adds a second canister boundary labeled peer at right and a Timeline strip under the stage with three segments named frame 1, await and frame 2.

View Framing and anchor
edge Client at left, the Shop's public edge, EditorPane for api.rs or lib.rs above.
two_types Two EditorPane columns for api.rs and inventory/memory/v1.rs with a mapping arrow between them.
probe The probe canister with one Counters ModuleCard, the peer canister at right, EditorPane for the probe's lib.rs above, Timeline below.
check TestPanel with lines from sdk-lifecycle.mjs beside the Counters StateCard.

Scene typed_messages — What crosses the boundary

Enters with The Shop App frame, now inside a canister boundary with its endpoint names on the edge.

Beat message_type — Declare the message

View and focus edge, pane on src/api.rs.

Show src/api.rs lines 1 to 15, then src/lib.rs lines 26 to 29.

#[derive(
    Clone,
    Copy,
    Debug,
    PartialEq,
    Eq,
    cdk_rsx::serde::Serialize,
    cdk_rsx::serde::Deserialize,
    cdk_rsx::WireType,
)]
#[serde(crate = "cdk_rsx::serde")]
pub struct Item {
    pub price: u64,
    pub stock: u32,
}
#[cdk_rsx::query]
fn item(branch: u64, item: u64) -> Option<api::Item> {
    root::read(|app| app.branches().get(branch, item))
}

Narration

Clients receive typed messages. The Shop declares an Item message with a price and a stock. It derives Serialize, Deserialize and Wire Type. The query returns an optional Item, and the build produces a matching client interface from these declarations.

Cue and animation On “an Item message”, band the struct. On “Serialize, Deserialize and Wire Type”, band the three derive lines. On “returns an optional Item”, send item(9, 44) in and return ReceiptCard Some(Item { price: 100, stock: 5 }). On “a matching client interface”, show two small file chips at the client side, shop.wire.json and shop.wire.ts.

Leaves with A typed receipt at the client and two generated file chips.

Beat order_is_contract — Field order is the format

View and focus edge, pane on src/api.rs lines 12 to 15.

Show The two fields, with their types banded.

Narration

Two rules come with a message type. The order of the fields is the message format, so reordering them changes what clients must send and read. And integers have a fixed width, like u sixty-four and u thirty-two. A pointer-sized integer is not allowed in a message.

Cue and animation On “The order of the fields”, number the fields 1 and 2. On “reordering them”, swap the two lines briefly, mark the client chip out of date, then swap back. On “a fixed width”, band u64 and u32. On “not allowed”, show usize struck through.

Hold or transition Hold after the swap back. Balloon reads change a message, rebuild and redeploy its clients together.

Leaves with Numbered fields and an up-to-date client chip.

Beat saved_is_separate — The saved type stays inside

View and focus two_types.

Show Left, src/api.rs lines 12 to 15. Right, src/inventory/memory/v1.rs lines 5 to 8. Below, src/inventory/mod.rs lines 8 to 18.

    pub fn get(&self, item: u64) -> Result<Option<crate::api::Item>> {
        Ok(self
            .memory
            .read()?
            .items
            .get(&item)
            .map(|saved| crate::api::Item {
                price: saved.price,
                stock: saved.stock,
            }))
    }

Narration

The Shop has two Item types on purpose. One is the message. The other is the saved item inside Inventory. The service copies fields from the saved one into the message. Each can now change on its own schedule.

Cue and animation On “One is the message”, tag the left pane message. On “the saved item”, tag the right pane saved. On “copies fields”, band the map closure and draw two arrows, price → price and stock → stock.

Leaves with Two tagged types joined by a copy.

Scene access_and_refusal — Who may call and what comes back

Enters with The Shop's public edge.

Beat guard — Check the caller before the body

View and focus edge, pane on src/lib.rs.

Show tests/canisters/shop/src/lib.rs lines 34 to 37. Then benches/rrt/canister/src/lib.rs lines 115 to 124, RRT Heavy16's add_peer.

#[cdk_rsx::update(guard=cdk_rsx::guards::controller)]
fn set_tax(basis_points: u32) -> bool {
    root::with(|app| app.settings().set_tax(basis_points))
}
#[cdk_rsx::update(name = "addPeer")]
fn add_peer(peer: Principal) -> bool {
    root::with(|app| {
        if cdk_rsx::api::msg_caller() != app.select().owner()? || peer == Principal::anonymous() {
            return Ok(false);
        }
        app.reactor().add_peer(peer, cdk_rsx::api::time())?;
        Ok(true)
    })
}

Narration

Access checks have two homes. A guard on the attribute runs before the arguments are decoded, and the SDK ships one for controllers. When the rule depends on saved data, the check goes inside the method. This endpoint from a larger app compares the caller with a saved owner and answers false.

Cue and animation On “A guard on the attribute”, band guard=cdk_rsx::guards::controller and draw a small gate on the public edge at set_tax. On “before the arguments are decoded”, stop a pill from a non-controller at the gate. On “depends on saved data”, switch the pane to add_peer and band the if. On “answers false”, return a neutral ReceiptCard false.

Leaves with One gate on the edge and one in-method check.

Beat refuse_or_trap — A refusal returns, a trap undoes

View and focus probe, without the peer yet. Pane on the probe's lib.rs.

Show tests/canisters/async-probe/src/lib.rs lines 71 to 75, then sdk-lifecycle.mjs lines 83 and 84.

#[cdk_rsx::update]
fn trap_after_increment() {
    root::with(|app| app.counters().increment());
    cdk_rsx::trap("intentional rollback of Nyxus counter");
}
  await assert.rejects(()=>async.actor.trap_after_increment(),/intentional/);
  assert.deepEqual(await async.actor.stats(),before);

Narration

For an expected refusal, return false, None or an error before making any changes. This synchronous test method changes a counter and then traps. The Internet Computer rolls back that message's writes, so the counter is back where it was.

Cue and animation On “return false, None or an error”, show the false and None receipts from earlier films in a row. On “changes a counter”, change value 11 to value 12 in green on the Counters StateCard. On “then traps”, band cdk_rsx::trap and stamp the call trapped. On “back where it was”, restore value 11 and pass both check lines in a TestPanel.

Hold or transition Hold on the restored value. Balloon reads Returned refusal keeps earlier writes. Trap rolls back this message.

Leaves with The Counters card at started 1 · completed 1 · rejected 0 · value 11.

Scene await_call — Call another canister

Enters with The probe canister and its Counters card. The peer canister slides in at right.

Beat frame_one — Record, then let the scope end

View and focus probe with the Timeline.

Show tests/canisters/async-probe/src/lib.rs lines 50 to 53.

#[cdk_rsx::update]
async fn roundtrip(target: cdk_rsx::Principal, value: u64) -> Result<u64, String> {
    root::with(|app| app.counters().begin(value));
    // The entire root frame has ended. No view or retained borrow crosses await.

Narration

Roundtrip is an async update. It first records that a call has started. That write happens inside root with, and the scope ends on the same line. Nothing borrowed from the app is still held.

Cue and animation On “an async update”, band async fn. On “records that a call has started”, open a write outline, change started in green, and fill the frame 1 segment of the Timeline. On “the scope ends”, close the outline at the end of line 52. On “Nothing borrowed”, band the comment on line 53.

Leaves with A closed scope and frame 1 complete.

Beat the_await — Only owned values cross

View and focus probe, both canisters in frame.

Show Lines 54 to 62.

    let answer = match cdk_rsx::call::Call::bounded_wait(target, "echo")
        .with_arg(value)
        .await
    {
        Ok(response) => response
            .wire::<u64>()
            .map_err(|error| format!("reply: {error}")),
        Err(error) => Err(format!("call: {error}")),
    };

Narration

Now the call leaves. With arg encodes the value as a typed message, and await suspends this method until the peer replies. Other calls can run in the meantime. The reply is decoded into a u sixty-four. A failed call or a bad reply becomes an error value that the method owns.

Cue and animation On “the call leaves”, send a dashed arrow with a clock carrying echo(11) to the peer and fill the await segment. On “Other calls can run”, let a small unrelated stats() query pass through the probe and return. On “The reply is decoded”, bring 11 back and band .wire::<u64>(). On “becomes an error value”, band both Err arms.

Hold or transition Hold while the dashed arrow is out. Balloon on .await reads no scope, view or borrowed value may be held across this line. The conventions and the status page state this rule. Resume on “The reply is decoded”.

Leaves with The answer Ok(11) held by the method as a plain value.

Beat frame_two — Open a fresh scope

View and focus probe with the Timeline.

Show Lines 63 to 66.

    // This continuation opens a fresh frame after callback entry.
    root::with(|app| app.counters().complete(answer.is_err()));
    answer
}

Narration

After the reply, the method asks for write access again. This is a new scope. Whatever the first one read may have changed while the call was out, so the code reads again if it needs to. It records the outcome and returns the answer.

Cue and animation On “write access again”, open a second write outline and fill frame 2. On “may have changed”, pulse the Counters StateCard. On “records the outcome”, change completed in green. On “returns the answer”, return ReceiptCard Ok(11) to the client.

Leaves with A three-part Timeline and counters started 1 · completed 1 · rejected 0 · value 11.

Beat checked — What the tests cover

View and focus check.

Show sdk-lifecycle.mjs lines 80 to 82, and tests/canisters/async-probe/src/tests.rs lines 7 to 9.

  assert.deepEqual(await async.actor.roundtrip(peer.id,11n),{ok:11n});
  const before=await async.actor.stats();
  assert.deepEqual(before,{started:1n,completed:1n,rejected:0n,value:11n});
    app.with(|view| view.counters().begin(19)).unwrap();
    // Model the suspension boundary by ending the first frame completely.
    app.with(|view| view.counters().complete(false)).unwrap();

Narration

A native test can model the two scopes as two separate calls. The real suspension, the real peer and the trap are checked on PocketIC, where roundtrip returns eleven and the counters match.

Cue and animation On “two separate calls”, band the two app.with lines. On “checked on PocketIC”, pass the three JavaScript assertions. On “the counters match”, pulse the StateCard.

Leaves with Two passed panels. The next film needs every such call to have finished before it upgrades.

Try it

Verify Run the probe's native test, then the example lifecycle task if PocketIC is set up. Testing

source tools/env.sh
cargo test --manifest-path tests/Cargo.toml --locked --offline -p async-probe-canister
python3 tools/test.py run --task 'integration:examples' --cargo-home tmp/dependencies

Expected app-level result. fresh_frames_record_success_rejection_and_service_rebind passes natively. The integration task prints async native callback, update-trap rollback and drained KEEP retain counters and permit fresh calls.

Change, adapted exercise Return a typed receipt from the Shop's checkout. Add a message Receipt { branch: u64, item: u64, units: u32, total: u64 } to api.rs with the same derives as Item, and change the checkout endpoint to return Option<api::Receipt> built from its arguments and the total. Expected result on the lifecycle data is checkout(10, 20, 2) returning {branch: 10, item: 20, units: 2, total: 250}. This type is not in the checkout. It changes a public message, so the generated client files change with it and the existing lifecycle assertion for checkout needs the new shape.

Source and review notes

Item shown Status
#[cdk_rsx::update], #[cdk_rsx::query], guard = …, name = …, cdk_rsx::WireType, cdk_rsx::trap Shipped SDK API. Wire guide
cdk_rsx::call::Call::bounded_wait, with_arg, Response::wire Shipped SDK API. Calls, clients, and artifacts
#[cdk_rsx::dto] Shipped shorthand for the three derives. The examples write the derives out.
Generated .wire.json and .wire.ts Produced by the canonical builder. No .did file is generated. Building
trap_after_increment, yielding_query, yielding_composite_query Probe-only test methods. Show only trap_after_increment.
RRT Heavy16 add_peer Application code in a benchmark app, shown for its in-method owner check.
  • Limits are worth one sentence only if the edit has room. Endpoints accept up to the SDK default of 2 MiB of encoded input, and request_limits or response_limits on the attribute change that. The guide asks authors to test the largest valid request against the real limits. Limits and owned values
  • A reply that is too large or cannot be decoded does not prove the peer did nothing. The Wire guide calls this an uncertain successful execution. The probe counts it as rejected and does not retry. Lesson 9 returns to this with a workflow that keeps the outcome unknown.
  • Do not explain how suspension or callbacks are implemented. “Suspends this method until the peer replies” is the full description.
  • guards::controller is documented in its source as running before argument decoding. Guards
  • The film says “scope” throughout. The probe's comments say “frame”. The Timeline labels use the comments' word so the on-screen source and the label agree.