Shop: Compose Services in One Call

Audience task and outcome

  • Task Sell items from a branch's inventory and charge the configured tax.
  • Observable outcome The viewer can write a service that has no data of its own and calls other modules through their public methods. They can manage one child module per business key, and they can order a method so every refusal comes before the first change. checkout(9, 44, 3) returns Some(315) and leaves stock 5. A request for 6 returns None and leaves stock 5.
  • Starting point Lesson 2 added Settings and bound it in the root.
  • Handoff Lesson 4 looks inside Inventory's data declaration and asks how to choose its collection.
  • Pacing Four minutes. The checkout call is the centre of the film.

The worked example

The Shop root owns Settings and Branches. Branches owns one Inventory module per open branch. Checkout is a service with no saved data. The Shop test opens branch 9, puts item 44 at price 100 with stock 8, and sets tax 500 basis points. buy(9, 44, 3) gets a subtotal of 300, applies tax to get 315, sells three units and returns Some(315). Stock is 5. buy(9, 44, 6) returns None. After the app is reopened, closing branch 9 and opening it again gives an empty inventory. Shop · Checkout · Branches · Inventory · Shop test

The conventions describe the same rules. Composition services declare their dependencies as #[service] fields, public business methods take domain arguments, and expected refusals come before any saved change. Bind services once, borrow access per call · Authoring obligations

The story in one pass

Show the Shop's module cards and who owns whom. Open a branch, which creates an Inventory module under a key. Declare Checkout with two dependencies and wire it in the root. Follow one checkout call as it asks for a quote, reads the tax, and sells. Send a larger order and watch it stop at the quote. Close the branch and see its inventory go with it.

Views and visual objects

Use the shared visual language and the Shop AppTree from lesson 2. Inside the App frame, draw ModuleCards for Branches, Settings and Checkout. Checkout has no drawer. Branches' drawer holds a keyed rack labeled items, and each occupied rack position holds a complete Inventory ModuleCard with its own drawer. Inventory's StateCard rows read item 44 · price 100 · stock 8.

Method names on a card's edge appear in two weights. Public methods are solid. Crate-internal methods such as quote and sell are outlined and are reachable only from other Shop modules.

View Framing and anchor
shop_app The App frame with Branches, Settings and Checkout. Anchor on Checkout for requests.
branch_rack Branches' items rack with the Inventory card for key 9 at readable size.
checkout_code EditorPane for checkout.rs at left, shop_app at right.
inventory_code EditorPane for inventory/mod.rs at left, branch_rack at right.
test TestPanel with src/tests.rs and shop_app.

Scene shop_modules — Who owns what

Enters with The Shop App frame from lesson 2 with Settings attached and tax 500.

Beat open_branch — A module per branch

View and focus branch_rack, with an EditorPane on branches/mod.rs.

Show src/branches/memory/v1.rs line 3, then src/branches/mod.rs lines 33 to 46. Point at the two refusal conditions, then at attach.

 pub struct Children {pub(in crate::branches) items:cdk_rsx_store::ChildMap<u64,crate::inventory::memory::v1::Memory>}
    pub fn open(&self, branch: u64) -> Result<bool> {
        let children = self.memory.children()?;
        if children.items.reference(self.access(), &branch)?.is_some()
            || children.items.len() >= MAX_BRANCHES
        {
            return Ok(false);
        }
        children.items.attach(
            self.access(),
            branch,
            crate::inventory::memory::new(self.access())?,
        )?;
        Ok(true)
    }

Narration

Branches keeps no fields of its own. It keeps a map of child modules, one inventory per branch number. Opening branch nine checks that the branch is new and that the Shop has fewer than thirty-two. Then it creates an inventory and attaches it under key nine.

Cue and animation On “a map of child modules”, band the ChildMap line and reveal the empty items rack. On “checks that the branch is new”, band the if. On “fewer than thirty-two”, band MAX_BRANCHES. On “attaches it under key nine”, seat a new Inventory card in rack position 9.

Leaves with One Inventory card at items[9] with an empty table.

Beat stock_item — The parent forwards, the child stores

View and focus inventory_code.

Show src/branches/mod.rs lines 55 to 60, then src/inventory/mod.rs lines 30 to 37.

    pub fn put(&self, branch: u64, item: u64, price: u64, stock: u32) -> Result<bool> {
        match self.inventory(branch)? {
            Some(inventory) => inventory.view(self.access()).put(item, price, stock),
            None => Ok(false),
        }
    }
    pub fn put(&self, item: u64, price: u64, stock: u32) -> Result<bool> {
        let mut data = self.memory.write()?;
        if !data.items.contains_key(&item) && data.items.len() >= MAX_ITEMS {
            return Ok(false);
        }
        data.items.insert(item, Mem::Item { price, stock });
        Ok(true)
    }

Narration

To stock an item, Branches finds the inventory for that branch and calls its put method. Branches cannot see inside the inventory's data. Inventory checks its own limit and saves item forty-four at price one hundred with eight in stock.

