byteflow-actors 0.9.28

Embeddable flow runtime: M:N scheduler, Atomic Hop (Message+Cap), supervisor — use byteflow::
Documentation
//! Spawning: the shared [`spawn_on`] path used by hosts and bytecode, and the
//! detached [`RuntimeSpawner`] handle.
// Docs ratchet: public items here predate `missing_docs`. Delete this
// allow once they are documented; new files get the lint by default.
#![allow(missing_docs)]

use super::*;

/// Context for a bytecode `Spawn`: parent self-authority is attenuated into
/// the child. Host spawn passes `None` and mints a trusted root instead.
pub(crate) struct BytecodeSpawn<'a> {
    pub authority: &'a Cap,
    pub cell: &'a crate::bytecode::RevocationCell,
    pub quota: &'a crate::scheduler::quota::FlowQuota,
    pub requested_rights: CapRights,
}

/// Shared machinery behind `Runtime::spawn` and `RuntimeSpawner::spawn`
/// (and, transitively, `Supervisor`): build a fresh `Flow` (VM +
/// mailbox + completion channel), register it in the directory, and push
/// it onto the global injector for any worker to pick up.
///
/// Returns [`SpawnError`] on bad function index / VM init / directory
/// poison — never panics. Bytecode `Opcode::Spawn` that fails here turns
/// into `FlowOutcome::Failed` for the *parent* (see `worker`).
/// Bytecode `Spawn` must pass exactly the callee's arity. Host spawn is not
/// checked here.
pub(crate) fn bytecode_spawn_arity(arity: u8, argc: usize) -> Result<(), crate::vm::Fault> {
    if argc != usize::from(arity) {
        Err(crate::vm::Fault::BadArity {
            passed: argc,
            expected: arity,
        })
    } else {
        Ok(())
    }
}

#[allow(clippy::too_many_arguments)]
pub(crate) fn spawn_on(
    shared: &Arc<Shared>,
    chunk: &Arc<Chunk>,
    natives: &Arc<NativeTable>,
    function: u32,
    args: &[Value],
    restart_policy: RestartPolicy,
    supervisor: Option<SupervisorLink>,
    parent: Option<FlowId>,
    bytecode: Option<BytecodeSpawn<'_>>,
    // When `bytecode` is `None`, overrides `Shared::root_authority`.
    host_authority: Option<RootAuthorityPolicy>,
) -> Result<FlowHandle, SpawnError> {
    // Bytecode `Spawn` encodes argc. Host `Runtime::spawn` does not: a short
    // host argument list still fills the rest with `Unit`. Only the bytecode
    // path is rejected here, matching `VerifyError::CallArity` / `Fault::BadArity`.
    if bytecode.is_some() {
        match chunk.function(function) {
            Some(def) => {
                if let Err(fault) = bytecode_spawn_arity(def.arity, args.len()) {
                    return Err(fault.into());
                }
            }
            None => {
                return Err(SpawnError::BadFunction {
                    index: function,
                    table_size: chunk.functions.len() as u32,
                });
            }
        }
    }
    shared.flow_limit.try_reserve()?;
    let id = match crate::scheduler::process::try_next_flow_id() {
        Ok(id) => id,
        Err(crate::scheduler::error::RuntimeError::FlowIdExhausted) => {
            shared.flow_limit.release();
            return Err(SpawnError::FlowIdExhausted);
        }
        Err(_) => {
            shared.flow_limit.release();
            return Err(SpawnError::Unavailable);
        }
    };
    let cell = match shared.caps.bind_flow(id) {
        Ok(c) => c,
        Err(_) => {
            shared.flow_limit.release();
            return Err(SpawnError::Unavailable);
        }
    };
    let authority = match bytecode {
        None => {
            let policy = host_authority.unwrap_or(shared.root_authority);
            policy.mint(id.as_u64(), natives.len(), cell.as_ref())
        }
        Some(ctx) => match crate::scheduler::spawn::exec_spawn_authority(
            ctx.authority,
            ctx.cell,
            ctx.quota,
            id.as_u64(),
            ctx.requested_rights,
            None,
            cell.as_ref(),
        ) {
            Ok(cap) => cap,
            Err(e) => {
                shared.flow_limit.release();
                let _ = shared.caps.revoke_flow(id);
                return Err(SpawnError::from(e));
            }
        },
    };
    let args = match grant_caps_in_args(shared, parent, id, args) {
        Ok(a) => a,
        Err(e) => {
            shared.flow_limit.release();
            let _ = shared.caps.revoke_flow(id);
            return Err(e);
        }
    };
    let gate = NativeGate::from_authority(
        &authority,
        Arc::clone(&cell),
        shared.caps.native_cell(),
        natives.len(),
    );
    let quota = Arc::new(crate::scheduler::quota::FlowQuota::from_config(
        shared.quota,
    ));
    let mut vm = match Vm::with_native_gate(
        chunk.clone(),
        natives.clone(),
        gate,
        function,
        args.as_slice(),
    ) {
        Ok(vm) => vm,
        Err(e) => {
            shared.flow_limit.release();
            let _ = shared.caps.revoke_flow(id);
            return Err(e.into());
        }
    };
    vm.set_memory_budget(Arc::clone(&shared.memory));
    if let Err(e) = vm.set_quota(Arc::clone(&quota)) {
        shared.flow_limit.release();
        let _ = shared.caps.revoke_flow(id);
        return Err(e.into());
    }
    let mailbox = Arc::new(Mailbox::with_config(shared.mailbox));
    if let Err(e) = shared.directory.register(id, mailbox.clone()) {
        crate::scheduler::error::report_fault(e);
        shared.flow_limit.release();
        let _ = shared.caps.revoke_flow(id);
        return Err(SpawnError::Unavailable);
    }
    if let Err(e) = shared.quotas.insert(id, Arc::clone(&quota)) {
        crate::scheduler::error::report_fault(e);
        let _ = shared.directory.unregister(id);
        shared.flow_limit.release();
        let _ = shared.caps.revoke_flow(id);
        return Err(SpawnError::Unavailable);
    }
    let (tx, rx) = crate::scheduler::oneshot::channel();
    let mut flow = Box::new(Flow::new(id, vm, mailbox, restart_policy, tx));
    flow.authority = authority;
    flow.cell = cell;
    flow.quota = quota;
    flow.supervisor = supervisor;
    RuntimeMetrics::inc(&shared.metrics.processes_spawned);
    record_security_event(
        shared,
        &crate::scheduler::sandbox::SecurityEvent::CapabilityCreated {
            holder: id.as_u64(),
        },
    );
    if matches!(
        shared.trust,
        crate::bytecode::TrustLevel::Untrusted | crate::bytecode::TrustLevel::Restricted
    ) {
        crate::scheduler::sandbox::SecurityCounters::inc(&shared.security.active_untrusted_flows);
    }
    enqueue_flow(shared, flow);
    wake_workers(shared);
    Ok(FlowHandle { id, receiver: rx })
}

