1use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
2use std::sync::{Arc, Condvar, Mutex};
3use std::thread::JoinHandle;
4
5use crate::bytecode::{Cap, CapRights, CapTarget, Chunk, NativeMask, Value};
6use crate::vm::{NativeGate, NativeTable, Vm};
7use crossbeam_deque::{Injector, Stealer, Worker as LocalDeque};
8
9use super::directory::Directory;
10use super::error::SpawnError;
11use super::finalize::finalize_flow;
12use super::handle::FlowHandle;
13use super::mailbox::{Delivery, Mailbox, MailboxConfig, MailboxFullReason};
14use super::metrics::{RuntimeMetrics, RuntimeMetricsSnapshot};
15use super::monitor::FlowExitReason;
16use super::process::{Flow, FlowId, FlowOutcome, RestartPolicy};
17use super::supervisor::SupervisorLink;
18use super::timer::TimerWheel;
19use super::worker;
20
21pub const DEFAULT_QUANTUM: u32 = 10_000;
29
30#[derive(Clone, Debug)]
33pub struct RuntimeConfig {
34 pub workers: usize,
39 pub quantum: u32,
42 pub mailbox: MailboxConfig,
46 pub max_flows: u32,
49 pub trust: crate::bytecode::TrustLevel,
52 pub output: Arc<dyn crate::OutputSink>,
55 pub quota: super::quota::QuotaConfig,
57 #[cfg(feature = "jit")]
59 pub jit: JitConfig,
60}
61
62#[cfg(feature = "jit")]
64#[derive(Clone, Debug)]
65pub struct JitConfig {
66 pub enabled: bool,
68 pub hot_threshold: u32,
70}
71
72#[cfg(feature = "jit")]
73impl Default for JitConfig {
74 fn default() -> Self {
75 JitConfig {
76 enabled: false,
77 hot_threshold: crate::jit::HOT_THRESHOLD,
78 }
79 }
80}
81
82impl Default for RuntimeConfig {
83 fn default() -> Self {
84 RuntimeConfig {
85 workers: num_cpus::get().max(1),
86 quantum: DEFAULT_QUANTUM,
87 mailbox: MailboxConfig::DEFAULT,
88 max_flows: 0,
89 trust: crate::bytecode::TrustLevel::Untrusted,
90 output: Arc::new(crate::output::NullSink),
91 quota: super::quota::QuotaConfig::default(),
92 #[cfg(feature = "jit")]
93 jit: JitConfig::default(),
94 }
95 }
96}
97
98pub struct Shared {
105 pub(crate) injector: Injector<Box<Flow>>,
106 pub(crate) stealers: Vec<Stealer<Box<Flow>>>,
107 pub(crate) directory: Directory,
109 pub(crate) caps: super::capability::CapTable,
111 pub(crate) timer: Arc<TimerWheel>,
112 pub(crate) notify: (Mutex<()>, Condvar),
113 pub(crate) metrics: RuntimeMetrics,
114 pub(crate) shutdown: AtomicBool,
115 pub(crate) quantum: u32,
116 pub(crate) mailbox: MailboxConfig,
117 pub(crate) max_flows: u32,
118 pub(crate) quota: super::quota::QuotaConfig,
119 pub(crate) quotas: super::quota::QuotaTable,
120 pub(crate) monitors: super::monitor::MonitorStore,
121 pub(crate) links: super::link::LinkStore,
122 pub(crate) registry: super::registry::RegistryStore,
123 pub(crate) kill_signals: super::finalize::KillSignals,
124 pub(crate) waiting_send_at: super::finalize::WaitingSendIndex,
125 pub(crate) ask_waits: super::finalize::AskWaitIndex,
126 pub(crate) host_next_request_id: AtomicU64,
129 #[cfg(feature = "jit")]
131 pub(crate) jit: Option<std::sync::Arc<crate::jit::JitRuntime>>,
132}
133
134pub struct Runtime {
145 shared: Arc<Shared>,
146 chunk: Arc<Chunk>,
147 natives: Arc<NativeTable>,
148 workers: Vec<JoinHandle<()>>,
149 timer_thread: Option<JoinHandle<()>>,
150 trust: crate::bytecode::TrustLevel,
151}
152
153impl Runtime {
154 pub fn new(chunk: Chunk) -> Result<Self, SpawnError> {
162 Self::with_config(chunk, RuntimeConfig::default())
163 }
164
165 pub fn with_natives(chunk: Chunk, natives: Arc<NativeTable>) -> Result<Self, SpawnError> {
168 Self::with_natives_and_config(chunk, natives, RuntimeConfig::default())
169 }
170
171 pub fn with_config(chunk: Chunk, config: RuntimeConfig) -> Result<Self, SpawnError> {
172 Self::with_natives_and_config(chunk, NativeTable::empty(), config)
173 }
174
175 pub fn with_std_natives_and_config(
178 chunk: Chunk,
179 config: RuntimeConfig,
180 ) -> Result<Self, SpawnError> {
181 Self::with_natives_and_config(
182 chunk,
183 crate::std_native_table_with(Arc::clone(&config.output)),
184 config,
185 )
186 }
187
188 pub fn with_natives_and_config(
196 chunk: Chunk,
197 natives: Arc<NativeTable>,
198 config: RuntimeConfig,
199 ) -> Result<Self, SpawnError> {
200 crate::bytecode::verify_with(
201 &chunk,
202 crate::bytecode::VerifyConfig {
203 trust: config.trust,
204 },
205 )
206 .map_err(SpawnError::VerifyFailed)?;
207 let chunk = Arc::new(chunk);
208 let workers_n = config.workers.max(1);
209
210 let locals: Vec<LocalDeque<Box<Flow>>> =
211 (0..workers_n).map(|_| LocalDeque::new_fifo()).collect();
212 let stealers: Vec<Stealer<Box<Flow>>> = locals.iter().map(|l| l.stealer()).collect();
213
214 #[cfg(feature = "jit")]
215 let jit = if config.jit.enabled {
216 Some(super::jit::new_runtime(chunk.clone(), config.jit.hot_threshold))
217 } else {
218 None
219 };
220
221 let shared = Arc::new(Shared {
222 injector: Injector::new(),
223 stealers,
224 directory: Directory::new(),
225 caps: super::capability::CapTable::new(),
226 timer: TimerWheel::new(),
227 notify: (Mutex::new(()), Condvar::new()),
228 metrics: RuntimeMetrics::default(),
229 shutdown: AtomicBool::new(false),
230 quantum: config.quantum,
231 mailbox: config.mailbox,
232 max_flows: config.max_flows,
233 quota: config.quota,
234 quotas: super::quota::QuotaTable::new(),
235 monitors: super::monitor::MonitorStore::new(),
236 links: super::link::LinkStore::new(),
237 registry: super::registry::RegistryStore::new(),
238 kill_signals: super::finalize::KillSignals::new(),
239 waiting_send_at: super::finalize::WaitingSendIndex::new(),
240 ask_waits: super::finalize::AskWaitIndex::new(),
241 host_next_request_id: AtomicU64::new(1),
242 #[cfg(feature = "jit")]
243 jit,
244 });
245
246 let mut workers = Vec::with_capacity(workers_n);
247 for local in locals {
248 let shared = shared.clone();
249 let handle = std::thread::Builder::new()
250 .name("byteflow-worker".into())
251 .spawn(move || worker::run_worker(shared, local))
252 .map_err(|e| SpawnError::ThreadSpawnFailed(e.to_string()))?;
253 workers.push(handle);
254 }
255
256 let shared_timer = shared.clone();
257 let timer_thread = std::thread::Builder::new()
258 .name("byteflow-timer".into())
259 .spawn(move || {
260 shared_timer.timer.clone().drive(&shared_timer)
261 })
262 .map_err(|e| SpawnError::ThreadSpawnFailed(e.to_string()))?;
263
264 Ok(Runtime {
265 shared,
266 chunk,
267 natives,
268 workers,
269 timer_thread: Some(timer_thread),
270 trust: config.trust,
271 })
272 }
273
274 pub fn spawn(&self, function: u32, args: &[Value]) -> Result<FlowHandle, SpawnError> {
279 spawn_on(
280 &self.shared,
281 &self.chunk,
282 &self.natives,
283 function,
284 args,
285 RestartPolicy::Never,
286 None,
287 None,
288 None,
289 )
290 }
291
292 pub fn spawner(&self) -> RuntimeSpawner {
296 RuntimeSpawner { shared: self.shared.clone(), chunk: self.chunk.clone(), natives: self.natives.clone() }
297 }
298
299 pub fn supervisor(&self) -> Result<super::supervisor::Supervisor, SpawnError> {
302 super::supervisor::Supervisor::new(self.spawner())
303 }
304
305 pub fn function_index(&self, name: &str) -> Option<u32> {
309 self.chunk.functions.iter().position(|f| f.name == name).map(|i| i as u32)
310 }
311
312 pub fn metrics(&self) -> RuntimeMetricsSnapshot {
313 self.shared.metrics.snapshot()
314 }
315
316 pub fn live_flows(&self) -> usize {
320 self.shared.directory.len()
321 }
322
323 pub fn worker_count(&self) -> usize {
324 self.workers.len()
325 }
326
327 pub fn send(&self, target: FlowId, message: Value) -> Result<(), SendError> {
340 let Some(msg) = message.as_message().cloned() else {
341 return Err(SendError::NotAHop {
342 got: message.type_name(),
343 });
344 };
345 let mailbox = match self.shared.directory.lookup(target) {
346 Ok(Some(m)) => m,
347 Ok(None) => return Err(SendError::NoSuchFlow(target)),
348 Err(e) => {
349 super::error::report_fault(e);
350 return Err(SendError::Unavailable);
351 }
352 };
353 let stamped = match worker::authenticate_host_outgoing_message(&self.shared, target, msg) {
354 Ok(m) => Value::Message(m),
355 Err(_) => return Err(SendError::Capability),
356 };
357 match mailbox.push(stamped.clone()) {
358 Ok(Ok(Delivery::Queued | Delivery::QueuedDropOldest | Delivery::DroppedNewest)) => {
359 Ok(())
360 }
361 Ok(Ok(Delivery::Handoff(flow))) => {
362 let _ = self.shared.ask_waits.remove_asker(flow.id);
363 match flow.last_receive_dest {
364 Some(dest) => {
365 let Some(flow) =
366 super::finalize::resume_or_fail(&self.shared, flow, dest, stamped)
367 else {
368 return Err(SendError::Unavailable);
369 };
370 self.shared.injector.push(flow);
371 wake_workers(&self.shared);
372 Ok(())
373 }
374 None => {
375 super::error::report_fault(super::error::RuntimeError::PoisonedLock(
376 "Runtime::send handoff missing dest register",
377 ));
378 finalize_flow(
379 &self.shared,
380 *flow,
381 FlowOutcome::Failed("handoff missing dest register".into()),
382 FlowExitReason::Fault,
383 );
384 Err(SendError::Unavailable)
385 }
386 }
387 }
388 Ok(Err(full)) => Err(SendError::MailboxFull {
389 flow: target,
390 reason: full.reason(),
391 }),
392 Err(e) => {
393 super::error::report_fault(e);
394 Err(SendError::Unavailable)
395 }
396 }
397 }
398
399 fn require_live(&self, id: FlowId) -> Result<(), super::error::LifecycleError> {
400 match self.shared.directory.lookup(id) {
401 Ok(Some(_)) => Ok(()),
402 Ok(None) => Err(super::error::LifecycleError::NoSuchFlow(id)),
403 Err(e) => Err(self.unavailable(e)),
404 }
405 }
406
407 fn unavailable(&self, err: super::error::RuntimeError) -> super::error::LifecycleError {
408 super::error::report_fault(err);
409 super::error::LifecycleError::Unavailable
410 }
411
412 pub fn mint_cap(&self, flow: FlowId) -> Result<crate::bytecode::CapId, super::error::LifecycleError> {
414 self.require_live(flow)?;
415 self.shared
416 .caps
417 .mint(flow, flow, super::capability::CapRights::ADDRESSING)
418 .map_err(|e| self.unavailable(e))
419 }
420
421 pub fn grant_cap(
423 &self,
424 holder: FlowId,
425 target: FlowId,
426 ) -> Result<crate::bytecode::CapId, super::error::LifecycleError> {
427 self.require_live(holder)?;
428 self.require_live(target)?;
429 self.shared
430 .caps
431 .mint(holder, target, super::capability::CapRights::ADDRESSING)
432 .map_err(|e| self.unavailable(e))
433 }
434
435 pub fn monitor(
439 &self,
440 owner: FlowId,
441 target: FlowId,
442 ) -> Result<super::monitor::MonitorRef, super::error::LifecycleError> {
443 if owner == target {
444 return Err(super::error::LifecycleError::SelfRelation);
445 }
446 self.require_live(owner)?;
447 self.require_live(target)?;
448 let mon = self
449 .shared
450 .monitors
451 .create(owner, target)
452 .map_err(|e| self.unavailable(e))?;
453 if self.require_live(target).is_err() {
456 let _ = self.shared.monitors.remove_owned(owner, mon);
457 super::finalize::deliver_down(
458 &self.shared,
459 super::monitor::DownEvent {
460 monitor: mon,
461 owner,
462 target,
463 reason: super::monitor::FlowExitReason::Fault,
464 },
465 );
466 }
467 Ok(mon)
468 }
469
470 pub fn demonitor(
472 &self,
473 owner: FlowId,
474 monitor: super::monitor::MonitorRef,
475 ) -> Result<(), super::error::LifecycleError> {
476 self.require_live(owner)?;
477 match self.shared.monitors.remove_owned(owner, monitor) {
478 Ok(inner) => inner,
479 Err(e) => Err(self.unavailable(e)),
480 }
481 }
482
483 pub fn link(
485 &self,
486 a: FlowId,
487 b: FlowId,
488 ) -> Result<super::link::LinkId, super::error::LifecycleError> {
489 if a == b {
490 return Err(super::error::LifecycleError::SelfRelation);
491 }
492 self.require_live(a)?;
493 self.require_live(b)?;
494 match self.shared.links.link(a, b) {
495 Ok(inner) => inner,
496 Err(e) => Err(self.unavailable(e)),
497 }
498 }
499
500 pub fn unlink(
502 &self,
503 owner: FlowId,
504 link: super::link::LinkId,
505 ) -> Result<(), super::error::LifecycleError> {
506 self.require_live(owner)?;
507 match self.shared.links.unlink_owned(owner, link) {
508 Ok(inner) => inner,
509 Err(e) => Err(self.unavailable(e)),
510 }
511 }
512
513 pub fn register_name(
515 &self,
516 name: &str,
517 cap: crate::bytecode::CapId,
518 ) -> Result<(), super::error::LifecycleError> {
519 let entry = match self.shared.caps.lookup(cap) {
520 Ok(Some(e)) => e,
521 Ok(None) => return Err(super::error::LifecycleError::InvalidCapability),
522 Err(e) => return Err(self.unavailable(e)),
523 };
524 let target = match entry.target() {
525 Some(id) => id,
526 None => return Err(super::error::LifecycleError::InvalidCapability),
527 };
528 self.require_live(target)?;
529 match self.shared.registry.register(
530 super::registry::RegistryName::from(name),
531 cap,
532 target,
533 ) {
534 Ok(inner) => inner,
535 Err(e) => Err(self.unavailable(e)),
536 }
537 }
538
539 pub fn whereis(&self, name: &str) -> Result<Option<crate::bytecode::CapId>, super::error::LifecycleError> {
541 self.shared
542 .registry
543 .whereis(name)
544 .map_err(|e| self.unavailable(e))
545 }
546
547 pub fn kill(&self, id: FlowId) -> Result<(), super::error::LifecycleError> {
550 self.require_live(id)?;
551 super::finalize::request_kill(&self.shared, id, super::monitor::FlowExitReason::Killed);
552 Ok(())
553 }
554
555 pub fn mint_admin_cap(
557 &self,
558 holder: FlowId,
559 ) -> Result<crate::bytecode::CapId, super::error::LifecycleError> {
560 self.require_live(holder)?;
561 let cap = crate::bytecode::Cap::root(
562 crate::bytecode::CapTarget::Scheduler,
563 CapRights::ADMIN,
564 None,
565 self.shared.caps.scheduler_cell().as_ref(),
566 );
567 self.shared
568 .caps
569 .grant(holder, cap)
570 .map_err(|e| self.unavailable(e))
571 }
572
573 pub fn admin_kill(
575 &self,
576 holder: FlowId,
577 cap: crate::bytecode::CapId,
578 target: FlowId,
579 ) -> Result<(), super::error::LifecycleError> {
580 self.require_admin(holder, cap)?;
581 self.kill(target)
582 }
583
584 pub fn admin_top_up_cpu(
586 &self,
587 holder: FlowId,
588 cap: crate::bytecode::CapId,
589 target: FlowId,
590 extra: i64,
591 ) -> Result<(), super::error::LifecycleError> {
592 self.require_admin(holder, cap)?;
593 let quota = match self.shared.quotas.get(target) {
594 Ok(Some(q)) => q,
595 Ok(None) => return Err(super::error::LifecycleError::NoSuchFlow(target)),
596 Err(e) => return Err(self.unavailable(e)),
597 };
598 quota.top_up_cpu(extra);
599 Ok(())
600 }
601
602 pub fn admin_top_up_mem(
604 &self,
605 holder: FlowId,
606 cap: crate::bytecode::CapId,
607 target: FlowId,
608 extra: usize,
609 ) -> Result<(), super::error::LifecycleError> {
610 self.require_admin(holder, cap)?;
611 let quota = match self.shared.quotas.get(target) {
612 Ok(Some(q)) => q,
613 Ok(None) => return Err(super::error::LifecycleError::NoSuchFlow(target)),
614 Err(e) => return Err(self.unavailable(e)),
615 };
616 quota.top_up_mem(extra);
617 Ok(())
618 }
619
620 pub fn admin_top_up_send(
622 &self,
623 holder: FlowId,
624 cap: crate::bytecode::CapId,
625 target: FlowId,
626 extra: i64,
627 ) -> Result<(), super::error::LifecycleError> {
628 self.require_admin(holder, cap)?;
629 let quota = match self.shared.quotas.get(target) {
630 Ok(Some(q)) => q,
631 Ok(None) => return Err(super::error::LifecycleError::NoSuchFlow(target)),
632 Err(e) => return Err(self.unavailable(e)),
633 };
634 quota.top_up_send(extra);
635 Ok(())
636 }
637
638 fn require_admin(
639 &self,
640 holder: FlowId,
641 cap: crate::bytecode::CapId,
642 ) -> Result<(), super::error::LifecycleError> {
643 let entry = match self.shared.caps.resolve(cap, holder, CapRights::ADMIN) {
644 Ok(e) => e,
645 Err(_) => return Err(super::error::LifecycleError::InvalidCapability),
646 };
647 super::link_admin::check_admin(&entry.cap, self.shared.caps.scheduler_cell().as_ref())
648 .map_err(|_| super::error::LifecycleError::InvalidCapability)
649 }
650
651 pub fn unregister_name(&self, name: &str) -> Result<bool, super::error::LifecycleError> {
653 self.shared
654 .registry
655 .unregister(name)
656 .map_err(|e| self.unavailable(e))
657 }
658
659 pub fn reload_chunk(&mut self, chunk: Chunk) -> Result<(), SpawnError> {
663 crate::bytecode::verify_with(
664 &chunk,
665 crate::bytecode::VerifyConfig {
666 trust: self.trust,
667 },
668 )
669 .map_err(SpawnError::VerifyFailed)?;
670 let chunk = Arc::new(chunk);
671 self.chunk = chunk.clone();
672 #[cfg(feature = "jit")]
673 if let Some(jit) = &self.shared.jit {
674 jit.reload(chunk);
675 }
676 Ok(())
677 }
678
679 fn request_shutdown(&self) {
682 self.shared.shutdown.store(true, Ordering::Release);
683 self.shared.timer.shutdown();
684 let (lock, cvar) = &self.shared.notify;
685 match super::sync_lock::lock(lock, "Runtime::request_shutdown") {
686 Ok(_g) => cvar.notify_all(),
687 Err(e) => super::error::report_fault(e),
688 }
689 }
690
691 pub fn shutdown(mut self) {
698 self.request_shutdown();
699 for w in self.workers.drain(..) {
700 let _ = w.join();
701 }
702 if let Some(t) = self.timer_thread.take() {
703 let _ = t.join();
704 }
705 }
706}
707
708impl Drop for Runtime {
709 fn drop(&mut self) {
710 if !self.shared.shutdown.load(Ordering::Acquire) {
711 self.request_shutdown();
712 }
713 }
714}
715
716pub fn flow_id_from_u64(raw: u64) -> FlowId {
720 FlowId(raw)
721}
722
723#[derive(Debug, Clone, PartialEq, Eq)]
725pub enum SendError {
726 NoSuchFlow(FlowId),
727 NotAHop { got: &'static str },
729 MailboxFull {
733 flow: FlowId,
734 reason: MailboxFullReason,
735 },
736 Capability,
738 Unavailable,
740}
741
742impl std::fmt::Display for SendError {
743 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
744 match self {
745 SendError::NoSuchFlow(id) => write!(f, "no live flow {id}"),
746 SendError::NotAHop { got } => {
747 write!(f, "atomic hop requires Value::Message, got {got}")
748 }
749 SendError::MailboxFull { flow, reason } => {
750 write!(f, "mailbox full for {flow} ({reason})")
751 }
752 SendError::Capability => {
753 write!(f, "host send could not reissue a capability in the hop")
754 }
755 SendError::Unavailable => write!(f, "runtime table unavailable (poisoned lock)"),
756 }
757 }
758}
759
760impl std::error::Error for SendError {}
761
762pub(crate) struct BytecodeSpawn<'a> {
765 pub authority: &'a Cap,
766 pub cell: &'a crate::bytecode::RevocationCell,
767 pub quota: &'a super::quota::FlowQuota,
768 pub requested_rights: CapRights,
769}
770
771pub(crate) fn spawn_on(
780 shared: &Arc<Shared>,
781 chunk: &Arc<Chunk>,
782 natives: &Arc<NativeTable>,
783 function: u32,
784 args: &[Value],
785 restart_policy: RestartPolicy,
786 supervisor: Option<SupervisorLink>,
787 parent: Option<FlowId>,
788 bytecode: Option<BytecodeSpawn<'_>>,
789) -> Result<FlowHandle, SpawnError> {
790 if shared.max_flows > 0 {
791 let current = shared.directory.len();
792 if current >= shared.max_flows as usize {
793 return Err(SpawnError::FlowLimit {
794 current,
795 max: shared.max_flows,
796 });
797 }
798 }
799 let id = match super::process::try_next_flow_id() {
800 Ok(id) => id,
801 Err(super::error::RuntimeError::FlowIdExhausted) => {
802 return Err(SpawnError::FlowIdExhausted)
803 }
804 Err(_) => return Err(SpawnError::Unavailable),
805 };
806 let cell = shared
807 .caps
808 .bind_flow(id)
809 .map_err(|_| SpawnError::Unavailable)?;
810 let authority = match bytecode {
811 None => Cap::root(
812 CapTarget::Flow(id.as_u64()),
813 CapRights::ROOT,
814 Some(NativeMask::full(natives.len())),
815 cell.as_ref(),
816 ),
817 Some(ctx) => super::spawn::exec_spawn_authority(
818 ctx.authority,
819 ctx.cell,
820 ctx.quota,
821 id.as_u64(),
822 ctx.requested_rights,
823 None,
824 cell.as_ref(),
825 )
826 .map_err(SpawnError::from)?,
827 };
828 let args = grant_caps_in_args(shared, parent, id, args)?;
829 let gate = NativeGate::from_authority(
830 &authority,
831 Arc::clone(&cell),
832 shared.caps.native_cell(),
833 natives.len(),
834 );
835 let quota = Arc::new(super::quota::FlowQuota::from_config(shared.quota));
836 let mut vm = Vm::with_native_gate(chunk.clone(), natives.clone(), gate, function, args.as_slice())?;
837 vm.set_quota(Arc::clone("a))?;
838 let mailbox = Arc::new(Mailbox::with_config(shared.mailbox));
839 if let Err(e) = shared.directory.register(id, mailbox.clone()) {
840 super::error::report_fault(e);
841 return Err(SpawnError::Unavailable);
842 }
843 if let Err(e) = shared.quotas.insert(id, Arc::clone("a)) {
844 super::error::report_fault(e);
845 return Err(SpawnError::Unavailable);
846 }
847 let (tx, rx) = super::oneshot::channel();
848 let mut flow = Box::new(Flow::new(id, vm, mailbox, restart_policy, tx));
849 flow.authority = authority;
850 flow.cell = cell;
851 flow.quota = quota;
852 flow.supervisor = supervisor;
853 RuntimeMetrics::inc(&shared.metrics.processes_spawned);
854 shared.injector.push(flow);
855 wake_workers(shared);
856 Ok(FlowHandle { id, receiver: rx })
857}
858
859fn grant_caps_in_args(
860 shared: &Shared,
861 parent: Option<FlowId>,
862 child: FlowId,
863 args: &[Value],
864) -> Result<Vec<Value>, SpawnError> {
865 let mut out = Vec::with_capacity(args.len());
866 for arg in args {
867 match arg {
868 Value::Cap(id) => {
869 let granted = match parent {
870 None => shared.caps.reissue_for(*id, child),
871 Some(p) => shared.caps.delegate(*id, p, child),
872 };
873 match granted {
874 Ok(cap) => out.push(Value::Cap(cap)),
875 Err(_) => return Err(SpawnError::InvalidCapability),
876 }
877 }
878 other => out.push(other.clone()),
879 }
880 }
881 Ok(out)
882}
883
884pub(crate) fn wake_workers(shared: &Shared) {
885 let (lock, cvar) = &shared.notify;
886 match super::sync_lock::lock(lock, "wake_workers") {
887 Ok(_g) => cvar.notify_one(),
888 Err(e) => super::error::report_fault(e),
889 }
890}
891
892#[derive(Clone)]
898pub struct RuntimeSpawner {
899 pub(crate) shared: Arc<Shared>,
900 pub(crate) chunk: Arc<Chunk>,
901 pub(crate) natives: Arc<NativeTable>,
902}
903
904impl RuntimeSpawner {
905 pub fn spawn(
906 &self,
907 function: u32,
908 args: &[Value],
909 restart_policy: RestartPolicy,
910 ) -> Result<FlowHandle, SpawnError> {
911 spawn_on(
912 &self.shared,
913 &self.chunk,
914 &self.natives,
915 function,
916 args,
917 restart_policy,
918 None,
919 None,
920 None,
921 )
922 }
923
924 pub(crate) fn spawn_linked(
925 &self,
926 function: u32,
927 args: &[Value],
928 restart_policy: RestartPolicy,
929 supervisor: SupervisorLink,
930 ) -> Result<FlowHandle, SpawnError> {
931 spawn_on(
932 &self.shared,
933 &self.chunk,
934 &self.natives,
935 function,
936 args,
937 restart_policy,
938 Some(supervisor),
939 None,
940 None,
941 )
942 }
943
944 pub fn metrics(&self) -> RuntimeMetricsSnapshot {
945 self.shared.metrics.snapshot()
946 }
947
948 pub(crate) fn request_kill(&self, id: FlowId, reason: super::monitor::FlowExitReason) {
949 super::finalize::request_kill(&self.shared, id, reason);
950 }
951}
952
953#[cfg(test)]
954mod tests {
955 use super::*;
956 use crate::bytecode::{builder::ChunkBuilder, Opcode, Value};
957 use crate::scheduler::FlowOutcome;
958 use std::time::Duration;
959
960 fn add_chunk() -> Chunk {
961 let mut b = ChunkBuilder::new("test");
962 b.begin_function("main", 0, 2);
963 b.emit_load_imm(0, 41);
964 b.emit_load_imm(1, 1);
965 b.emit_binop(Opcode::Add, 0, 0, 1);
966 b.emit_return(0);
967 b.finish()
968 }
969
970 fn sleep_then_return_chunk(millis: i32) -> Chunk {
973 let mut b = ChunkBuilder::new("test");
974 b.begin_function("main", 0, 2);
975 b.emit_load_imm(0, millis);
976 b.emit_sleep(0);
977 b.emit_load_imm(0, 7);
978 b.emit_return(0);
979 b.finish()
980 }
981
982 #[test]
986 fn polling_and_bounded_waits_never_commit_the_host_thread() -> Result<(), Box<dyn std::error::Error>>
987 {
988 const FLOW_SLEEP: i32 = 150;
989 let rt = Runtime::with_config(
990 sleep_then_return_chunk(FLOW_SLEEP),
991 RuntimeConfig {
992 workers: 1,
993 quantum: 1_000,
994 mailbox: MailboxConfig::DEFAULT,
995 ..Default::default()
996 },
997 )?;
998 let handle = rt.spawn(0, &[])?;
999
1000 if let Some(outcome) = handle.try_join() {
1003 rt.shutdown();
1004 return Err(format!("try_join answered too early: {outcome:?}").into());
1005 }
1006
1007 if let Some(outcome) = handle.join_timeout(Duration::from_millis(20)) {
1010 rt.shutdown();
1011 return Err(format!("join_timeout answered too early: {outcome:?}").into());
1012 }
1013
1014 let outcome = handle.join_timeout(Duration::from_secs(10));
1017 rt.shutdown();
1018 match outcome {
1019 Some(FlowOutcome::Completed(Value::Int(7))) => Ok(()),
1020 other => Err(format!("unexpected outcome: {other:?}").into()),
1021 }
1022 }
1023
1024 #[test]
1025 fn spawn_and_join_add() -> Result<(), Box<dyn std::error::Error>> {
1026 let rt = Runtime::with_config(
1027 add_chunk(),
1028 RuntimeConfig {
1029 workers: 1,
1030 quantum: 1_000,
1031 mailbox: MailboxConfig::DEFAULT,
1032 ..Default::default()
1033 },
1034 )?;
1035 let outcome = rt.spawn(0, &[])?.join();
1036 rt.shutdown();
1037 match outcome {
1038 FlowOutcome::Completed(Value::Int(42)) => Ok(()),
1039 other => Err(format!("unexpected outcome: {other:?}").into()),
1040 }
1041 }
1042
1043 fn receive_forever_chunk() -> Chunk {
1044 let mut b = ChunkBuilder::new("recv");
1045 b.begin_function("main", 0, 1);
1046 b.emit_receive(0);
1047 b.emit_return(0);
1048 b.finish()
1049 }
1050
1051 #[test]
1052 fn kill_parked_flow_joins_failed() -> Result<(), Box<dyn std::error::Error>> {
1053 let rt = Runtime::with_config(
1054 receive_forever_chunk(),
1055 RuntimeConfig {
1056 workers: 1,
1057 quantum: 1_000,
1058 mailbox: MailboxConfig::DEFAULT,
1059 ..Default::default()
1060 },
1061 )?;
1062 let handle = rt.spawn(0, &[])?;
1063 rt.kill(handle.id())?;
1064 let outcome = handle.join();
1065 rt.shutdown();
1066 assert!(
1067 matches!(outcome, FlowOutcome::Failed(_)),
1068 "kill must fail the joiner, got {outcome:?}"
1069 );
1070 Ok(())
1071 }
1072
1073 #[test]
1074 fn max_flows_rejects_extra_spawn() -> Result<(), Box<dyn std::error::Error>> {
1075 let rt = Runtime::with_config(
1076 receive_forever_chunk(),
1077 RuntimeConfig {
1078 workers: 1,
1079 quantum: 1_000,
1080 mailbox: MailboxConfig::DEFAULT,
1081 max_flows: 1,
1082 ..Default::default()
1083 },
1084 )?;
1085 let first = rt.spawn(0, &[])?;
1086 let second = rt.spawn(0, &[]);
1087 rt.kill(first.id())?;
1088 let _ = first.join();
1089 rt.shutdown();
1090 match second {
1091 Err(SpawnError::FlowLimit { current, max }) => {
1092 assert_eq!(current, 1);
1093 assert_eq!(max, 1);
1094 Ok(())
1095 }
1096 other => Err(format!(
1097 "expected FlowLimit, got {}",
1098 match &other {
1099 Ok(_) => "Ok(handle)".into(),
1100 Err(e) => format!("Err({e})"),
1101 }
1102 )
1103 .into()),
1104 }
1105 }
1106
1107 #[cfg(feature = "jit")]
1108 #[test]
1109 fn runtime_with_jit_enabled_completes_add() -> Result<(), Box<dyn std::error::Error>> {
1110 use crate::JitConfig;
1111
1112 let rt = Runtime::with_config(
1113 add_chunk(),
1114 RuntimeConfig {
1115 workers: 1,
1116 quantum: 1_000,
1117 mailbox: MailboxConfig::DEFAULT,
1118 jit: JitConfig {
1119 enabled: true,
1120 hot_threshold: 1,
1121 },
1122 ..Default::default()
1123 },
1124 )?;
1125 let outcome = rt.spawn(0, &[])?.join();
1126 rt.shutdown();
1127 match outcome {
1128 FlowOutcome::Completed(Value::Int(42)) => Ok(()),
1129 other => Err(format!("unexpected outcome: {other:?}").into()),
1130 }
1131 }
1132}