Cue and animation On “finds the inventory”, pulse rack position 9. On “calls its put method”, move put(44, 100, 8) from Branches into the Inventory card. On “cannot see inside”, keep Branches' side of the Inventory drawer closed while Inventory's own method opens it. On “saves item forty-four”, add the row 44 · price 100 · stock 8.

Leaves with Item 44 at price 100, stock 8, and tax 500.

Scene declare_checkout — A service made of other services

Enters with The stocked Shop.

Beat checkout_fields — Dependencies are fields

View and focus checkout_code.

Show src/checkout.rs lines 12 to 18, then src/root/mod.rs lines 55 to 58.

#[cdk_rsx::service(view = View)]
pub struct Checkout {
    #[service]
    branches: std::rc::Rc<branches::Branches>,
    #[service]
    settings: std::rc::Rc<settings::Settings>,
}
        let branches = Rc::new(branches);
        let settings = Rc::new(settings);
        let checkout = crate::checkout::Checkout::new(branches.clone(), settings.clone());
        Ok(Self::new(actor, branches, settings, checkout))

Narration

Checkout saves nothing, so it has no memory folder. Its service lists the two services it depends on. The root builds Branches and Settings once and hands the same two to Checkout.

Cue and animation On “no memory folder”, show checkout.rs as a single file in the tree and the Checkout card without a drawer. On “the two services it depends on”, band the two fields and draw thin dependency lines from Checkout to Branches and to Settings. On “hands the same two”, band Checkout::new(branches.clone(), settings.clone()).

Leaves with Checkout connected to Branches and Settings.

Scene one_checkout — Follow the sale

Enters with The wired Shop, stock 8, tax 500.

Beat enter_checkout — One endpoint, one scope

View and focus shop_app, with src/lib.rs in a small EditorPane.

Show src/lib.rs lines 30 to 33.

#[cdk_rsx::update]
fn checkout(branch: u64, item: u64, units: u32) -> Option<u64> {
    root::with(|app| app.checkout().buy(branch, item, units))
}

Narration

A customer checks out three units of item forty-four from branch nine. The endpoint opens one write scope and calls buy. Everything that follows happens inside that one scope.

Cue and animation On “A customer checks out”, bring the pill checkout(9, 44, 3) in. On “one write scope”, draw a write outline around the whole App frame. On “calls buy”, move buy(9, 44, 3) to Checkout.

Leaves with An open scope and the request at Checkout.

Beat quote — Ask before changing anything

View and focus checkout_code, then follow the call into inventory_code.

