Shop: Add a Module That Owns Its Data

Audience task and outcome

  • Task Give the Shop a tax rate that an admin can set and anyone can read.
  • Observable outcome The viewer can add a stateful feature module in six small edits. They declare its versioned data, give it a constructor and a service, attach it to the app, bind it at install and at restore, and expose it. In the Shop test, a tax of 500 is still 500 after the app is dropped and opened again.
  • Starting point Lesson 1 showed the finished shape of a module. This film builds one.
  • Handoff Lesson 3 lets Checkout use Settings together with the Shop's inventory.
  • Pacing Four minutes. Each edit gets its own beat.

The worked example

The Shop is a larger app with the same layout as Quickstart. Its Settings module saves one number, the tax in basis points. The film presents the module's real files in the order an author would write them, as if the Shop were gaining the feature today. The Shop test sets the tax to 500, drops the app, opens it on the same Store and reads 500. A second test shows set_tax(10_001) returning false and set_tax(10_000) returning true. Shop · Settings service · Settings data V1 · Shop root · Shop test

The steps follow the documented conventions for owner folders, records, services and the root. Application memory conventions

The Shop in the checkout already contains Settings from its first install. Adding a child to the root of an app that is already deployed changes the root's saved contract. That case needs the data revision steps in lesson 7.

The story in one pass

Start with an empty settings/ folder in the Shop's tree. Write the data declaration, select it as the current version, and add a constructor. Write the service with one read method and one write method that refuses a bad rate. Give the root a slot for the new module, create and attach it at install, and bind the service where the app starts. Add two endpoints. Finish with the test that reopens the app.

Views and visual objects

Use the shared visual language. The Shop's AppTree shows lib.rs, api.rs, checkout.rs, branches/, inventory/, root/ and settings/. Keep these positions for lessons 3, 5 and 6. Settings gets a ModuleCard with tax and set_tax on its edge and a StateCard holding tax. The App frame holds ModuleCard positions for Branches, Settings and Checkout. Only Settings is in focus in this film, and the others are dimmed outlines.

A small slot socket on the inside of the App frame marks where a module is attached. A socket holds exactly one module of one named version.

View Framing and anchor
shop_tree The Shop AppTree with the settings/ folder empty.
settings_files Two EditorPane columns for files under settings/, with the Settings card beneath.
root_files Two EditorPane columns for root/memory/v1.rs and root/mod.rs, with the App frame beneath.
shop_app The App frame with its three module positions and the Settings card attached.
test TestPanel with src/tests.rs and the Settings card.

Scene declare_data — Say what the module saves

Enters with The empty folder outline from lesson 1, now named settings/ inside the Shop tree.

Beat request — One number, owned by one module

View and focus shop_tree. Focus on the empty settings/ folder.

Show The Shop src listing. Point at settings/.

Narration

The Shop needs a tax rate. An admin sets it and checkout will read it. That is one saved number, and it gets a module of its own called Settings.

Cue and animation On “a tax rate”, show the request as a small note tax rate, admin sets, anyone reads. On “a module of its own”, draw an empty Settings ModuleCard outline beside the folder.

Leaves with An empty folder and an empty card outline.

Beat write_v1 — The data declaration

View and focus settings_files, left pane on settings/memory/v1.rs.

Show The whole file, lines 2 to 10. Point at the tax field, then at owner = crate::settings.

use cdk_rsx_collections::nyxus::NyxusData;
#[repr(C)]
#[derive(NyxusData)]
pub struct Data {
    pub(in crate::settings) tax: u32,
}

#[cdk_rsx_store::memory(owner = crate::settings)]
pub struct Memory;

Narration

The first file is memory, v one. Data lists what the module saves, here a single tax field that only Settings code can see. The memory attribute names the owner. Other modules will refer to Memory, and never to the fields.

Cue and animation On “memory, v one”, slide v1.rs into the tree under settings/memory/. On “a single tax field”, band line 6 and open the card's drawer with a tax row showing no value yet. On “names the owner”, band the attribute. On “refer to Memory”, pulse pub struct Memory.

Hold or transition Hold after “names the owner”. Balloon on owner = crate::settings reads this file is Settings' saved-data contract, version 1. Resume on “Other modules”.

Leaves with v1.rs in the tree and a drawer with one empty row, badged v1.

Beat select_current — Pick the current version and a constructor

View and focus settings_files, right pane on settings/memory/mod.rs.

Show The whole file, lines 1 to 6.

pub mod v1;
use cdk_rsx_store::{Detached, Result, Scope};
pub use v1 as current;
pub(crate) fn new<'s>(scope: &Scope<'s>) -> Result<Detached<'s, current::Memory>> {
    scope.create(&current::KEY, current::Data { tax: 0 })
}

Narration

Beside it, the selector says which version the service uses today. The module also gets a constructor. It creates fresh Settings data with a tax of zero and returns it as a ticket for the parent to attach.

