mod.rs

benches/rrt/canister/src/root/mod.rs

mod.rs392 lines← Benchmarks
1//! One actor root owns all library modules; services borrow one execution frame.2#[cfg(target_family = "wasm")]3mod admission;4#[cdk_rsx::root(init=initialize,restore=restore,check=check_upgrade,shutdown=shutdown,arguments=(cdk_rsx::Principal,cdk_rsx::wire::Nat,u64,cdk_rsx::wire::Nat,cdk_rsx::wire::Nat,cdk_rsx::wire::Nat))]5pub mod memory;6#[cfg(not(target_family = "wasm"))]7use cdk_rsx::transient::Reclaimable;8use cdk_rsx::transient::{RootKey, TransientRoot};9use cdk_rsx::{Principal, wire::Nat};10use cdk_rsx_reactor::{Error, Result};11use cdk_rsx_reactor::{12    Reactor, Runtime as ReactorRuntime, SchedulerSettings, Settings, scheduler::Scheduler,13};14use cdk_rsx_store::{Access, Actor, ModuleRef, ReadScope, Scope, Store};15use std::rc::Rc;16struct Bindings {17    reactor: Rc<Reactor>,18    reactor_runtime: Rc<ReactorRuntime>,19    rechain: Rc<cdk_rsx_rechain::Runtime>,20    coordinator: Rc<cdk_rsx_takt::coordination::Coordinator>,21    select: crate::ledger::selectors::Selectors,22    commands: Rc<crate::ledger::Commands>,23    flows: Rc<crate::flows::Flows>,24    config: crate::config::Config,25    admissions: Rc<crate::admissions::Admissions>,26}27pub struct Root {28    actor: Actor<memory::Memory>,29    services: Bindings,30}31impl Root {32    pub fn new(33        owner: Principal,34        items: Nat,35        budget: u64,36        concurrent: Nat,37        bytes: Nat,38        callbacks: Nat,39        canister: Principal,40    ) -> Result<Rc<Self>> {41        let saved = configuration(42            (owner, items, budget, concurrent, bytes, callbacks),43            canister,44        )?;45        #[cfg(not(target_family = "wasm"))]46        let store = Store::default();47        #[cfg(target_family = "wasm")]48        let store = Store::initialize()?;49        Self::install(&store, saved)50    }51    fn install(store: &Store, saved: memory::v1::Data) -> Result<Rc<Self>> {52        let actor = store.install(&memory::v1::KEY, |scope| {53            let root = scope.create(&memory::v1::KEY, saved)?;54            let children = root.reference().children(scope, &memory::v1::KEY)?;55            children.reactor_runtime.attach(56                scope,57                checked(cdk_rsx_reactor::memory::new_runtime(58                    scope,59                    saved.canister,60                    1,61                )),62            )?;63            children.reactor.attach(64                scope,65                checked(cdk_rsx_reactor::memory::new(scope, saved.settings)),66            )?;67            children.rechain.attach(68                scope,69                checked(cdk_rsx_rechain::memory::new(70                    scope,71                    &crate::ledger::chains(),72                )),73            )?;74            children.replay.attach(75                scope,76                checked(cdk_rsx_rechain::idempotency::memory::new(scope, 0, 100_000)),77            )?;78            children.work.attach(79                scope,80                checked(crate::ledger::memory::new(scope, saved.owner)),81            )?;82            children83                .config84                .attach(scope, checked(crate::config::memory::new(scope)))?;85            children.admissions.attach(86                scope,87                checked(crate::admissions::memory::new(scope, saved.owner)),88            )?;89            children90                .flows91                .attach(scope, crate::flows::memory::new(scope, saved.concurrent)?)?;92            drop(children);93            Ok(root)94        })?;95        Self::bind(actor)96    }97    pub fn reopen(store: &Store) -> Result<Rc<Self>> {98        Self::bind(store.open(&memory::v1::KEY)?)99    }100    fn bind(actor: Actor<memory::Memory>) -> Result<Rc<Self>> {101        let services = actor.read(|scope, root| Ok(Bindings::bind(scope, root)))??;102        Ok(Rc::new(Self { actor, services }))103    }104    pub fn store(&self) -> &Store {105        self.actor.store()106    }107    pub fn view<'a, A: Access>(&'a self, access: &'a A) -> RootView<'a, A> {108        RootView { root: self, access }109    }110    pub fn read<T>(111        &self,112        f: impl for<'a, 's> FnOnce(RootView<'a, ReadScope<'s>>) -> Result<T>,113    ) -> Result<T> {114        self.actor.read(|scope, _| Ok(f(self.view(scope))))?115    }116    pub fn with<T>(117        &self,118        f: impl for<'a, 's> FnOnce(RootView<'a, Scope<'s>>) -> Result<T>,119    ) -> Result<T> {120        self.actor.with(|scope, _| Ok(f(self.view(scope))))?121    }122    pub fn reactor(&self) -> &Rc<Reactor> {123        &self.services.reactor124    }125    pub fn rechain(&self) -> &Rc<cdk_rsx_rechain::Runtime> {126        &self.services.rechain127    }128    pub fn coordinator(&self) -> &Rc<cdk_rsx_takt::coordination::Coordinator> {129        &self.services.coordinator130    }131    pub fn commands(&self) -> &Rc<crate::ledger::Commands> {132        &self.services.commands133    }134    pub fn flows(&self) -> &Rc<crate::flows::Flows> {135        &self.services.flows136    }137    pub fn admissions(&self) -> &Rc<crate::admissions::Admissions> {138        &self.services.admissions139    }140}141impl Bindings {142    fn bind(access: &impl Access, root: ModuleRef<memory::Memory>) -> Result<Self> {143        let saved = *root.read(access, &memory::v1::KEY)?;144        let children = root.children(access, &memory::v1::KEY)?;145        let scheduler = Scheduler::new(saved.settings.scheduler)?;146        let reactor_runtime = ReactorRuntime::bind(147            access,148            children.reactor_runtime.reference(access)?.unwrap(),149            saved.canister,150            1,151            scheduler.clone(),152        )?;153        let reactor = Reactor::bind(154            access,155            children.reactor.reference(access)?.unwrap(),156            saved.settings,157            reactor_runtime.clone(),158        )?;159        let rechain = cdk_rsx_rechain::Runtime::bind(160            access,161            children.rechain.reference(access)?.unwrap(),162            &crate::ledger::chains(),163        )?;164        let coordinator = cdk_rsx_takt::coordination::Coordinator::new(165            reactor.clone(),166            cdk_rsx_takt::coordination::Runtime::new(scheduler.clone()),167        );168        let work = crate::ledger::Work::bind(access, children.work.reference(access)?.unwrap())?;169        let select = crate::ledger::selectors::Selectors::new(work.clone());170        let replay = cdk_rsx_rechain::idempotency::Idempotency::bind(171            access,172            children.replay.reference(access)?.unwrap(),173            0,174            100_000,175        )?;176        let commands = Rc::new(crate::ledger::Commands::new(177            rechain.clone(),178            replay,179            work,180            coordinator.clone(),181            Rc::new(cdk_rsx_rechain::cleanup::Cleanup::default()),182            saved.canister,183        ));184        let flows = crate::flows::Flows::bind(185            access,186            children.flows.reference(access)?.unwrap(),187            saved.concurrent,188            scheduler,189            commands.clone(),190            coordinator.clone(),191            reactor.clone(),192        )?;193        let config =194            crate::config::Config::bind(access, children.config.reference(access)?.unwrap())?;195        let admissions = crate::admissions::Admissions::bind(196            access,197            children.admissions.reference(access)?.unwrap(),198            saved.owner,199        )?;200        Ok(Self {201            reactor,202            reactor_runtime,203            rechain,204            coordinator,205            select,206            commands,207            flows,208            config,209            admissions,210        })211    }212}213pub struct RootView<'a, A: Access> {214    root: &'a Root,215    access: &'a A,216}217impl<A: Access> Copy for RootView<'_, A> {}218impl<A: Access> Clone for RootView<'_, A> {219    fn clone(&self) -> Self {220        *self221    }222}223impl<A: Access> RootView<'_, A> {224    pub fn reactor(&self) -> cdk_rsx_reactor::ReactorView<'_, A> {225        cdk_rsx_store::binding::Service::view(&self.root.services.reactor, self.access)226    }227    pub fn reactor_runtime(&self) -> cdk_rsx_reactor::RuntimeView<'_, A> {228        self.root.services.reactor_runtime.view(self.access)229    }230    pub fn rechain(&self) -> cdk_rsx_rechain::View<'_, A> {231        self.root.services.rechain.view(self.access)232    }233    pub fn coordinator(&self) -> cdk_rsx_takt::coordination::CoordinatorView<'_, A> {234        self.root.services.coordinator.view(self.access)235    }236    pub fn flows(&self) -> crate::flows::FlowsView<'_, A> {237        cdk_rsx_store::binding::Service::view(&self.root.services.flows, self.access)238    }239    pub fn select(&self) -> crate::ledger::selectors::View<'_, A> {240        self.root.services.select.view(self.access)241    }242    pub fn commands(&self) -> crate::ledger::CommandsView<'_, A> {243        self.root.services.commands.view(self.access)244    }245    pub fn config(&self) -> crate::config::View<'_, A> {246        self.root.services.config.view(self.access)247    }248    pub fn admissions(&self) -> crate::admissions::View<'_, A> {249        self.root.services.admissions.view(self.access)250    }251}252type Init = (Principal, Nat, u64, Nat, Nat, Nat);253fn configuration(254    (owner, items, budget, concurrent, bytes, callbacks): Init,255    canister: Principal,256) -> Result<memory::v1::Data> {257    fn number(n: Nat) -> Result<u32> {258        n.try_to_u64()259            .and_then(|v| u32::try_from(v).ok())260            .ok_or(Error::InvalidInput("configuration exceeds u32"))261    }262    let settings = Settings {263        scheduler: SchedulerSettings {264            instruction_budget: budget,265            max_callbacks: number(callbacks)?,266            reserved_control: 4,267        },268        max_batch_items: number(items)?,269        max_batch_bytes: number(bytes)?,270        ..Default::default()271    };272    settings.validate()?;273    Ok(memory::v1::Data {274        owner,275        canister,276        concurrent: number(concurrent)?,277        settings,278    })279}280#[cfg(target_family = "wasm")]281static APP: cdk_rsx::transient::HotRoot<Rc<Root>> = {282    // SAFETY: this root owns the unique init/admission exports, fixes Rc<Root>283    // for the executable lifetime and clears this slot before KEEP. Canonical284    // startup resets the SDK's disjoint root interval before constructing it.285    unsafe { cdk_rsx::transient::HotRoot::new() }286};287#[cfg(not(target_family = "wasm"))]288thread_local! {static APP:Reclaimable<Option<Rc<Root>>>=const{Reclaimable::new()};}289pub fn current() -> Rc<Root> {290    RootKey::with(&APP, Rc::clone)291}292pub fn checked<T>(result: Result<T>) -> T {293    result.unwrap_or_else(|error| cdk_rsx::trap(format!("RRT Fourcans: {error:?}")))294}295pub fn read<T>(f: impl for<'a, 's> FnOnce(RootView<'a, ReadScope<'s>>) -> Result<T>) -> T {296    checked(current().read(f))297}298pub fn with<T>(f: impl for<'a, 's> FnOnce(RootView<'a, Scope<'s>>) -> Result<T>) -> T {299    checked(current().with(f))300}301fn install_app(app: Rc<Root>) -> Result<()> {302    RootKey::install(&APP, app.clone());303    #[cfg(target_family = "wasm")]304    crate::start_runtime(app)?;305    #[cfg(target_family = "wasm")]306    admission::publish();307    Ok(())308}309pub fn initialize(args: Init) -> Result<()> {310    let saved = configuration(args, cdk_rsx::api::canister_self())?;311    #[cfg(not(target_family = "wasm"))]312    let store = Store::default();313    #[cfg(target_family = "wasm")]314    let store = Store::initialize()?;315    install_app(Root::install(&store, saved)?)316}317pub fn restore() -> Result<()> {318    #[cfg(target_family = "wasm")]319    {320        let store = unsafe { Store::reopen() }?;321        install_app(Root::reopen(&store)?)322    }323    #[cfg(not(target_family = "wasm"))]324    {325        Err(Error::InvalidInput(326            "native restore requires an explicit Store",327        ))328    }329}330pub fn check_upgrade() -> Result<()> {331    cdk_rsx_store::assert_quiescent();332    current().read(|app| {333        let work = app.flows().runtime().stats()?;334        let wire = app.reactor().stats()?;335        if app.admissions().queued()? != 0336            || work.pending != 0337            || work.logical_calls != 0338            || work.physical_calls != 0339            || wire.incoming != 0340            || wire.outgoing != 0341            || wire.completions != 0342            || wire.active_calls != 0343            || wire.publications != 0344            || wire.recipients != 0345            || wire.subscriptions != 0346        {347            return Err(Error::InvalidInput(348                "typed-root KEEP requires full business and transport drain",349            ));350        }351        Ok(())352    })353}354fn clear_app() {355    let app = (!RootKey::is_empty(&APP)).then(current);356    RootKey::clear(&APP);357    if let Some(app) = app {358        checked(cdk_rsx_reactor::ic::shutdown());359        cdk_rsx_rechain::ic::shutdown();360        app.admissions().shutdown();361        app.commands().cleanup_handle().shutdown();362        checked(app.with(|view| view.flows().runtime().shutdown()));363        checked(app.coordinator().shutdown());364        checked(app.reactor().runtime_handle().shutdown());365        checked(app.reactor().runtime_handle().scheduler.shutdown());366        drop(app);367    }368}369fn app_clear() -> bool {370    RootKey::is_empty(&APP)371}372static TRANSIENT_ROOTS: &[TransientRoot] = &[373    TransientRoot {374        name: "fourcans::APP service graph",375        clear: clear_app,376        is_clear: app_clear,377    },378    TransientRoot {379        name: "Reactor controller",380        clear: || checked(cdk_rsx_reactor::ic::shutdown()),381        is_clear: cdk_rsx_reactor::ic::is_shutdown,382    },383    TransientRoot {384        name: "Rechain publisher",385        clear: cdk_rsx_rechain::ic::shutdown,386        is_clear: cdk_rsx_rechain::ic::is_shutdown,387    },388];389pub fn shutdown() -> Result<()> {390    cdk_rsx::transient::run_registered(TRANSIENT_ROOTS);391    Ok(())392}