lib.rs

benches/rrt/canister/src/lib.rs

lib.rs431 lines← Benchmarks
1//! One shard hosts all seven original generated graphs on one shared runtime.2#![feature(arbitrary_self_types_pointers, allocator_ext)]34mod admissions;5pub mod api;6mod config;7pub mod flows;8#[cfg(feature = "tripwire-workload")]9pub mod ingress;10pub mod ledger;11mod metrics;12#[cfg(feature = "tripwire-workload")]13pub mod protocol;14pub mod root;15pub mod wire;16pub mod workflows;1718#[cfg(feature = "instruction-profile")]19#[cdk_rsx::query]20fn instruction_profile() -> cdk_rsx_reactor::profile::Snapshot {21    cdk_rsx_reactor::profile::snapshot()22}2324mod page_scopes {25    cdk_rsx::page_profile::declare_scope!(pub const START_BODY = 32, "app.start.body");26    cdk_rsx::page_profile::declare_scope!(pub const START_INPUT = 33, "app.start.input");27    cdk_rsx::page_profile::declare_scope!(pub const START_ADMISSION = 34, "app.start.admission");28    cdk_rsx::page_profile::declare_scope!(pub const START_REPLY = 35, "app.start.reply");29}3031#[cfg(feature = "tripwire-workload")]32use crate::protocol::Endpoint;33use cdk_rsx::{Principal, wire::Nat};34use cdk_rsx_reactor::Result;35#[cfg(not(feature = "tripwire-workload"))]36use cdk_rsx_reactor::typed::Endpoint;37use cdk_rsx_reactor::{Context, Decision};38use cdk_rsx_takt as flow;39#[cfg(feature = "tripwire-workload")]40type ObserveAdmission = protocol::ObserveAdmission;41#[cfg(not(feature = "tripwire-workload"))]42type ObserveAdmission = wire::ObserveInput;43#[cfg(feature = "tripwire-workload")]44type ObserveResponse = protocol::ObserveOutputNumbers;45#[cfg(not(feature = "tripwire-workload"))]46type ObserveResponse = wire::reactor::Response<Nat>;4748fn route(49    app: &root::RootView<'_, cdk_rsx_store::Scope<'_>>,50    context: Context,51    route: &str,52    bytes: &[u8],53) -> Result<Decision<Vec<u8>>> {54    let now = cdk_rsx::api::time();55    if route == flow::coordination::ROUTE {56        return app.flows().scheduled_receive(context, bytes, now);57    }58    if route == "work.dispatch" {59        let dispatch = |context: Context, command: wire::CommandRef<'_>| {60            let enabled = app.config().telemetry()?;61            let before = enabled.then(|| cdk_rsx::api::performance_counter(0));62            let result = if app.config().should_reject(command)? {63                Err(wire::DispatchError::App(wire::BusinessError::Unavailable))64            } else {65                app.commands()66                    .dispatch(context.origin.caller, now, command)?67            };68            let metrics = before.map(|before| wire::Metrics {69                instructions: cdk_rsx::api::performance_counter(0) - before,70                elapsed_nanos: 0,71            });72            Ok(Decision::Reply(wire::DispatchOutput {73                result,74                caller: context.origin.caller,75                metrics,76            }))77        };78        #[cfg(feature = "tripwire-workload")]79        return protocol::dispatch_command(context, bytes, dispatch);80        #[cfg(not(feature = "tripwire-workload"))]81        return wire::reactor::dispatch(context, bytes, dispatch);82    }83    if route == "work.observe" {84        let endpoint = Endpoint::<ObserveAdmission, ObserveResponse>::new("work.observe");85        let observe = |context: Context, _| {86            let before = app87                .config()88                .telemetry()?89                .then(|| cdk_rsx::api::performance_counter(0));90            #[cfg(feature = "tripwire-workload")]91            let total = app.select().total_value()?;92            #[cfg(not(feature = "tripwire-workload"))]93            let total = app.select().total()?;94            let metrics = before.map(|before| wire::Metrics {95                instructions: cdk_rsx::api::performance_counter(0) - before,96                elapsed_nanos: 0,97            });98            #[cfg(feature = "tripwire-workload")]99            let reply = ObserveResponse {100                total,101                caller: context.origin.caller,102                metrics,103            };104            #[cfg(not(feature = "tripwire-workload"))]105            let reply = ObserveResponse::new(total, context.origin.caller, metrics);106            Ok(Decision::Reply(reply))107        };108        #[cfg(feature = "tripwire-workload")]109        return endpoint.dispatch(context, bytes, observe);110        #[cfg(not(feature = "tripwire-workload"))]111        return endpoint.dispatch_evolving(context, bytes, observe);112    }113    Ok(Decision::Blocked)114}115116#[cdk_rsx::update(name = "addPeer")]117fn add_peer(peer: Principal) -> bool {118    root::with(|app| {119        if cdk_rsx::api::msg_caller() != app.select().owner()? || peer == Principal::anonymous() {120            return Ok(false);121        }122        app.reactor().add_peer(peer, cdk_rsx::api::time())?;123        Ok(true)124    })125}126#[cdk_rsx::update(name = "setEndpointTelemetry")]127fn set_endpoint_telemetry(enabled: bool) -> bool {128    root::with(|app| {129        if cdk_rsx::api::msg_caller() != app.select().owner()? {130            return Ok(false);131        }132        app.config().set_telemetry(enabled)?;133        Ok(true)134    })135}136#[cdk_rsx::update]137fn test_reject_next(count: Nat) -> bool {138    root::with(|app| {139        let Some(count) = count.try_to_u64().and_then(|n| u8::try_from(n).ok()) else {140            return Ok(false);141        };142        if cdk_rsx::api::msg_caller() != app.select().owner()? || count > 10 {143            return Ok(false);144        }145        app.config().reject_next(count)?;146        Ok(true)147    })148}149#[cfg(not(feature = "tripwire-workload"))]150#[cdk_rsx::update]151fn start(kind: api::Workflow, #[evolve] args: api::Start) -> api::Admission {152    match start_workflow(kind, args.into()) {153        Ok(id) => api::Admission::Ok(id.into()),154        Err(error) => api::Admission::Err(error),155    }156}157#[cfg(feature = "tripwire-workload")]158#[cdk_rsx::update(tripwire, max_arg_bytes=2*1024*1024)]159fn start(packet: ingress::StartPacket<'_>) -> cdk_rsx::tripwire::StackEncoded<10> {160    let (kind, args) = ingress::request(packet)161        .unwrap_or_else(|error| cdk_rsx::trap(format!("Tripwire admission: {error}")));162    ingress::response(start_workflow(kind, args))163}164#[inline]165fn start_workflow(166    kind: api::Workflow,167    args: admissions::Input,168) -> std::result::Result<u64, flow::Problem> {169    cdk_rsx::page_profile::scope_block!(page_scopes::START_BODY, {170        let caller = cdk_rsx::api::msg_caller();171        let now = cdk_rsx::api::time();172        root::with(|app| {173            let result = cdk_rsx::page_profile::scope_block!(174                page_scopes::START_ADMISSION,175                app.admissions().enqueue(caller, kind, args, now)176            )?;177            cdk_rsx::page_profile::scope_block!(page_scopes::START_REPLY, Ok(result))178        })179    })180}181#[cdk_rsx::query]182fn request_status(request: Nat) -> Option<api::RequestStatus> {183    let Some(id) = request.try_to_u64() else {184        return None;185    };186    let caller = cdk_rsx::api::msg_caller();187    root::read(|app| app.admissions().status(caller, id))188}189#[cdk_rsx::query]190fn state() -> metrics::Stats {191    let flags = cdk_rsx_reactor::ic::stats();192    root::read(|app| {193        let (admitted, rejected) = app.config().admissions()?;194        let reactor = app.reactor_runtime();195        Ok(metrics::Stats::from_snapshot(metrics::Snapshot {196            admitted,197            rejected,198            queued_requests: app.admissions().queued()?,199            reclaim_pending: false,200            event_waits: app.coordinator().pending()?,201            counts: app.select().counts()?,202            total: app.select().total()?,203            last_caller: app.select().last_caller()?,204            fingerprints: app.commands().retained()?,205            retry_bytes_match: app.config().retry_bytes_match()?,206            runtime: app.flows().runtime().stats()?,207            workflow: app.flows().runtime().workflow_metrics()?,208            transport: app.reactor().stats()?,209            metrics: reactor.metrics(),210            scheduler: reactor.scheduler.stats(),211            immediate_armed: u64::from(flags.immediate_armed || flags.pumping || flags.continuing),212        }))213    })214}215216#[cdk_rsx::query]217fn takt_inspect(request: flows::InspectionRequest) -> flows::InspectionResponse {218    let caller = cdk_rsx::api::msg_caller();219    root::read(|app| app.flows().inspect(caller, request, cdk_rsx::api::time()))220}221222#[cdk_rsx::update(name = "setWorkflowTracing")]223fn set_workflow_tracing(kind: flows::Workflow, enabled: bool) -> bool {224    root::with(|app| {225        if cdk_rsx::api::msg_caller() != app.select().owner()? {226            return Ok(false);227        }228        app.flows().configure_tracing(kind, enabled)?;229        Ok(true)230    })231}232233#[cfg(target_family = "wasm")]234fn start_runtime(app: std::rc::Rc<root::Root>) -> Result<()> {235    use std::rc::Rc;236    let runtime = app.reactor().runtime_handle();237    cdk_rsx_reactor::ic::start(238        app.store().clone(),239        Rc::new(ReactorHost(app.clone())),240        runtime.clone(),241    );242    app.flows().start_drivers(app.store().clone())?;243    let admissions = app.admissions().clone();244    let app_admission = app.clone();245    admissions.start(runtime.scheduler.clone(), move |scope, now| {246        let app_admission = app_admission.view(scope);247        if let Some(admitted) = app_admission248            .admissions()249            .process_one(now, |workflow, seed, now| {250                app_admission.flows().start(workflow, seed, now)251            })?252        {253            app_admission.config().record_admission(admitted)?;254        }255        Ok(())256    });257    cdk_rsx_takt::coordination::start(258        Rc::new(CoordinationHost(app.clone())),259        app.coordinator().runtime_handle(),260    )?;261    app.read(|view| {262        cdk_rsx_rechain::ic::start(view.rechain(), runtime.scheduler.clone());263        Ok(())264    })?;265    let commands = app.commands().clone();266    let prune = commands.clone();267    let cleanup = commands.cleanup_handle();268    cleanup.start(269        runtime.scheduler.clone(),270        move |scope| commands.view(scope).next_expiry(),271        move |scope, now| prune.view(scope).collect(now),272    );273    Ok(())274}275#[cfg(target_family = "wasm")]276struct ReactorHost(std::rc::Rc<root::Root>);277#[cfg(target_family = "wasm")]278impl cdk_rsx_reactor::ic::Host for ReactorHost {279    fn receive(280        &self,281        cap: &cdk_rsx_store::Scope<'_>,282        sender: Principal,283        batch: cdk_rsx_reactor::wire::BatchRef<'_>,284        now: u64,285    ) -> Result<cdk_rsx_reactor::Acknowledgement> {286        cdk_rsx_reactor::profile::scoped(cdk_rsx_reactor::profile::Operation::Receive, |scope| {287            scope.body(|| {288                self.0289                    .view(cap)290                    .reactor()291                    .receive(sender, batch, now, || cdk_rsx::api::performance_counter(0))292            })293        })294    }295    fn process(296        &self,297        cap: &cdk_rsx_store::Scope<'_>,298        p: cdk_rsx_reactor::Priority,299        now: u64,300    ) -> Result<bool> {301        cdk_rsx_reactor::profile::scoped(cdk_rsx_reactor::profile::Operation::Process, |scope| {302            scope.body(|| {303                self.0304                    .view(cap)305                    .reactor()306                    .process_one(p, now, |context, name, bytes| {307                        cdk_rsx_reactor::profile::measure(308                            cdk_rsx_reactor::profile::Phase::Router,309                            || route(&self.0.view(cap), context, name, bytes),310                        )311                    })312            })313        })314    }315    fn fanout(&self, cap: &cdk_rsx_store::Scope<'_>, now: u64) -> Result<bool> {316        cdk_rsx_reactor::profile::scoped(cdk_rsx_reactor::profile::Operation::Fanout, |scope| {317            scope.body(|| self.0.view(cap).reactor().fanout_one(now))318        })319    }320    fn prepare(321        &self,322        cap: &cdk_rsx_store::Scope<'_>,323        p: cdk_rsx_reactor::Priority,324        now: u64,325    ) -> Result<Option<cdk_rsx_reactor::Exchange>> {326        cdk_rsx_reactor::profile::scoped(cdk_rsx_reactor::profile::Operation::Prepare, |scope| {327            scope.body(|| self.0.view(cap).reactor().prepare_exchange(p, now))328        })329    }330    fn finish(331        &self,332        cap: &cdk_rsx_store::Scope<'_>,333        exchange: &mut cdk_rsx_reactor::Exchange,334        ack: Option<cdk_rsx_reactor::Acknowledgement>,335        _disposition: cdk_rsx_reactor::ic::PhysicalDisposition,336        now: u64,337    ) -> Result<()> {338        cdk_rsx_reactor::profile::scoped(cdk_rsx_reactor::profile::Operation::Finish, |scope| {339            scope.body(|| {340                self.0341                    .view(cap)342                    .reactor()343                    .finish_exchange(exchange, ack, now)344            })345        })346    }347}348#[cfg(target_family = "wasm")]349struct CoordinationHost(std::rc::Rc<root::Root>);350#[cfg(target_family = "wasm")]351impl cdk_rsx_takt::coordination::Host for CoordinationHost {352    fn step(&self, cap: &cdk_rsx_store::Scope<'_>, now: u64) -> Result<()> {353        self.0354            .view(cap)355            .coordinator()356            .process_one(now, |key, producer, bytes| {357                self.0.view(cap).flows().signal(key, producer, bytes, now)358            })?;359        Ok(())360    }361}362#[cfg(not(feature = "tripwire"))]363#[cdk_rsx::update(raw, max_arg_bytes=cdk_rsx_reactor::wire::MAX_WIRE_BYTES)]364fn reactor_receive(bytes: Vec<u8>) -> Vec<u8> {365    cdk_rsx_reactor::ic::receive_wire(cdk_rsx::api::msg_caller(), &bytes)366}367#[cfg(not(feature = "tripwire"))]368#[cdk_rsx::update(raw, max_arg_bytes=cdk_rsx_reactor::wire::MAX_TURN_WIRE_BYTES, guard=reactor_self)]369fn reactor_turn(bytes: Vec<u8>) -> Vec<u8> {370    cdk_rsx_reactor::ic::turn_wire(&bytes)371}372#[cfg(feature = "tripwire")]373#[cdk_rsx::update(tripwire, max_arg_bytes=cdk_rsx_reactor::tripwire::MAX_ENVELOPE_BYTES)]374fn reactor_receive(packet: cdk_rsx_reactor::tripwire::EnvelopePacket<'_>) -> Vec<u8> {375    cdk_rsx_reactor::ic::receive_tripwire(cdk_rsx::api::msg_caller(), packet)376}377#[cfg(feature = "tripwire")]378#[cdk_rsx::update(tripwire, max_arg_bytes=cdk_rsx_reactor::wire::MAX_TURN_WIRE_BYTES, guard=reactor_self)]379fn reactor_turn(packet: cdk_rsx_reactor::tripwire::TurnPacket<'_>) -> Vec<u8> {380    cdk_rsx_reactor::ic::turn_tripwire(packet)381}382fn reactor_self() -> std::result::Result<(), String> {383    if cdk_rsx::api::msg_caller() == cdk_rsx::api::canister_self() {384        Ok(())385    } else {386        Err("Reactor continuation is private".into())387    }388}389#[cdk_rsx::query(response_limits = cdk_rsx::wire::LARGE_PAYLOAD_LIMITS)]390fn get_blocks(391    requests: Vec<cdk_rsx_rechain::wire::TransactionRange>,392    chain: Option<u8>,393) -> cdk_rsx_rechain::wire::GetBlocksResponse {394    root::read(|app| {395        app.rechain().wire_get_blocks(396            &requests,397            chain,398            &cdk_rsx_rechain::ReadContext::from_system(),399        )400    })401}402#[cdk_rsx::query]403fn get_chain_info(404    request: cdk_rsx_rechain::wire::GetChainInfoArgs,405    chain: Option<u8>,406) -> std::result::Result<cdk_rsx_rechain::wire::ChainInfo, cdk_rsx_rechain::wire::ChainError> {407    root::read(|app| {408        app.rechain()409            .wire_chain_info(cdk_rsx::api::canister_self(), &request, chain)410    })411}412#[cdk_rsx::query]413fn get_format() -> cdk_rsx_rechain::wire::Format {414    cdk_rsx_rechain::wire::format()415}416#[cdk_rsx::query]417fn get_tip_certificate(418    chain: Option<u8>,419) -> std::result::Result<420    Option<cdk_rsx_rechain::wire::DataCertificate>,421    cdk_rsx_rechain::wire::ChainError,422> {423    cdk_rsx_rechain::ic::get_tip_certificate(chain)424}425#[cdk_rsx::update(guard=cdk_rsx::guards::controller)]426fn rechain_retry_maintenance() {427    cdk_rsx_rechain::ic::retry_maintenance()428}429430#[cfg(test)]431mod tests;