Cue and animation On “which version”, band pub use v1 as current. On “a constructor”, band fn new. On “a tax of zero”, set the drawer row to tax 0. On “a ticket”, lift a small ticket shape labeled Settings out of the pane and park it above the card.

Leaves with A parked Settings ticket and tax 0 in the drawer preview.

Scene write_service — Give the module its methods

Enters with Both memory files in the tree.

Beat service_methods — Read freely, write with a check

View and focus settings_files, left pane switches to settings/mod.rs.

Show The whole file, lines 1 to 19. Point at the attribute, then tax, then the check in set_tax.

#[cdk_rsx::service(memory = Mem, view = View)]
pub struct Settings;
impl<A: Access> View<'_, A> {
    pub fn tax(&self) -> Result<u32> {
        Ok(self.memory.read()?.tax)
    }
}
impl View<'_, Scope<'_>> {
    pub fn set_tax(&self, basis_points: u32) -> Result<bool> {
        if basis_points > 10_000 {
            return Ok(false);
        }
        self.memory.write()?.tax = basis_points;
        Ok(true)
    }
}

Narration

The service is declared in mod dot r s. The service attribute connects it to the current memory version. Tax is a read method. Set tax needs a write scope. It refuses a rate above ten thousand before it touches the data, and only then writes.

Cue and animation On “The service attribute”, band lines 4 and 5 of the file and put the name Settings on the card. On “a read method”, add tax to the card's read group. On “needs a write scope”, add set_tax to its write group. On “refuses a rate”, band the if and show a neutral ReceiptCard false leaving with the drawer closed. On “only then writes”, band the assignment.

Leaves with A complete Settings card that is not attached to the App yet.

Scene attach_and_bind — Make it part of the app

Enters with The finished Settings card floating outside the App frame, with its ticket above it.

Beat root_slot — The root names its children

View and focus root_files, left pane on root/memory/v1.rs.

Show Lines 2 to 10. Point at the settings line.

cdk_rsx_store::module_children! {
 pub struct Children{
  pub(in crate::root) branches:cdk_rsx_store::ChildSlot<crate::branches::memory::v1::Memory>,
  pub(in crate::root) settings:cdk_rsx_store::ChildSlot<crate::settings::memory::v1::Memory>,
 }
}

#[cdk_rsx_store::memory(owner = crate::root, data = (), children = Children)]
pub struct Memory;

Narration

The root has a memory file too. It saves no fields of its own. It lists the modules attached to it, one slot each. The settings slot names Settings memory, version one, exactly.

Cue and animation On “lists the modules”, show two sockets inside the App frame. On “The settings slot”, band line 5 and label the second socket settings · v1.

Hold or transition Hold on “exactly”. Balloon on settings::memory::v1::Memory reads a parent pins the child's exact version. Resume into the next beat.

Leaves with An empty settings · v1 socket in the App frame.

Beat attach_on_install — Create and attach in one scope

View and focus root_files, right pane on root/mod.rs.

Show Lines 19 to 33, the install function. Point at the settings attach call.

        let actor = store.install(&Mem::KEY, |scope| {
            let root = scope.create(&Mem::KEY, ())?;
            let children = root.reference().children(scope, &Mem::KEY)?;
            children
                .branches
                .attach(scope, branches::memory::new(scope)?)?;
            children
                .settings
                .attach(scope, settings::memory::new(scope)?)?;
            drop(children);
            Ok(root)
        })?;

Narration

Install runs once, when the canister is first installed. It creates the root, calls each module's constructor, and attaches the result to its slot. Creating and attaching happen in the same scope. A ticket that is never attached is discarded when the scope ends.

Cue and animation On “creates the root”, band scope.create. On “calls each module's constructor”, band settings::memory::new(scope)?. On “attaches the result”, move the Settings ticket into the settings · v1 socket and seat the Settings drawer there. On “never attached”, show a ghost ticket fading at the scope's closing edge.

Leaves with Settings data attached to the App with tax 0.

Beat bind_service — Build the service from the slot

View and focus root_files, right pane scrolled to bind.

Show Lines 47 to 58 of root/mod.rs, then lines 8 to 17, the App struct. Point at Settings::bind, then at the settings field.

                settings::Settings::bind(
                    children
                        .settings
                        .reference(scope)?
                        .ok_or(Error::NotInstalled)?,
                ),
#[cdk_rsx::service(actor = actor)]
pub(crate) struct App {
    actor: Actor<Mem::Memory>,
    #[service]
    branches: Rc<branches::Branches>,
    #[service]
    settings: Rc<settings::Settings>,
    #[service]
    checkout: crate::checkout::Checkout,
}

Narration

Data alone is not callable. Bind looks up the settings slot and builds the Settings service from it. The App keeps that service in a field marked service, which gives endpoints the call app dot settings.

Cue and animation On “looks up the settings slot”, band children.settings.reference(scope). On “builds the Settings service”, attach the card's method edge to the seated drawer. On “a field marked service”, band the settings field and draw the accessor label app.settings() on the App frame.

