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};
7
8use super::directory::Directory;
9use super::error::SpawnError;
10use super::finalize::finalize_flow;
11use super::handle::FlowHandle;
12use super::mailbox::{Delivery, Mailbox, MailboxConfig, MailboxFullReason};
13use super::metrics::{RuntimeMetrics, RuntimeMetricsSnapshot};
14use super::monitor::FlowExitReason;
15use super::process::{Flow, FlowId, FlowOutcome, RestartPolicy};
16use super::runqueue::{Injector, Stealer, Worker as LocalDeque};
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 max_runtime_bytes: usize,
54 pub trust: crate::bytecode::TrustLevel,
57 pub output: Arc<dyn crate::OutputSink>,
60 pub quota: super::quota::QuotaConfig,
62 #[cfg(feature = "jit")]
64 pub jit: JitConfig,
65}
66
67#[cfg(feature = "jit")]
69#[derive(Clone, Debug)]
70pub struct JitConfig {
71 pub enabled: bool,
73 pub hot_threshold: u32,
75}
76
77#[cfg(feature = "jit")]
78impl Default for JitConfig {
79 fn default() -> Self {
80 JitConfig {
81 enabled: false,
82 hot_threshold: crate::jit::HOT_THRESHOLD,
83 }
84 }
85}
86
87fn default_worker_count() -> usize {
89 match std::thread::available_parallelism() {
90 Ok(n) => n.get().max(1),
91 Err(_) => 1,
92 }
93}
94
95impl Default for RuntimeConfig {
96 fn default() -> Self {
97 RuntimeConfig {
98 workers: default_worker_count(),
99 quantum: DEFAULT_QUANTUM,
100 mailbox: MailboxConfig::DEFAULT,
101 max_flows: 0,
102 max_runtime_bytes: 256 * 1024 * 1024,
103 trust: crate::bytecode::TrustLevel::Untrusted,
104 output: Arc::new(crate::output::NullSink),
105 quota: super::quota::QuotaConfig::default(),
106 #[cfg(feature = "jit")]
107 jit: JitConfig::default(),
108 }
109 }
110}
111
112pub struct Shared {
119 pub(crate) injector: Injector<Box<Flow>>,
120 pub(crate) stealers: Vec<Stealer<Box<Flow>>>,
121 pub(crate) directory: Directory,
123 pub(crate) caps: super::capability::CapTable,
125 pub(crate) timer: Arc<TimerWheel>,
126 pub(crate) notify: (Mutex<()>, Condvar),
127 pub(crate) metrics: RuntimeMetrics,
128 pub(crate) shutdown: AtomicBool,
129 pub(crate) quantum: u32,
130 pub(crate) mailbox: MailboxConfig,
131 pub(crate) flow_limit: super::flow_limit::FlowLimit,
133 pub(crate) memory: Arc<crate::MemoryBudget>,
134 pub(crate) quota: super::quota::QuotaConfig,
135 pub(crate) quotas: super::quota::QuotaTable,
136 pub(crate) monitors: super::monitor::MonitorStore,
137 pub(crate) links: super::link::LinkStore,
138 pub(crate) registry: super::registry::RegistryStore,
139 pub(crate) kill_signals: super::finalize::KillSignals,
140 pub(crate) waiting_send_at: super::finalize::WaitingSendIndex,
141 pub(crate) ask_waits: super::finalize::AskWaitIndex,
142 pub(crate) host_next_request_id: AtomicU64,
145 #[cfg(feature = "jit")]
147 pub(crate) jit: Option<std::sync::Arc<crate::jit::JitRuntime>>,
148}
149
150pub struct Runtime {
161 shared: Arc<Shared>,
162 chunk: Arc<Chunk>,
163 natives: Arc<NativeTable>,
164 workers: Vec<JoinHandle<()>>,
165 timer_thread: Option<JoinHandle<()>>,
166 trust: crate::bytecode::TrustLevel,
167}
168
169impl Runtime {
170 pub fn new(chunk: Chunk) -> Result<Self, SpawnError> {
178 Self::with_config(chunk, RuntimeConfig::default())
179 }
180
181 pub fn with_natives(chunk: Chunk, natives: Arc<NativeTable>) -> Result<Self, SpawnError> {
184 Self::with_natives_and_config(chunk, natives, RuntimeConfig::default())
185 }
186
187 pub fn with_config(chunk: Chunk, config: RuntimeConfig) -> Result<Self, SpawnError> {
188 Self::with_natives_and_config(chunk, NativeTable::empty(), config)
189 }
190
191 pub fn with_std_natives_and_config(
194 chunk: Chunk,
195 config: RuntimeConfig,
196 ) -> Result<Self, SpawnError> {
197 Self::with_natives_and_config(
198 chunk,
199 crate::std_native_table_with(Arc::clone(&config.output)),
200 config,
201 )
202 }
203
204 pub fn with_natives_and_config(
212 chunk: Chunk,
213 natives: Arc<NativeTable>,
214 config: RuntimeConfig,
215 ) -> Result<Self, SpawnError> {
216 crate::bytecode::verify_with(
217 &chunk,
218 crate::bytecode::VerifyConfig {
219 trust: config.trust,
220 },
221 )
222 .map_err(SpawnError::VerifyFailed)?;
223 let chunk = Arc::new(chunk);
224 let workers_n = config.workers.max(1);
225
226 let locals: Vec<LocalDeque<Box<Flow>>> =
227 (0..workers_n).map(|_| LocalDeque::new_fifo()).collect();
228 let stealers: Vec<Stealer<Box<Flow>>> = locals.iter().map(|l| l.stealer()).collect();
229
230 #[cfg(feature = "jit")]
231 let jit = if config.jit.enabled {
232 Some(super::jit::new_runtime(chunk.clone(), config.jit.hot_threshold))
233 } else {
234 None
235 };
236
237 let shared = Arc::new(Shared {
238 injector: Injector::new(),
239 stealers,
240 directory: Directory::new(),
241 caps: super::capability::CapTable::new(),
242 timer: TimerWheel::new(),
243 notify: (Mutex::new(()), Condvar::new()),
244 metrics: RuntimeMetrics::default(),
245 shutdown: AtomicBool::new(false),
246 quantum: config.quantum,
247 mailbox: config.mailbox,
248 flow_limit: super::flow_limit::FlowLimit::new(config.max_flows),
249 memory: Arc::new(crate::MemoryBudget::new(config.max_runtime_bytes)),
250 quota: config.quota,
251 quotas: super::quota::QuotaTable::new(),
252 monitors: super::monitor::MonitorStore::new(),
253 links: super::link::LinkStore::new(),
254 registry: super::registry::RegistryStore::new(),
255 kill_signals: super::finalize::KillSignals::new(),
256 waiting_send_at: super::finalize::WaitingSendIndex::new(),
257 ask_waits: super::finalize::AskWaitIndex::new(),
258 host_next_request_id: AtomicU64::new(1),
259 #[cfg(feature = "jit")]
260 jit,
261 });
262
263 let mut workers = Vec::with_capacity(workers_n);
264 for local in locals {
265 let shared = shared.clone();
266 let handle = std::thread::Builder::new()
267 .name("byteflow-worker".into())
268 .spawn(move || worker::run_worker(shared, local))
269 .map_err(|e| SpawnError::ThreadSpawnFailed(e.to_string()))?;
270 workers.push(handle);
271 }
272
273 let shared_timer = shared.clone();
274 let timer_thread = std::thread::Builder::new()
275 .name("byteflow-timer".into())
276 .spawn(move || {
277 shared_timer.timer.clone().drive(&shared_timer)
278 })
279 .map_err(|e| SpawnError::ThreadSpawnFailed(e.to_string()))?;
280
281 Ok(Runtime {
282 shared,
283 chunk,
284 natives,
285 workers,
286 timer_thread: Some(timer_thread),
287 trust: config.trust,
288 })
289 }
290
291 pub fn spawn(&self, function: u32, args: &[Value]) -> Result<FlowHandle, SpawnError> {
296 spawn_on(
297 &self.shared,
298 &self.chunk,
299 &self.natives,
300 function,
301 args,
302 RestartPolicy::Never,
303 None,
304 None,
305 None,
306 )
307 }
308
309 pub fn spawner(&self) -> RuntimeSpawner {
313 RuntimeSpawner { shared: self.shared.clone(), chunk: self.chunk.clone(), natives: self.natives.clone() }
314 }
315
316 pub fn supervisor(&self) -> Result<super::supervisor::Supervisor, SpawnError> {
319 super::supervisor::Supervisor::new(self.spawner())
320 }
321
322 pub fn function_index(&self, name: &str) -> Option<u32> {
326 self.chunk.functions.iter().position(|f| f.name == name).map(|i| i as u32)
327 }
328
329 pub fn metrics(&self) -> RuntimeMetricsSnapshot {
330 self.shared.metrics.snapshot()
331 }
332
333 pub fn live_flows(&self) -> usize {
339 self.shared.directory.len()
340 }
341
342 pub fn memory_snapshot(&self) -> crate::MemorySnapshot {
344 self.shared.memory.snapshot()
345 }
346
347 pub fn worker_count(&self) -> usize {
348 self.workers.len()
349 }
350
351 pub fn send(&self, target: FlowId, message: Value) -> Result<(), SendError> {
364 let Some(msg) = message.as_message().cloned() else {
365 return Err(SendError::NotAHop {
366 got: message.type_name(),
367 });
368 };
369 let mailbox = match self.shared.directory.lookup(target) {
370 Ok(Some(m)) => m,
371 Ok(None) => return Err(SendError::NoSuchFlow(target)),
372 Err(e) => {
373 super::error::report_fault(e);
374 return Err(SendError::Unavailable);
375 }
376 };
377 let stamped = match worker::authenticate_host_outgoing_message(&self.shared, target, msg) {
378 Ok(m) => Value::Message(m),
379 Err(_) => return Err(SendError::Capability),
380 };
381 match mailbox.push(stamped.clone()) {
382 Ok(Ok(Delivery::Queued | Delivery::QueuedDropOldest | Delivery::DroppedNewest)) => {
387 Ok(())
388 }
389 Ok(Ok(Delivery::Handoff(flow))) => {
390 let _ = self.shared.ask_waits.remove_asker(flow.id);
391 match flow.last_receive_dest {
392 Some(dest) => {
393 let Some(flow) =
394 super::finalize::resume_or_fail(&self.shared, flow, dest, stamped)
395 else {
396 return Err(SendError::Unavailable);
397 };
398 self.shared.injector.push(flow);
399 wake_workers(&self.shared);
400 Ok(())
401 }
402 None => {
403 super::error::report_fault(super::error::RuntimeError::PoisonedLock(
404 "Runtime::send handoff missing dest register",
405 ));
406 finalize_flow(
407 &self.shared,
408 *flow,
409 FlowOutcome::Failed("handoff missing dest register".into()),
410 FlowExitReason::Fault,
411 );
412 Err(SendError::Unavailable)
413 }
414 }
415 }
416 Ok(Err(full)) => {
417 if full.reason() == MailboxFullReason::Closed {
418 return Err(SendError::NoSuchFlow(target));
419 }
420 Err(SendError::MailboxFull {
421 flow: target,
422 reason: full.reason(),
423 })
424 }
425 Err(e) => {
426 super::error::report_fault(e);
427 Err(SendError::Unavailable)
428 }
429 }
430 }
431
432 fn require_live(&self, id: FlowId) -> Result<(), super::error::LifecycleError> {
433 match self.shared.directory.lookup(id) {
434 Ok(Some(_)) => Ok(()),
435 Ok(None) => Err(super::error::LifecycleError::NoSuchFlow(id)),
436 Err(e) => Err(self.unavailable(e)),
437 }
438 }
439
440 fn unavailable(&self, err: super::error::RuntimeError) -> super::error::LifecycleError {
441 super::error::report_fault(err);
442 super::error::LifecycleError::Unavailable
443 }
444
445 pub fn mint_cap(&self, flow: FlowId) -> Result<crate::bytecode::CapId, super::error::LifecycleError> {
447 self.require_live(flow)?;
448 self.shared
449 .caps
450 .mint(flow, flow, super::capability::CapRights::ADDRESSING)
451 .map_err(|e| self.unavailable(e))
452 }
453
454 pub fn grant_cap(
456 &self,
457 holder: FlowId,
458 target: FlowId,
459 ) -> Result<crate::bytecode::CapId, super::error::LifecycleError> {
460 self.require_live(holder)?;
461 self.require_live(target)?;
462 self.shared
463 .caps
464 .mint(holder, target, super::capability::CapRights::ADDRESSING)
465 .map_err(|e| self.unavailable(e))
466 }
467
468 pub fn monitor(
472 &self,
473 owner: FlowId,
474 target: FlowId,
475 ) -> Result<super::monitor::MonitorRef, super::error::LifecycleError> {
476 if owner == target {
477 return Err(super::error::LifecycleError::SelfRelation);
478 }
479 self.require_live(owner)?;
480 self.require_live(target)?;
481 let mon = self
482 .shared
483 .monitors
484 .create(owner, target)
485 .map_err(|e| self.unavailable(e))?;
486 if self.require_live(target).is_err() {
489 let _ = self.shared.monitors.remove_owned(owner, mon);
490 super::finalize::deliver_down(
491 &self.shared,
492 super::monitor::DownEvent {
493 monitor: mon,
494 owner,
495 target,
496 reason: super::monitor::FlowExitReason::Fault,
497 },
498 );
499 }
500 Ok(mon)
501 }
502
503 pub fn demonitor(
505 &self,
506 owner: FlowId,
507 monitor: super::monitor::MonitorRef,
508 ) -> Result<(), super::error::LifecycleError> {
509 self.require_live(owner)?;
510 match self.shared.monitors.remove_owned(owner, monitor) {
511 Ok(inner) => inner,
512 Err(e) => Err(self.unavailable(e)),
513 }
514 }
515
516 pub fn link(
518 &self,
519 a: FlowId,
520 b: FlowId,
521 ) -> Result<super::link::LinkId, super::error::LifecycleError> {
522 if a == b {
523 return Err(super::error::LifecycleError::SelfRelation);
524 }
525 self.require_live(a)?;
526 self.require_live(b)?;
527 match self.shared.links.link(a, b) {
528 Ok(inner) => inner,
529 Err(e) => Err(self.unavailable(e)),
530 }
531 }
532
533 pub fn unlink(
535 &self,
536 owner: FlowId,
537 link: super::link::LinkId,
538 ) -> Result<(), super::error::LifecycleError> {
539 self.require_live(owner)?;
540 match self.shared.links.unlink_owned(owner, link) {
541 Ok(inner) => inner,
542 Err(e) => Err(self.unavailable(e)),
543 }
544 }
545
546 pub fn register_name(
548 &self,
549 name: &str,
550 cap: crate::bytecode::CapId,
551 ) -> Result<(), super::error::LifecycleError> {
552 let entry = match self.shared.caps.lookup(cap) {
553 Ok(Some(e)) => e,
554 Ok(None) => return Err(super::error::LifecycleError::InvalidCapability),
555 Err(e) => return Err(self.unavailable(e)),
556 };
557 let target = match entry.target() {
558 Some(id) => id,
559 None => return Err(super::error::LifecycleError::InvalidCapability),
560 };
561 self.require_live(target)?;
562 match self.shared.registry.register(
563 super::registry::RegistryName::from(name),
564 cap,
565 target,
566 ) {
567 Ok(inner) => inner,
568 Err(e) => Err(self.unavailable(e)),
569 }
570 }
571
572 pub fn whereis(&self, name: &str) -> Result<Option<crate::bytecode::CapId>, super::error::LifecycleError> {
574 self.shared
575 .registry
576 .whereis(name)
577 .map_err(|e| self.unavailable(e))
578 }
579
580 pub fn kill(&self, id: FlowId) -> Result<(), super::error::LifecycleError> {
583 self.require_live(id)?;
584 super::finalize::request_kill(&self.shared, id, super::monitor::FlowExitReason::Killed);
585 Ok(())
586 }
587
588 pub fn mint_admin_cap(
590 &self,
591 holder: FlowId,
592 ) -> Result<crate::bytecode::CapId, super::error::LifecycleError> {
593 self.require_live(holder)?;
594 let cap = crate::bytecode::Cap::root(
595 crate::bytecode::CapTarget::Scheduler,
596 CapRights::ADMIN,
597 None,
598 self.shared.caps.scheduler_cell().as_ref(),
599 );
600 self.shared
601 .caps
602 .grant(holder, cap)
603 .map_err(|e| self.unavailable(e))
604 }
605
606 pub fn admin_kill(
608 &self,
609 holder: FlowId,
610 cap: crate::bytecode::CapId,
611 target: FlowId,
612 ) -> Result<(), super::error::LifecycleError> {
613 self.require_admin(holder, cap)?;
614 self.kill(target)
615 }
616
617 pub fn admin_top_up_cpu(
619 &self,
620 holder: FlowId,
621 cap: crate::bytecode::CapId,
622 target: FlowId,
623 extra: i64,
624 ) -> Result<(), super::error::LifecycleError> {
625 self.require_admin(holder, cap)?;
626 let quota = match self.shared.quotas.get(target) {
627 Ok(Some(q)) => q,
628 Ok(None) => return Err(super::error::LifecycleError::NoSuchFlow(target)),
629 Err(e) => return Err(self.unavailable(e)),
630 };
631 quota.top_up_cpu(extra);
632 Ok(())
633 }
634
635 pub fn admin_top_up_mem(
637 &self,
638 holder: FlowId,
639 cap: crate::bytecode::CapId,
640 target: FlowId,
641 extra: usize,
642 ) -> Result<(), super::error::LifecycleError> {
643 self.require_admin(holder, cap)?;
644 let quota = match self.shared.quotas.get(target) {
645 Ok(Some(q)) => q,
646 Ok(None) => return Err(super::error::LifecycleError::NoSuchFlow(target)),
647 Err(e) => return Err(self.unavailable(e)),
648 };
649 quota.top_up_mem(extra);
650 Ok(())
651 }
652
653 pub fn admin_top_up_send(
655 &self,
656 holder: FlowId,
657 cap: crate::bytecode::CapId,
658 target: FlowId,
659 extra: i64,
660 ) -> Result<(), super::error::LifecycleError> {
661 self.require_admin(holder, cap)?;
662 let quota = match self.shared.quotas.get(target) {
663 Ok(Some(q)) => q,
664 Ok(None) => return Err(super::error::LifecycleError::NoSuchFlow(target)),
665 Err(e) => return Err(self.unavailable(e)),
666 };
667 quota.top_up_send(extra);
668 Ok(())
669 }
670
671 fn require_admin(
672 &self,
673 holder: FlowId,
674 cap: crate::bytecode::CapId,
675 ) -> Result<(), super::error::LifecycleError> {
676 let entry = match self.shared.caps.resolve(cap, holder, CapRights::ADMIN) {
677 Ok(e) => e,
678 Err(_) => return Err(super::error::LifecycleError::InvalidCapability),
679 };
680 super::link_admin::check_admin(&entry.cap, self.shared.caps.scheduler_cell().as_ref())
681 .map_err(|_| super::error::LifecycleError::InvalidCapability)
682 }
683
684 pub fn unregister_name(&self, name: &str) -> Result<bool, super::error::LifecycleError> {
686 self.shared
687 .registry
688 .unregister(name)
689 .map_err(|e| self.unavailable(e))
690 }
691
692 pub fn reload_chunk(&mut self, chunk: Chunk) -> Result<(), SpawnError> {
696 crate::bytecode::verify_with(
697 &chunk,
698 crate::bytecode::VerifyConfig {
699 trust: self.trust,
700 },
701 )
702 .map_err(SpawnError::VerifyFailed)?;
703 let chunk = Arc::new(chunk);
704 self.chunk = chunk.clone();
705 #[cfg(feature = "jit")]
706 if let Some(jit) = &self.shared.jit {
707 jit.reload(chunk);
708 }
709 Ok(())
710 }
711
712 fn request_shutdown(&self) {
715 self.shared.shutdown.store(true, Ordering::Release);
716 self.shared.timer.shutdown();
717 let (lock, cvar) = &self.shared.notify;
718 match super::sync_lock::lock(lock, "Runtime::request_shutdown") {
719 Ok(_g) => cvar.notify_all(),
720 Err(e) => super::error::report_fault(e),
721 }
722 }
723
724 pub fn shutdown(mut self) {
731 self.request_shutdown();
732 for w in self.workers.drain(..) {
733 let _ = w.join();
734 }
735 if let Some(t) = self.timer_thread.take() {
736 let _ = t.join();
737 }
738 }
739}
740
741impl Drop for Runtime {
742 fn drop(&mut self) {
743 if !self.shared.shutdown.load(Ordering::Acquire) {
744 self.request_shutdown();
745 }
746 }
747}
748
749pub fn flow_id_from_u64(raw: u64) -> FlowId {
753 FlowId(raw)
754}
755
756#[derive(Debug, Clone, PartialEq, Eq)]
758pub enum SendError {
759 NoSuchFlow(FlowId),
760 NotAHop { got: &'static str },
762 MailboxFull {
766 flow: FlowId,
767 reason: MailboxFullReason,
768 },
769 Capability,
771 Unavailable,
773}
774
775impl std::fmt::Display for SendError {
776 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
777 match self {
778 SendError::NoSuchFlow(id) => write!(f, "no live flow {id}"),
779 SendError::NotAHop { got } => {
780 write!(f, "atomic hop requires Value::Message, got {got}")
781 }
782 SendError::MailboxFull { flow, reason } => {
783 write!(f, "mailbox full for {flow} ({reason})")
784 }
785 SendError::Capability => {
786 write!(f, "host send could not reissue a capability in the hop")
787 }
788 SendError::Unavailable => write!(f, "runtime table unavailable (poisoned lock)"),
789 }
790 }
791}
792
793impl std::error::Error for SendError {}
794
795pub(crate) struct BytecodeSpawn<'a> {
798 pub authority: &'a Cap,
799 pub cell: &'a crate::bytecode::RevocationCell,
800 pub quota: &'a super::quota::FlowQuota,
801 pub requested_rights: CapRights,
802}
803
804pub(crate) fn spawn_on(
813 shared: &Arc<Shared>,
814 chunk: &Arc<Chunk>,
815 natives: &Arc<NativeTable>,
816 function: u32,
817 args: &[Value],
818 restart_policy: RestartPolicy,
819 supervisor: Option<SupervisorLink>,
820 parent: Option<FlowId>,
821 bytecode: Option<BytecodeSpawn<'_>>,
822) -> Result<FlowHandle, SpawnError> {
823 shared.flow_limit.try_reserve()?;
824 let id = match super::process::try_next_flow_id() {
825 Ok(id) => id,
826 Err(super::error::RuntimeError::FlowIdExhausted) => {
827 shared.flow_limit.release();
828 return Err(SpawnError::FlowIdExhausted);
829 }
830 Err(_) => {
831 shared.flow_limit.release();
832 return Err(SpawnError::Unavailable);
833 }
834 };
835 let cell = match shared.caps.bind_flow(id) {
836 Ok(c) => c,
837 Err(_) => {
838 shared.flow_limit.release();
839 return Err(SpawnError::Unavailable);
840 }
841 };
842 let authority = match bytecode {
843 None => Cap::root(
844 CapTarget::Flow(id.as_u64()),
845 CapRights::ROOT,
846 Some(NativeMask::full(natives.len())),
847 cell.as_ref(),
848 ),
849 Some(ctx) => match super::spawn::exec_spawn_authority(
850 ctx.authority,
851 ctx.cell,
852 ctx.quota,
853 id.as_u64(),
854 ctx.requested_rights,
855 None,
856 cell.as_ref(),
857 ) {
858 Ok(cap) => cap,
859 Err(e) => {
860 shared.flow_limit.release();
861 let _ = shared.caps.revoke_flow(id);
862 return Err(SpawnError::from(e));
863 }
864 },
865 };
866 let args = match grant_caps_in_args(shared, parent, id, args) {
867 Ok(a) => a,
868 Err(e) => {
869 shared.flow_limit.release();
870 let _ = shared.caps.revoke_flow(id);
871 return Err(e);
872 }
873 };
874 let gate = NativeGate::from_authority(
875 &authority,
876 Arc::clone(&cell),
877 shared.caps.native_cell(),
878 natives.len(),
879 );
880 let quota = Arc::new(super::quota::FlowQuota::from_config(shared.quota));
881 let mut vm = match Vm::with_native_gate(
882 chunk.clone(),
883 natives.clone(),
884 gate,
885 function,
886 args.as_slice(),
887 ) {
888 Ok(vm) => vm,
889 Err(e) => {
890 shared.flow_limit.release();
891 let _ = shared.caps.revoke_flow(id);
892 return Err(e.into());
893 }
894 };
895 vm.set_memory_budget(Arc::clone(&shared.memory));
896 if let Err(e) = vm.set_quota(Arc::clone("a)) {
897 shared.flow_limit.release();
898 let _ = shared.caps.revoke_flow(id);
899 return Err(e.into());
900 }
901 let mailbox = Arc::new(Mailbox::with_config(shared.mailbox));
902 if let Err(e) = shared.directory.register(id, mailbox.clone()) {
903 super::error::report_fault(e);
904 shared.flow_limit.release();
905 let _ = shared.caps.revoke_flow(id);
906 return Err(SpawnError::Unavailable);
907 }
908 if let Err(e) = shared.quotas.insert(id, Arc::clone("a)) {
909 super::error::report_fault(e);
910 let _ = shared.directory.unregister(id);
911 shared.flow_limit.release();
912 let _ = shared.caps.revoke_flow(id);
913 return Err(SpawnError::Unavailable);
914 }
915 let (tx, rx) = super::oneshot::channel();
916 let mut flow = Box::new(Flow::new(id, vm, mailbox, restart_policy, tx));
917 flow.authority = authority;
918 flow.cell = cell;
919 flow.quota = quota;
920 flow.supervisor = supervisor;
921 RuntimeMetrics::inc(&shared.metrics.processes_spawned);
922 shared.injector.push(flow);
923 wake_workers(shared);
924 Ok(FlowHandle { id, receiver: rx })
925}
926
927fn grant_caps_in_args(
928 shared: &Shared,
929 parent: Option<FlowId>,
930 child: FlowId,
931 args: &[Value],
932) -> Result<Vec<Value>, SpawnError> {
933 let mut out = Vec::with_capacity(args.len());
934 for arg in args {
935 match arg {
936 Value::Cap(id) => {
937 let granted = match parent {
938 None => shared.caps.reissue_for(*id, child),
939 Some(p) => shared.caps.delegate(*id, p, child),
940 };
941 match granted {
942 Ok(cap) => out.push(Value::Cap(cap)),
943 Err(_) => return Err(SpawnError::InvalidCapability),
944 }
945 }
946 other => out.push(other.clone()),
947 }
948 }
949 Ok(out)
950}
951
952pub(crate) fn wake_workers(shared: &Shared) {
953 let (lock, cvar) = &shared.notify;
954 match super::sync_lock::lock(lock, "wake_workers") {
955 Ok(_g) => cvar.notify_one(),
956 Err(e) => super::error::report_fault(e),
957 }
958}
959
960#[derive(Clone)]
966pub struct RuntimeSpawner {
967 pub(crate) shared: Arc<Shared>,
968 pub(crate) chunk: Arc<Chunk>,
969 pub(crate) natives: Arc<NativeTable>,
970}
971
972impl RuntimeSpawner {
973 pub fn spawn(
974 &self,
975 function: u32,
976 args: &[Value],
977 restart_policy: RestartPolicy,
978 ) -> Result<FlowHandle, SpawnError> {
979 spawn_on(
980 &self.shared,
981 &self.chunk,
982 &self.natives,
983 function,
984 args,
985 restart_policy,
986 None,
987 None,
988 None,
989 )
990 }
991
992 pub(crate) fn spawn_linked(
993 &self,
994 function: u32,
995 args: &[Value],
996 restart_policy: RestartPolicy,
997 supervisor: SupervisorLink,
998 ) -> Result<FlowHandle, SpawnError> {
999 spawn_on(
1000 &self.shared,
1001 &self.chunk,
1002 &self.natives,
1003 function,
1004 args,
1005 restart_policy,
1006 Some(supervisor),
1007 None,
1008 None,
1009 )
1010 }
1011
1012 pub fn metrics(&self) -> RuntimeMetricsSnapshot {
1013 self.shared.metrics.snapshot()
1014 }
1015
1016 pub(crate) fn request_kill(&self, id: FlowId, reason: super::monitor::FlowExitReason) {
1017 super::finalize::request_kill(&self.shared, id, reason);
1018 }
1019}
1020
1021#[cfg(test)]
1022mod tests {
1023 use super::*;
1024 use crate::bytecode::{builder::ChunkBuilder, Opcode, Value};
1025 use crate::scheduler::FlowOutcome;
1026 use std::time::Duration;
1027
1028 fn add_chunk() -> Chunk {
1029 let mut b = ChunkBuilder::new("test");
1030 b.begin_function("main", 0, 2);
1031 b.emit_load_imm(0, 41);
1032 b.emit_load_imm(1, 1);
1033 b.emit_binop(Opcode::Add, 0, 0, 1);
1034 b.emit_return(0);
1035 b.finish()
1036 }
1037
1038 fn sleep_then_return_chunk(millis: i32) -> Chunk {
1041 let mut b = ChunkBuilder::new("test");
1042 b.begin_function("main", 0, 2);
1043 b.emit_load_imm(0, millis);
1044 b.emit_sleep(0);
1045 b.emit_load_imm(0, 7);
1046 b.emit_return(0);
1047 b.finish()
1048 }
1049
1050 #[test]
1054 fn polling_and_bounded_waits_never_commit_the_host_thread() -> Result<(), Box<dyn std::error::Error>>
1055 {
1056 const FLOW_SLEEP: i32 = 150;
1057 let rt = Runtime::with_config(
1058 sleep_then_return_chunk(FLOW_SLEEP),
1059 RuntimeConfig {
1060 workers: 1,
1061 quantum: 1_000,
1062 mailbox: MailboxConfig::DEFAULT,
1063 ..Default::default()
1064 },
1065 )?;
1066 let handle = rt.spawn(0, &[])?;
1067
1068 if let Some(outcome) = handle.try_join() {
1071 rt.shutdown();
1072 return Err(format!("try_join answered too early: {outcome:?}").into());
1073 }
1074
1075 if let Some(outcome) = handle.join_timeout(Duration::from_millis(20)) {
1078 rt.shutdown();
1079 return Err(format!("join_timeout answered too early: {outcome:?}").into());
1080 }
1081
1082 let outcome = handle.join_timeout(Duration::from_secs(10));
1085 rt.shutdown();
1086 match outcome {
1087 Some(FlowOutcome::Completed(Value::Int(7))) => Ok(()),
1088 other => Err(format!("unexpected outcome: {other:?}").into()),
1089 }
1090 }
1091
1092 #[test]
1093 fn spawn_and_join_add() -> Result<(), Box<dyn std::error::Error>> {
1094 let rt = Runtime::with_config(
1095 add_chunk(),
1096 RuntimeConfig {
1097 workers: 1,
1098 quantum: 1_000,
1099 mailbox: MailboxConfig::DEFAULT,
1100 ..Default::default()
1101 },
1102 )?;
1103 let outcome = rt.spawn(0, &[])?.join();
1104 rt.shutdown();
1105 match outcome {
1106 FlowOutcome::Completed(Value::Int(42)) => Ok(()),
1107 other => Err(format!("unexpected outcome: {other:?}").into()),
1108 }
1109 }
1110
1111 fn receive_forever_chunk() -> Chunk {
1112 let mut b = ChunkBuilder::new("recv");
1113 b.begin_function("main", 0, 1);
1114 b.emit_receive(0);
1115 b.emit_return(0);
1116 b.finish()
1117 }
1118
1119 #[test]
1120 fn kill_parked_flow_joins_failed() -> Result<(), Box<dyn std::error::Error>> {
1121 let rt = Runtime::with_config(
1122 receive_forever_chunk(),
1123 RuntimeConfig {
1124 workers: 1,
1125 quantum: 1_000,
1126 mailbox: MailboxConfig::DEFAULT,
1127 ..Default::default()
1128 },
1129 )?;
1130 let handle = rt.spawn(0, &[])?;
1131 rt.kill(handle.id())?;
1132 let outcome = handle.join();
1133 rt.shutdown();
1134 assert!(
1135 matches!(outcome, FlowOutcome::Failed(_)),
1136 "kill must fail the joiner, got {outcome:?}"
1137 );
1138 Ok(())
1139 }
1140
1141 #[test]
1142 fn max_flows_rejects_extra_spawn() -> Result<(), Box<dyn std::error::Error>> {
1143 let rt = Runtime::with_config(
1144 receive_forever_chunk(),
1145 RuntimeConfig {
1146 workers: 1,
1147 quantum: 1_000,
1148 mailbox: MailboxConfig::DEFAULT,
1149 max_flows: 1,
1150 ..Default::default()
1151 },
1152 )?;
1153 let first = rt.spawn(0, &[])?;
1154 let second = rt.spawn(0, &[]);
1155 rt.kill(first.id())?;
1156 let _ = first.join();
1157 let third = rt.spawn(0, &[])?;
1159 rt.kill(third.id())?;
1160 let _ = third.join();
1161 rt.shutdown();
1162 match second {
1163 Err(SpawnError::FlowLimit { current, max }) => {
1164 assert_eq!(current, 1);
1165 assert_eq!(max, 1);
1166 Ok(())
1167 }
1168 other => Err(format!(
1169 "expected FlowLimit, got {}",
1170 match &other {
1171 Ok(_) => "Ok(handle)".into(),
1172 Err(e) => format!("Err({e})"),
1173 }
1174 )
1175 .into()),
1176 }
1177 }
1178
1179 #[test]
1181 fn ask_drop_newest_fails_closed() -> Result<(), Box<dyn std::error::Error>> {
1182 use crate::bytecode::{Message, Program};
1183 use crate::scheduler::mailbox::{MailboxCapacity, OverflowPolicy};
1184
1185 let mut program = Program::new("ask-drop-newest");
1186 let busy = program.function("busy", 0, |f| {
1187 let loop_lbl = f.label();
1189 f.bind(loop_lbl);
1190 let ms = f.load_i32(50);
1191 f.sleep(ms);
1192 f.jump(loop_lbl);
1193 });
1194 let asker = program.function("asker", 1, |f| {
1195 let server = f.reg(0);
1196 let z = f.load_i32(0);
1197 let req = f.hop_fresh(1, z);
1198 let reply = f.ask(server, req);
1199 f.return_(reply);
1200 });
1201 let chunk = program.build();
1202
1203 let cap = MailboxCapacity::new(1).ok_or("cap")?;
1204 let rt = Runtime::with_natives_and_config(
1205 chunk,
1206 crate::std_native_table(),
1207 RuntimeConfig {
1208 workers: 2,
1210 quantum: 1_000,
1211 mailbox: MailboxConfig::new(cap, OverflowPolicy::DropNewest),
1212 ..Default::default()
1213 },
1214 )?;
1215
1216 let server = rt.spawn(busy, &[])?;
1217 rt.send(
1219 server.id(),
1220 Value::Message(Message::request(1, 9, Value::Int(1))),
1221 )?;
1222 let server_cap = rt.mint_cap(server.id())?;
1223 let ask = rt.spawn(asker, &[Value::Cap(server_cap)])?;
1224 let outcome = ask.join_timeout(Duration::from_secs(3));
1225 rt.kill(server.id())?;
1226 let _ = server.join_timeout(Duration::from_millis(500));
1227 rt.shutdown();
1228
1229 match outcome {
1230 Some(FlowOutcome::Failed(msg)) if msg.contains("DropNewest") => Ok(()),
1231 other => Err(format!("expected Ask DropNewest failure, got {other:?}").into()),
1232 }
1233 }
1234
1235 #[cfg(feature = "jit")]
1236 #[test]
1237 fn runtime_with_jit_enabled_completes_add() -> Result<(), Box<dyn std::error::Error>> {
1238 use crate::JitConfig;
1239
1240 let rt = Runtime::with_config(
1241 add_chunk(),
1242 RuntimeConfig {
1243 workers: 1,
1244 quantum: 1_000,
1245 mailbox: MailboxConfig::DEFAULT,
1246 jit: JitConfig {
1247 enabled: true,
1248 hot_threshold: 1,
1249 },
1250 ..Default::default()
1251 },
1252 )?;
1253 let outcome = rt.spawn(0, &[])?.join();
1254 rt.shutdown();
1255 match outcome {
1256 FlowOutcome::Completed(Value::Int(42)) => Ok(()),
1257 other => Err(format!("unexpected outcome: {other:?}").into()),
1258 }
1259 }
1260}