2026-02-06 11:25:37 +00:00
|
|
|
use std::any::Any;
|
|
|
|
|
use std::cell::RefCell;
|
|
|
|
|
use std::collections::{HashMap, VecDeque};
|
2026-02-07 16:51:40 +00:00
|
|
|
use std::sync::atomic::{AtomicBool, Ordering};
|
2026-02-06 14:45:19 +00:00
|
|
|
use std::sync::Arc;
|
2026-02-06 11:25:37 +00:00
|
|
|
use std::thread;
|
|
|
|
|
|
2026-02-07 16:51:40 +00:00
|
|
|
use crate::actor::{ActorAddress, AnyActor, ContextInner, Ctx};
|
|
|
|
|
use crate::channel::Receiver;
|
|
|
|
|
use crate::delivery::{Envelope, TickContext, WorkerId};
|
|
|
|
|
use crate::stats::WorkerStats;
|
2026-02-06 11:25:37 +00:00
|
|
|
use crate::Error;
|
|
|
|
|
|
|
|
|
|
/// A worker owns a set of actors and runs them in a loop.
|
|
|
|
|
pub(crate) struct Worker {
|
2026-02-08 16:18:39 +00:00
|
|
|
pub(crate) id: WorkerId,
|
refactor: repack external bindings into their own crates (#19)
Split the monolithic crate into a Cargo workspace with the Python and Wasm bindings as separate member crates.
- Cargo.toml: declare a `[workspace]` with members `.`/`crates/swactor-python`/`crates/swactor-wasm`, remove the `python` feature and pyo3 dependency, and change root crate-type from `["cdylib","rlib"]` to `["rlib"]`
- crates/swactor-python: new cdylib crate re-exporting the PyO3 bindings (Runtime/RuntimeConfig/RuntimeHandle/Inbox/Ctx/ActorAddress/RuntimeStats), depending on `swactor` + pyo3; pyproject.toml and uv.lock relocated here from the root
- crates/swactor-wasm: new cdylib crate moved from top-level `wasm/`, depending on `swactor` with `no_random` features
- src/actor.rs: widen `Actor::new`, `AnyActor`, `ContextInner`, and `Ctx::raw_inner` to `pub` so the separate binding crates can drive the runtime
- src/lib.rs: delete the in-tree `python` module and `#[pymodule]`, and gate the `no_random` RNG behind `all(feature = "no_random", not(feature = "getrandom"))`
- tools/: relocate package.json/package-lock.json; drop the now-duplicate `wasm/Cargo.lock`
Signed-off-by: Zachery Aaron Shores-Chmielewski <zacheryasc@gmail.com>
2026-02-07 17:39:02 +00:00
|
|
|
pub(crate) pool: ActorPool,
|
2026-02-06 11:25:37 +00:00
|
|
|
transfer_rx: Receiver<Envelope>,
|
|
|
|
|
spawn_rx: Receiver<(ActorAddress, Box<dyn AnyActor>)>,
|
2026-02-06 14:45:19 +00:00
|
|
|
stats: Arc<WorkerStats>,
|
2026-02-06 11:25:37 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl Worker {
|
2026-02-06 14:45:19 +00:00
|
|
|
pub(crate) fn new(
|
2026-02-06 11:25:37 +00:00
|
|
|
id: WorkerId,
|
|
|
|
|
transfer_rx: Receiver<Envelope>,
|
|
|
|
|
spawn_rx: Receiver<(ActorAddress, Box<dyn AnyActor>)>,
|
2026-02-06 14:45:19 +00:00
|
|
|
stats: Arc<WorkerStats>,
|
2026-02-06 11:25:37 +00:00
|
|
|
) -> Self {
|
|
|
|
|
Self {
|
|
|
|
|
id,
|
|
|
|
|
pool: ActorPool::new(),
|
|
|
|
|
transfer_rx,
|
|
|
|
|
spawn_rx,
|
2026-02-06 14:45:19 +00:00
|
|
|
stats,
|
2026-02-06 11:25:37 +00:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Run one iteration of the worker loop. Returns `true` if any work was done.
|
2026-02-06 14:45:19 +00:00
|
|
|
pub(crate) fn tick_once(&mut self, tc: &TickContext) -> bool {
|
2026-02-06 11:25:37 +00:00
|
|
|
let mut did_work = false;
|
|
|
|
|
|
|
|
|
|
// 1. Drain spawn queue → add actors to pool
|
|
|
|
|
while let Some((addr, actor)) = self.spawn_rx.try_recv() {
|
|
|
|
|
self.pool.insert(addr, actor);
|
|
|
|
|
did_work = true;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 2. Drain transfer queue → deliver envelopes to actors
|
|
|
|
|
while let Some(envelope) = self.transfer_rx.try_recv() {
|
|
|
|
|
let dest = envelope.dest();
|
|
|
|
|
let payload = envelope.into_payload();
|
|
|
|
|
self.pool.deliver(&dest, payload);
|
|
|
|
|
did_work = true;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 3. Tick all actors with WorkerContext
|
|
|
|
|
let pending_local: RefCell<Vec<(ActorAddress, Box<dyn Any + Send>)>> =
|
|
|
|
|
RefCell::new(Vec::new());
|
|
|
|
|
|
2026-02-06 14:45:19 +00:00
|
|
|
let processed;
|
2026-02-06 11:25:37 +00:00
|
|
|
{
|
|
|
|
|
let worker_ctx = WorkerContext {
|
|
|
|
|
worker_id: self.id,
|
2026-02-07 10:36:45 +00:00
|
|
|
tc,
|
2026-02-06 11:25:37 +00:00
|
|
|
pending_local: &pending_local,
|
|
|
|
|
};
|
2026-02-06 14:45:19 +00:00
|
|
|
processed = self.pool.tick_all(&worker_ctx);
|
|
|
|
|
if processed > 0 {
|
2026-02-06 11:25:37 +00:00
|
|
|
did_work = true;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-09 07:24:16 +00:00
|
|
|
// 4. Drain spawn queue again — actors spawned during step 3
|
|
|
|
|
// must be in the pool before pending_local delivery.
|
|
|
|
|
while let Some((addr, actor)) = self.spawn_rx.try_recv() {
|
|
|
|
|
self.pool.insert(addr, actor);
|
|
|
|
|
did_work = true;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 5. Drain pending_local buffer → deliver to local actors
|
2026-02-06 11:25:37 +00:00
|
|
|
let pending = pending_local.into_inner();
|
|
|
|
|
if !pending.is_empty() {
|
|
|
|
|
did_work = true;
|
|
|
|
|
}
|
|
|
|
|
for (addr, msg) in pending {
|
|
|
|
|
self.pool.deliver(&addr, msg);
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-09 07:24:16 +00:00
|
|
|
// 6. Publish stats
|
2026-02-06 14:45:19 +00:00
|
|
|
self.stats.num_actors.store(self.pool.len(), Ordering::Relaxed);
|
|
|
|
|
self.stats.total_mailbox_depth.store(self.pool.total_mailbox_depth(), Ordering::Relaxed);
|
|
|
|
|
self.stats.messages_processed.fetch_add(processed as u64, Ordering::Relaxed);
|
|
|
|
|
|
2026-02-06 11:25:37 +00:00
|
|
|
did_work
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-07 10:36:45 +00:00
|
|
|
pub(crate) fn run(&mut self, tc: &TickContext, is_running: &AtomicBool) {
|
|
|
|
|
let backoff = &tc.config.backoff_policy;
|
2026-02-06 11:25:37 +00:00
|
|
|
let mut idle_count: u32 = 0;
|
|
|
|
|
while is_running.load(Ordering::Acquire) {
|
|
|
|
|
let did_work = self.tick_once(tc);
|
|
|
|
|
if did_work {
|
|
|
|
|
idle_count = 0;
|
|
|
|
|
} else {
|
|
|
|
|
idle_count = idle_count.saturating_add(1);
|
|
|
|
|
if idle_count < backoff.spin_threshold {
|
|
|
|
|
// Hot spin
|
|
|
|
|
} else if idle_count < backoff.yield_threshold {
|
|
|
|
|
thread::yield_now();
|
|
|
|
|
} else {
|
|
|
|
|
let micros = std::cmp::min(
|
|
|
|
|
(idle_count - backoff.yield_threshold) as u64 * backoff.sleep_increment_us,
|
|
|
|
|
backoff.sleep_max_us,
|
|
|
|
|
);
|
|
|
|
|
thread::sleep(std::time::Duration::from_micros(micros));
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// The `ContextInner` impl for worker threads.
|
|
|
|
|
///
|
|
|
|
|
/// Same-worker sends are buffered in `pending_local` (delivered after current tick round).
|
|
|
|
|
/// Cross-worker sends go through the transfer queue.
|
|
|
|
|
struct WorkerContext<'a> {
|
|
|
|
|
worker_id: WorkerId,
|
2026-02-07 10:36:45 +00:00
|
|
|
tc: &'a TickContext<'a>,
|
2026-02-06 11:25:37 +00:00
|
|
|
pending_local: &'a RefCell<Vec<(ActorAddress, Box<dyn Any + Send>)>>,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl ContextInner for WorkerContext<'_> {
|
|
|
|
|
fn send_any(&self, addr: ActorAddress, msg: Box<dyn Any + Send>) -> Result<(), Error> {
|
2026-02-07 10:36:45 +00:00
|
|
|
match self.tc.address_map.lookup(&addr) {
|
2026-02-06 11:25:37 +00:00
|
|
|
Some(wid) if wid == self.worker_id => {
|
|
|
|
|
// Same worker: buffer for local delivery (after current tick round)
|
|
|
|
|
self.pending_local.borrow_mut().push((addr, msg));
|
|
|
|
|
Ok(())
|
|
|
|
|
}
|
|
|
|
|
Some(wid) => {
|
|
|
|
|
// Cross worker: envelope through transfer queue
|
|
|
|
|
let envelope = Envelope::new(addr, msg);
|
2026-02-07 10:36:45 +00:00
|
|
|
let _ = self.tc.transfer_txs[wid.as_usize()].try_send(envelope);
|
2026-02-06 11:25:37 +00:00
|
|
|
Ok(())
|
|
|
|
|
}
|
|
|
|
|
None => {
|
|
|
|
|
// Try inbox registry (external inboxes)
|
2026-02-07 10:36:45 +00:00
|
|
|
self.tc.inbox_registry.try_deliver(addr, msg)
|
2026-02-06 11:25:37 +00:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn spawn_any(&self, addr: ActorAddress, actor: Box<dyn AnyActor>) -> Result<(), Error> {
|
2026-02-07 10:36:45 +00:00
|
|
|
let worker_id = self.tc.placement.next_worker();
|
|
|
|
|
self.tc.address_map.insert(addr, worker_id);
|
|
|
|
|
self.tc.spawn_txs[worker_id.as_usize()]
|
2026-02-06 11:25:37 +00:00
|
|
|
.try_send((addr, actor))
|
|
|
|
|
.map_err(|_| Error::from("Spawn queue full"))
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-06 14:45:19 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
struct ActorSlot {
|
|
|
|
|
mailbox: VecDeque<Box<dyn Any + Send>>,
|
|
|
|
|
actor: Box<dyn AnyActor>,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Per-worker actor storage. Owns per-actor mailboxes.
|
2026-02-06 11:25:37 +00:00
|
|
|
pub(crate) struct ActorPool {
|
2026-02-06 14:45:19 +00:00
|
|
|
actors: HashMap<ActorAddress, ActorSlot>,
|
2026-02-06 11:25:37 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl ActorPool {
|
|
|
|
|
pub fn new() -> Self {
|
|
|
|
|
Self {
|
|
|
|
|
actors: HashMap::new(),
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub fn insert(&mut self, addr: ActorAddress, actor: Box<dyn AnyActor>) {
|
2026-02-06 14:45:19 +00:00
|
|
|
self.actors.insert(addr, ActorSlot {
|
|
|
|
|
mailbox: VecDeque::new(),
|
|
|
|
|
actor,
|
|
|
|
|
});
|
2026-02-06 11:25:37 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub fn remove(&mut self, addr: &ActorAddress) -> Option<Box<dyn AnyActor>> {
|
2026-02-06 14:45:19 +00:00
|
|
|
self.actors.remove(addr).map(|slot| slot.actor)
|
2026-02-06 11:25:37 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Deliver a type-erased message to the actor at `addr`.
|
2026-02-06 14:45:19 +00:00
|
|
|
/// Returns `true` if the actor exists (message is queued; type check deferred to tick).
|
2026-02-06 11:25:37 +00:00
|
|
|
pub fn deliver(&mut self, addr: &ActorAddress, msg: Box<dyn Any + Send>) -> bool {
|
2026-02-06 14:45:19 +00:00
|
|
|
if let Some(slot) = self.actors.get_mut(addr) {
|
|
|
|
|
slot.mailbox.push_back(msg);
|
|
|
|
|
true
|
2026-02-06 11:25:37 +00:00
|
|
|
} else {
|
|
|
|
|
false
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-06 14:45:19 +00:00
|
|
|
/// Tick all actors in the pool. Returns the number of messages processed.
|
|
|
|
|
pub fn tick_all(&mut self, inner: &dyn ContextInner) -> usize {
|
|
|
|
|
let mut count = 0;
|
|
|
|
|
for (&addr, slot) in self.actors.iter_mut() {
|
2026-02-09 07:24:16 +00:00
|
|
|
let ctx = Ctx::new(inner, addr);
|
|
|
|
|
while let Some(msg) = slot.mailbox.pop_front() {
|
|
|
|
|
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
|
|
|
|
|
slot.actor.handle_any(&ctx, msg);
|
|
|
|
|
}));
|
|
|
|
|
if result.is_err() {
|
|
|
|
|
eprintln!("swactor: actor {addr} panicked in handler");
|
2026-02-06 14:45:19 +00:00
|
|
|
}
|
2026-02-09 07:24:16 +00:00
|
|
|
count += 1;
|
2026-02-06 11:25:37 +00:00
|
|
|
}
|
|
|
|
|
}
|
2026-02-06 14:45:19 +00:00
|
|
|
count
|
2026-02-06 11:25:37 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub fn len(&self) -> usize {
|
|
|
|
|
self.actors.len()
|
|
|
|
|
}
|
2026-02-06 14:45:19 +00:00
|
|
|
|
|
|
|
|
pub fn total_mailbox_depth(&self) -> usize {
|
|
|
|
|
self.actors.values().map(|slot| slot.mailbox.len()).sum()
|
|
|
|
|
}
|
2026-02-06 11:25:37 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|