Leaves with A complete, attached Settings card reachable as app.settings().

Beat install_and_restore — Two ways in, one bind

View and focus root_files, right pane on the bottom of root/mod.rs.

Show Line 2, the root attribute, then lines 61 to 76, install and reopen.

#[cdk_rsx::root(state = App, init = install, restore = reopen)]
pub mod memory;
fn reopen() -> Result<()> {
    #[cfg(target_family = "wasm")]
    {
        // SAFETY: canonical startup admitted every source module before opening memory.
        let store = unsafe { Store::reopen() }?;
        save(App::open(&store)?);
        Ok(())
    }

Narration

The root attribute names two startup callbacks. Init runs on first install and ends by binding the services. Restore runs after an upgrade. It opens the saved data and binds the services again. Services are rebuilt every time the program starts. Only the data is kept.

Cue and animation On “two startup callbacks”, band init = install and restore = reopen. On “first install”, draw a path install → App::install → bind. On “after an upgrade”, draw a second path reopen → App::open → bind that joins the first at bind. On “rebuilt every time”, flash the method edge of the Settings card while the drawer stays still.

Hold or transition Hold on the unsafe line. Balloon reads call Store::reopen only inside this restore callback. The conventions state this requirement. Resume on “Services are rebuilt”.

Leaves with Two labeled startup paths meeting at bind.

Scene expose_and_test — Call it and check it

Enters with The attached Settings card.

Beat endpoints — Two public methods

View and focus shop_app with an EditorPane for src/lib.rs at left.

Show src/lib.rs lines 34 to 41.

#[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::query]
fn tax() -> u32 {
    root::read(|app| app.settings().tax())
}

Narration

Two endpoints finish the feature. Set tax is an update that only a controller may call. Tax is a query for anyone. Setting five hundred returns true, and the saved tax is five hundred.

Cue and animation On “only a controller”, band the guard. On “Setting five hundred”, send set_tax(500) through a write scope and change tax 0 to tax 500 in green. On “returns true”, return ReceiptCard true.

Leaves with tax 500.

Beat reopen_test — The value survives a rebuild

View and focus test.

Show src/tests.rs lines 10, 29 to 31, and from the second test lines 46 and 47.

        assert!(view.settings().set_tax(500)?);
    drop(app);
    let app = App::open(&store).unwrap();
    assert_eq!(app.read(|view| view.settings().tax()).unwrap(), 500);
        assert!(!view.settings().set_tax(10_001)?);
        assert!(view.settings().set_tax(10_000)?);

Narration

The Shop test checks both paths. It sets the tax, drops the app, opens it again, and reads five hundred. A second test confirms that ten thousand and one is refused and ten thousand is accepted.

Cue and animation On “drops the app”, fade the App frame and method edges while the drawer keeps tax 500. On “opens it again”, redraw them through the App::open → bind path. On “reads five hundred”, pass the assertion. On “is refused”, show false with no change. On “is accepted”, show tax 10000 in the second test's own panel.

Leaves with A passed TestPanel and the Shop App frame with Settings in place, ready for Checkout.

Try it

Verify Run the Shop tests from the newstack root. Testing

source tools/env.sh
cargo test --manifest-path tests/Cargo.toml --locked --offline -p shop-canister

Expected app-level result. nested_modules_rebind_and_checkout_uses_one_scope and admission_and_overflow_reject_before_changing_stock pass.

Change, adapted exercise Add your own native test beside them. Install the app, call set_tax(750), drop the app, open it on the same Store and assert that tax() returns 750. Then assert that set_tax(20_000) returns false and tax() still returns 750. This test is not in the checkout. It mirrors the PocketIC check, which sets 750 before a real upgrade and reads 750 after it. Lifecycle check

Source and review notes

Item shown Status
#[cdk_rsx_store::memory(owner = …)], module_children!, ChildSlot, Detached, Scope::create Shipped SDK API. Declare the record · Account for child ownership
#[cdk_rsx::root(state = App, init, restore)], generated save, Store::initialize, Store::reopen, Store::install, Store::open Shipped SDK API. Keep the root declarative
settings::memory::new, App::install, App::open, App::bind Written by the app. The names are a convention, and the conventions guide calls the constructor create in its own sample.
  • The conventions also offer module_memory!, which declares the root memory and its single-child slots in one block. The Shop uses module_children! with the memory attribute. Show the Shop's form.
  • The versions belong to each owner. A later root version may keep attaching Settings v1. Say this once, in root_slot, through the balloon.
  • Mem::KEY appears in the excerpts. If a viewer asks, it is the owner's key for its own memory, and the declaration keeps it private to the owner. Do not explain how it works.
  • Keep #[repr(C)] in frame as written and do not narrate it. The declaration is copied whole from the file.
  • Review the two startup paths against root/mod.rs. Both end in Self::bind.