fn grant_caps_in_args(
    shared: &Shared,
    parent: Option<FlowId>,
    child: FlowId,
    args: &[Value],
) -> Result<Vec<Value>, SpawnError> {
    let mut out = Vec::with_capacity(args.len());
    for arg in args {
        if !arg.within_nesting_limit() {
            return Err(SpawnError::InvalidCapability);
        }
        let granted = arg.map_caps(
            0,
            &SpawnError::InvalidCapability,
            &mut |id| match parent {
                None => shared
                    .caps
                    .reissue_for(id, child)
                    .map_err(|_| SpawnError::InvalidCapability),
                Some(holder) => match shared.caps.delegate(id, holder, child) {
                    Ok(granted) => {
                        record_security_event(
                            shared,
                            &crate::scheduler::sandbox::SecurityEvent::CapabilityDelegated {
                                from: holder.as_u64(),
                                to: child.as_u64(),
                            },
                        );
                        Ok(granted)
                    }
                    Err(_) => Err(SpawnError::InvalidCapability),
                },
            },
            &mut |message| {
                if let Some(holder) = parent {
                    if message.sender == 0 {
                        message.sender = holder.as_u64();
                    }
                }
                if message.request_id == 0 {
                    message.request_id =
                        crate::scheduler::worker::mint_host_request_id(&shared.host_next_request_id)
                            .ok_or(SpawnError::RequestIdsExhausted)?;
                }
                if !message.reply_cap.is_none() {
                    message.reply_cap = match parent {
                        None => shared
                            .caps
                            .reissue_for(message.reply_cap, child)
                            .map_err(|_| SpawnError::InvalidCapability)?,
                        Some(holder) => {
                            match shared.caps.delegate(message.reply_cap, holder, child) {
                                Ok(granted) => {
                                    record_security_event(
                                        shared,
                                        &crate::scheduler::sandbox::SecurityEvent::CapabilityDelegated {
                                            from: holder.as_u64(),
                                            to: child.as_u64(),
                                        },
                                    );
                                    granted
                                }
                                Err(_) => return Err(SpawnError::InvalidCapability),
                            }
                        }
                    };
                }
                Ok(())
            },
        )?;
        out.push(granted);
    }
    Ok(out)
}

/// A `Send + Sync`, freely cloneable capability to spawn flows into a
/// [`Runtime`], detached from the `Runtime` value itself. Exists because
/// [`crate::scheduler::supervisor::Supervisor`] needs to respawn flows from a
/// background monitor thread whose lifetime isn't tied to the `Runtime`
/// object's own (which owns non-`Sync` `JoinHandle`s for its workers).
#[derive(Clone)]
pub struct RuntimeSpawner {
    pub(crate) shared: Arc<Shared>,
    pub(crate) chunk: Arc<Chunk>,
    pub(crate) natives: Arc<NativeTable>,
}

impl RuntimeSpawner {
    pub fn spawn(
        &self,
        function: u32,
        args: &[Value],
        restart_policy: RestartPolicy,
    ) -> Result<FlowHandle, SpawnError> {
        spawn_on(
            &self.shared,
            &self.chunk,
            &self.natives,
            function,
            args,
            restart_policy,
            None,
            None,
            None,
            None,
        )
    }

    /// Host spawn with [`RootAuthorityPolicy::Untrusted`].
    pub fn spawn_untrusted(
        &self,
        function: u32,
        args: &[Value],
        restart_policy: RestartPolicy,
    ) -> Result<FlowHandle, SpawnError> {
        spawn_on(
            &self.shared,
            &self.chunk,
            &self.natives,
            function,
            args,
            restart_policy,
            None,
            None,
            None,
            Some(RootAuthorityPolicy::Untrusted),
        )
    }

    pub(crate) fn spawn_linked(
        &self,
        function: u32,
        args: &[Value],
        restart_policy: RestartPolicy,
        supervisor: SupervisorLink,
    ) -> Result<FlowHandle, SpawnError> {
        spawn_on(
            &self.shared,
            &self.chunk,
            &self.natives,
            function,
            args,
            restart_policy,
            Some(supervisor),
            None,
            None,
            None,
        )
    }

    pub fn metrics(&self) -> RuntimeMetricsSnapshot {
        self.shared.metrics.snapshot()
    }

    pub(crate) fn request_kill(
        &self,
        id: FlowId,
        reason: crate::scheduler::monitor::FlowExitReason,
    ) {
        crate::scheduler::finalize::request_kill(&self.shared, id, reason);
    }
}