Show src/checkout.rs lines 20 to 23, then src/inventory/mod.rs lines 19 to 27.

    pub fn buy(&self, branch: u64, item: u64, units: u32) -> Result<Option<u64>> {
        let Some(subtotal) = self.branches().quote(branch, item, units)? else {
            return Ok(None);
        };
    pub fn quote(&self, item: u64, units: u32) -> Result<Option<u64>> {
        Ok(self
            .memory
            .read()?
            .items
            .get(&item)
            .filter(|saved| units > 0 && units <= saved.stock)
            .and_then(|saved| saved.price.checked_mul(u64::from(units))))
    }

Narration

Buy first asks Branches for a quote. Branches passes the question to the inventory for branch nine. Quote only reads. Eight are in stock, so three at one hundred gives three hundred.

Cue and animation On “asks Branches for a quote”, band self.branches().quote and move quote(9, 44, 3) to Branches, then into Inventory 9. On “only reads”, band .read() and tint the row without changing it. On “Eight are in stock”, band the filter line. On “gives three hundred”, return Some(300) to Checkout.

Leaves with Checkout holding 300. Stock still 8.

Beat tax — Read a second module

View and focus checkout_code.

Show src/checkout.rs lines 24 to 29.

        let Some(taxed) = u128::from(subtotal)
            .checked_mul(10_000 + u128::from(self.settings().tax()?))
            .and_then(|value| u64::try_from(value / 10_000).ok())
        else {
            return Ok(None);
        };

Narration

Next it reads the tax from Settings, which is five hundred basis points. The arithmetic is checked. A total that does not fit returns None. Here the total is three hundred and fifteen.

Cue and animation On “reads the tax from Settings”, band self.settings().tax() and move tax() to Settings and back with 500. On “The arithmetic is checked”, band checked_mul and try_from. On “three hundred and fifteen”, show 315 at Checkout.

Leaves with Checkout holding 315. Nothing has been written.

Beat sell — The only write

View and focus inventory_code.

Show src/checkout.rs lines 30 to 33, then src/inventory/mod.rs lines 38 to 48.

        if !self.branches().sell(branch, item, units)? {
            return Ok(None);
        }
        Ok(Some(taxed))
    pub(crate) fn sell(&self, item: u64, units: u32) -> Result<bool> {
        let mut data = self.memory.write()?;
        let Some(saved) = data.items.get_mut(&item) else {
            return Ok(false);
        };
        if units == 0 || units > saved.stock {
            return Ok(false);
        }
        saved.stock -= units;
        Ok(true)
    }

Narration

Only now does checkout ask for the sale. Inventory checks the quantity once more and takes three from stock. Five remain. Checkout returns three hundred and fifteen and the scope closes.

Cue and animation On “ask for the sale”, move sell(9, 44, 3) through Branches into Inventory 9. On “checks the quantity once more”, band the if. On “takes three from stock”, send a red −3 up from stock and change 8 to 5. On “returns three hundred and fifteen”, return ReceiptCard Some(315) to the client and close the write outline.

Hold or transition Hold after the stock changes. Balloon on pub(crate) fn sell reads callable inside the Shop crate only. The outlined sell and quote names on the Inventory and Branches cards pulse. Resume on “Checkout returns”.

Leaves with Stock 5 and a receipt of Some(315).

Beat refuse_order — A refusal before any change

View and focus shop_app, then test.

Show src/tests.rs lines 25 to 28.

    assert_eq!(
        app.with(|view| view.checkout().buy(9, 44, 6)).unwrap(),
        None
    );

Narration

The test then asks for six. Five are left, so the quote comes back empty and buy returns None before it reads tax or sells. This order matters. A returned refusal does not undo a write that already happened, so the checks come first.

Cue and animation On “asks for six”, send checkout(9, 44, 6) down the quote path. On “comes back empty”, return None from Inventory through Branches to Checkout. On “returns None”, return a neutral ReceiptCard None and close the scope. Keep stock 5 steady. On “the checks come first”, show the three steps of buy as a strip quote · tax · sell with a bracket labeled no changes over the first two.

Hold or transition Hold on the strip through the last two sentences. Balloon reads refuse first, change last.

Leaves with Stock 5, two receipts, and the quote · tax · sell strip.

Scene close_branch — A child's lifetime belongs to its parent

Enters with The Shop after two checkouts.

Beat close_and_reopen — Closing removes the inventory

View and focus branch_rack, with TestPanel for the last lines of the first test.

Show src/branches/mod.rs lines 47 to 54, then src/tests.rs lines 33 to 35.

    pub fn close(&self, branch: u64) -> Result<bool> {
        Ok(self
            .memory
            .children()?
            .items
            .take(self.access(), &branch)?
            .is_some())
    }
    assert!(app.with(|view| view.branches().close(9)).unwrap());
    assert!(app.with(|view| view.branches().open(9)).unwrap());
    assert_eq!(app.read(|view| view.branches().get(9, 44)).unwrap(), None);

Narration

Closing a branch takes its inventory out of the map. Nothing attaches it anywhere else, so it is gone when the scope ends. Opening branch nine again creates a new, empty inventory. Item forty-four is no longer there.

Cue and animation On “takes its inventory out”, lift the Inventory card from rack position 9 as a ticket. On “gone when the scope ends”, fade the ticket at the scope's closing edge. On “a new, empty inventory”, seat a fresh empty Inventory card at position 9. On “no longer there”, pass the None assertion.

Leaves with A new empty Inventory at items[9]. The next film looks at how Inventory declares its item table.

Try it

Verify Run the Shop tests as in lesson 2 and read admission_and_overflow_reject_before_changing_stock. It opens thirty-two branches and sees the thirty-third refused. It stocks one unit at price u64::MAX with tax 10_000, and asserts that buy(0, 1, 1) returns None with stock still 1. Expected app-level result is that both Shop tests pass. Shop test

Change, adapted exercise Add a price preview that sells nothing. In checkout.rs, add preview(branch, item, units) in a new impl<A: Access> View<'_, A> block that runs the quote and tax steps and returns the taxed total. Add a #[cdk_rsx::query] endpoint that calls it through root::read. Expected result with the test data is preview(9, 44, 3) == Some(315) while stock stays 8. The method is not in the checkout. The documentation test at the top of checkout.rs shows that view.settings().tax() is available under any access. Checkout

Source and review notes

Item shown Status
#[service] dependency fields, generated self.branches() and self.settings() accessors, generated Checkout::new Shipped SDK API. Service attribute
ChildMap with attach, take, reference, keys, len Shipped SDK API. Account for child ownership
MAX_BRANCHES, MAX_ITEMS, Branches::inventory Shop's own constants and helper. The limits are the app's decision.
quote, sell as pub(crate) Shop's own interface choice.
  • The conventions state the failure rule this film relies on. A returned error or refusal does not roll a write scope back, and a failure after a change must trap when rollback is required. The film shows only the first half, through refuse_order. Lesson 5 shows the trap.
  • The memory series film 2 animates this same checkout at the storage level. This film must not borrow its memory cells, guards or key badges. Use module cards, drawers and call pills.
  • Check the arithmetic on screen. 300 × (10_000 + 500) / 10_000 = 315.
  • Branches binds an Inventory service for each call through its private inventory helper. The film shows this as “finds the inventory”. Do not add a binding animation.