rings_node/extension/ext/registry.rs
1//! Router + capability core.
2//!
3//! [`Extensions`] registers `(Protocol, Interpret)` pairs by namespace. Each interpreter is
4//! handed a namespace-scoped [`Scope`] (overlay `send` / `did` / self-`inject`, confined to its
5//! own namespace) — *not* the router-internal `Core`. Protocols that authenticate and select an
6//! exact physical next hop may additionally use crate-private `send_direct`; it preserves the
7//! namespace envelope while bypassing Chord route selection. `Core` is the crate-private capability
8//! that resolves a namespace's [`Route`], through which an inbound [`Envelope`] reaches its
9//! protocol, and drives the bounded re-injection fixpoint; the registry stays uniform (everything
10//! erased to the internal `Handler`) while each extension's shell is its own. Extension authors
11//! see only `Protocol` / `Interpret` / `Scope` / `Transition` / `Extensions`.
12
13use std::cell::RefCell;
14use std::collections::HashMap;
15use std::collections::VecDeque;
16use std::future::poll_fn;
17use std::future::Future;
18use std::ops::Deref;
19use std::pin::pin;
20use std::sync::atomic::AtomicU64;
21use std::sync::atomic::Ordering;
22use std::sync::Arc;
23use std::sync::Mutex;
24use std::sync::RwLock;
25
26use bytes::Bytes;
27use futures::lock::Mutex as AsyncMutex;
28use rings_core::dht::Did;
29use rings_core::swarm::LaneCreditView;
30use rings_runtime::MaybeSendSync;
31
32use super::delegation;
33use super::delegation::Delegation;
34use super::Ctx;
35use super::Envelope;
36use super::Interpret;
37use super::LinkFact;
38use super::Protocol;
39use super::Reject;
40use super::Transition;
41use super::Wire;
42use crate::error::Error;
43use crate::error::Result;
44use crate::processor::Processor;
45use crate::sync_lock::lock;
46use crate::tasks::NodeTasks;
47
48/// Upper bound on synchronous feedback iterations within one protocol turn.
49const MAX_FIXPOINT_STEPS: u32 = 1024;
50
51static NEXT_RUNNER_ID: AtomicU64 = AtomicU64::new(1);
52
53pub(crate) fn next_runner_id() -> u64 {
54 NEXT_RUNNER_ID.fetch_add(1, Ordering::Relaxed)
55}
56
57thread_local! {
58 /// Stack of `Runner::runner_id`s whose `transition_gate` is owned by the future currently
59 /// being polled on this thread. Populated per-`poll` so a suspended turn never marks an
60 /// unrelated or spawned task on the same executor thread as re-entrant.
61 static ACTIVE_RUNNERS: RefCell<Vec<u64>> = const { RefCell::new(Vec::new()) };
62}
63
64struct ActiveRunnerGuard(u64);
65
66impl Drop for ActiveRunnerGuard {
67 fn drop(&mut self) {
68 ACTIVE_RUNNERS.with(|active| {
69 let mut active = active.borrow_mut();
70 if let Some(pos) = active.iter().rposition(|&id| id == self.0) {
71 active.remove(pos);
72 }
73 });
74 }
75}
76
77fn enter_active_runner(runner_id: u64) -> ActiveRunnerGuard {
78 ACTIVE_RUNNERS.with(|active| active.borrow_mut().push(runner_id));
79 ActiveRunnerGuard(runner_id)
80}
81
82fn is_runner_active(runner_id: u64) -> bool {
83 ACTIVE_RUNNERS.with(|active| active.borrow().contains(&runner_id))
84}
85
86async fn with_active_runner<F: Future>(runner_id: u64, fut: F) -> F::Output {
87 let mut fut = pin!(fut);
88 poll_fn(|cx| {
89 let _guard = enter_active_runner(runner_id);
90 fut.as_mut().poll(cx)
91 })
92 .await
93}
94
95/// Type-erased handler stored in the registry: native is `Send + Sync`, browser not.
96pub(crate) type DynHandler = rings_runtime::maybe_send_sync!(dyn Handler);
97
98type HandlerMap = RwLock<HashMap<String, Arc<DynHandler>>>;
99
100/// Erased, runtime-facing handler — the router-internal ABI. Implemented once, generically, by
101/// `Runner`; protocol authors never name it (they write `Protocol` + `Interpret`).
102#[cfg_attr(rings_browser, async_trait::async_trait(?Send))]
103#[cfg_attr(rings_native, async_trait::async_trait)]
104pub(crate) trait Handler {
105 /// Decode → step (pure, committed) → run the protocol's effects and synchronous
106 /// feedback. `handle : (from, payload) → IO ()`.
107 async fn handle(&self, core: &Core, from: Did, payload: Bytes) -> Result<()>;
108
109 /// Step the protocol's [`Protocol::link_fact`] event for `fact`, if it makes one, as a turn
110 /// of its own. `observe_link : LinkFact → IO ()`.
111 async fn observe_link(&self, core: &Core, fact: LinkFact) -> Result<()>;
112}
113
114/// The router-internal capability. Cloneable and `'static` so a long-running engine task can
115/// keep a copy and feed events back via [`inject`](Core::inject). Not handed to extension
116/// shells — they get a namespace-scoped [`Scope`] instead.
117///
118/// Holds [`Processor`] weakly so background tasks spawned onto [`NodeTasks`] (such as
119/// [`Backend::serve`](crate::extension::Backend::serve)) never form an `Arc` cycle that keeps the
120/// swarm, its application inbox sender, or browser IndexedDB locks alive after the last
121/// [`Provider`](crate::provider::Provider) is dropped.
122#[derive(Clone)]
123pub(crate) struct Core {
124 processor: std::sync::Weak<Processor>,
125 /// Retained only when constructed standalone via [`Extensions::new`] without an enclosing
126 /// [`Provider`](crate::provider::Provider) owning the [`Processor`]. [`Provider`] builds its
127 /// registry via [`Extensions::new_weak`] so spawned [`Backend::serve`] / protocol tasks never
128 /// form a strong `Arc<Processor>` cycle.
129 _standalone_owner: Option<Arc<Processor>>,
130 did: Did,
131 network_id: u32,
132 tasks: NodeTasks,
133 slot_roster: Arc<rings_core::message::SlotRoster>,
134 onion_role: crate::onion::OnionRole<crate::onion::OnionExitOffer>,
135 onion_idle_floor: crate::onion::circuit::OnionIdleFloor,
136 onion_udp_bind_config: crate::onion::OnionUdpBindConfig,
137 onion_process_epoch: crate::onion::OnionProcessEpochCell,
138 clock: rings_core::utils::SharedClock,
139 rng: rings_core::utils::SharedRng,
140 handlers: Arc<HandlerMap>,
141}
142
143impl Core {
144 fn upgrade_processor(&self) -> Result<Arc<Processor>> {
145 self.processor
146 .upgrade()
147 .ok_or_else(|| Error::ExtensionError("node processor is closed".to_string()))
148 }
149
150 /// This node's DID.
151 pub fn did(&self) -> Did {
152 self.did
153 }
154
155 /// The node's tasks, onto which every engine and shell task is spawned (`crate::tasks`).
156 pub(crate) fn tasks(&self) -> &NodeTasks {
157 &self.tasks
158 }
159
160 /// Whether `peer`'s link generation is admitted now; `false` when the lifecycle cannot be
161 /// read or the processor has been dropped.
162 pub(crate) fn peer_admitted(&self, peer: Did) -> bool {
163 self.processor
164 .upgrade()
165 .and_then(|processor| processor.swarm.is_peer_admitted(peer).ok())
166 .unwrap_or(false)
167 }
168
169 /// The peers whose link generation is admitted now, each read under the lifecycle lock.
170 pub(crate) fn admitted_peers(&self) -> Vec<Did> {
171 let Some(processor) = self.processor.upgrade() else {
172 return Vec::new();
173 };
174 processor
175 .swarm
176 .peer_dids()
177 .into_iter()
178 .filter(|peer| processor.swarm.is_peer_admitted(*peer).unwrap_or(false))
179 .collect()
180 }
181
182 /// The read-only view of the Application lane's send credit of `peer`'s sendable
183 /// connection generation, or `None` without one (`Swarm::application_credit`, #913).
184 pub(crate) fn application_credit(&self, peer: Did) -> Option<LaneCreditView> {
185 self.processor.upgrade()?.swarm.application_credit(peer)
186 }
187
188 /// `𝓡`, the capacity of the swarm's connection registry (#723).
189 pub(crate) fn connection_registry_capacity(&self) -> Result<usize> {
190 self.upgrade_processor()?
191 .swarm
192 .connection_registry_capacity()
193 .map_err(Error::InternalError)
194 }
195
196 /// The node's shared connection-slot roster (`PeerRing::edges`, #1183).
197 pub(crate) fn slot_roster(&self) -> Arc<rings_core::message::SlotRoster> {
198 Arc::clone(&self.slot_roster)
199 }
200
201 /// This node's active session key followed by any retained unexpired previous keys at
202 /// `now_ms` (#1153, #1223).
203 pub(crate) fn decryption_keys_at(
204 &self,
205 now_ms: u128,
206 ) -> Vec<rings_core::delegation::DelegateeKey> {
207 self.processor
208 .upgrade()
209 .map(|processor| processor.decryption_keys_at(now_ms))
210 .unwrap_or_default()
211 }
212
213 /// This process's onion role (#834 D2).
214 pub(crate) fn onion_role(&self) -> &crate::onion::OnionRole<crate::onion::OnionExitOffer> {
215 &self.onion_role
216 }
217
218 /// The cover floor of this node's idle onion links (#880).
219 pub(crate) fn onion_idle_floor(&self) -> crate::onion::circuit::OnionIdleFloor {
220 self.onion_idle_floor
221 }
222
223 /// Socket binding and peer-IP admission settings for native `onion::udp` exits.
224 pub(crate) fn onion_udp_bind_config(&self) -> crate::onion::OnionUdpBindConfig {
225 self.onion_udp_bind_config
226 }
227
228 /// The onion process epoch cell of this node (#834 D2).
229 pub(crate) fn onion_process_epoch(&self) -> crate::onion::OnionProcessEpochCell {
230 self.onion_process_epoch.clone()
231 }
232
233 /// The entry-guard manager shared across this node's onion route builders.
234 pub(crate) fn onion_entry_guards(&self) -> Result<Arc<crate::onion::OnionEntryGuards>> {
235 Ok(self.upgrade_processor()?.onion_entry_guards_arc())
236 }
237
238 /// Network identifier of this node's swarm.
239 pub(crate) fn network_id(&self) -> u32 {
240 self.network_id
241 }
242
243 /// The injected [`SharedClock`](rings_core::utils::SharedClock) of this node.
244 pub(crate) fn clock(&self) -> &rings_core::utils::SharedClock {
245 &self.clock
246 }
247
248 /// The injected [`SharedRng`](rings_core::utils::SharedRng) of this node.
249 pub(crate) fn rng(&self) -> &rings_core::utils::SharedRng {
250 &self.rng
251 }
252
253 /// Put a message on the overlay to `to` under `namespace`.
254 pub async fn send(&self, to: Did, namespace: &str, payload: Bytes) -> Result<()> {
255 let processor = self.upgrade_processor()?;
256 let envelope = Envelope::new(namespace, payload);
257 processor.send_envelope(to, &envelope).await?;
258 Ok(())
259 }
260
261 /// Put a message on an already-connected transport edge without Chord route selection.
262 async fn send_direct(&self, to: Did, namespace: &str, payload: Bytes) -> Result<()> {
263 let processor = self.upgrade_processor()?;
264 let envelope = Envelope::new(namespace, payload);
265 processor.send_direct_envelope(to, &envelope).await?;
266 Ok(())
267 }
268
269 /// Re-enter the router with a *self*-addressed message (`from = this node`): a locally
270 /// injected command, or an engine task feeding a lifecycle event back to its protocol (the
271 /// native relay engine, and the onion data plane's reconcile at install).
272 pub async fn inject(&self, namespace: &str, payload: Bytes) -> Result<()> {
273 self.dispatch(self.did(), Envelope::new(namespace, payload))
274 .await
275 }
276
277 /// Route one [`Envelope`] to its protocol. An unknown namespace is logged and dropped
278 /// (non-fatal). Same-turn feedback is reduced inside the selected handler; later lifecycle
279 /// injection starts a new dispatch.
280 ///
281 /// The caller chooses `from`, so a protocol's `decode` attributes the resulting event to that
282 /// DID (for the relay, a `from != me` envelope becomes a peer `Frame`). It is therefore
283 /// crate-private: production reaches it only through [`inject`](Core::inject), with
284 /// `from = self.did()`; inbound envelopes from peers take a [`Route`] instead, resolved by
285 /// the [`Backend`](crate::extension::Backend)'s router.
286 pub(crate) async fn dispatch(&self, from: Did, envelope: Envelope) -> Result<()> {
287 match self.route(envelope.namespace.as_str()) {
288 Some(route) => route.dispatch(from, envelope.payload).await,
289 None => {
290 tracing::warn!(namespace = %envelope.namespace, "no protocol registered, dropping");
291 Ok(())
292 }
293 }
294 }
295
296 /// The route to every registered namespace's protocol, with its namespace.
297 pub(crate) fn routes(&self) -> Vec<(String, Route)> {
298 let Ok(handlers) = self.handlers.read() else {
299 return Vec::new();
300 };
301 handlers
302 .iter()
303 .map(|(namespace, handler)| {
304 (namespace.clone(), Route {
305 core: self.clone(),
306 handler: Arc::clone(handler),
307 })
308 })
309 .collect()
310 }
311
312 /// The route to `namespace`'s protocol, or `None` when no protocol is registered under it.
313 pub(crate) fn route(&self, namespace: &str) -> Option<Route> {
314 let handler = self.handlers.read().ok()?.get(namespace).map(Arc::clone)?;
315 Some(Route {
316 core: self.clone(),
317 handler,
318 })
319 }
320}
321
322/// A registered namespace's protocol, resolved from the registry. Holding one witnesses that the
323/// namespace was registered when it was resolved, so its [`dispatch`](Route::dispatch) never
324/// re-checks the registration:
325///
326/// ```text
327/// route(ns) = Some(r) ⇒ r.dispatch(from, p) runs ns's handler on (from, p)
328/// ```
329///
330/// A later [`replace`](Extensions::replace) does not reach a route resolved before it.
331#[derive(Clone)]
332pub(crate) struct Route {
333 core: Core,
334 handler: Arc<DynHandler>,
335}
336
337impl Route {
338 /// Run the resolved protocol on `payload` from `from`: decode, step, then its effects and
339 /// synchronous feedback. This is the **authenticated ingress**: `from` must be the
340 /// message's verified signer, which only the [`Backend`](crate::extension::Backend) has.
341 pub(crate) async fn dispatch(&self, from: Did, payload: Bytes) -> Result<()> {
342 self.handler.handle(&self.core, from, payload).await
343 }
344
345 /// Run the resolved protocol on `fact`, which only the router establishes: a retirement it
346 /// reads off the core's inbox, or a drop by the namespace's own queue.
347 pub(crate) async fn observe_link(&self, fact: LinkFact) -> Result<()> {
348 self.handler.observe_link(&self.core, fact).await
349 }
350}
351
352/// A **namespace-scoped** capability handed to an [`Interpret`] shell — the effectful
353/// counterpart of the pure side's read-only [`Ctx`]. Every action is confined to the
354/// interpreter's own namespace: it may `send` to peers and self-`inject` only there, and it
355/// can neither reach another namespace nor forge a remote `from`. This is what keeps the
356/// capability honest: an extension shell cannot use the router as a generic
357/// inject-any-namespace bus (e.g. manufacture another extension's lifecycle events). Cloneable
358/// and `'static`, so a long-running engine task can keep a copy.
359#[derive(Clone)]
360pub struct Scope {
361 core: Core,
362 namespace: String,
363}
364
365impl Scope {
366 /// Confine `core` to `namespace`.
367 pub(crate) fn new(core: Core, namespace: String) -> Self {
368 Self { core, namespace }
369 }
370
371 /// This node's DID.
372 pub fn did(&self) -> Did {
373 self.core.did()
374 }
375
376 /// The node's tasks, onto which this scope's shell spawns its own (`crate::tasks`).
377 pub(crate) fn tasks(&self) -> &NodeTasks {
378 self.core.tasks()
379 }
380
381 /// The namespace this scope is confined to.
382 pub fn namespace(&self) -> &str {
383 self.namespace.as_str()
384 }
385
386 /// Put a message on the overlay to `to`, under this interpreter's own namespace.
387 pub async fn send(&self, to: Did, payload: Bytes) -> Result<()> {
388 self.core.send(to, self.namespace.as_str(), payload).await
389 }
390
391 /// Send to an exact, already-connected peer under this scope's namespace.
392 ///
393 /// This is intentionally crate-private: only protocols that already authenticate their own
394 /// hop selection, such as onion circuits, may bypass the overlay routing decision.
395 pub(crate) async fn send_direct(&self, to: Did, payload: Bytes) -> Result<()> {
396 self.core
397 .send_direct(to, self.namespace.as_str(), payload)
398 .await
399 }
400
401 /// Whether `peer`'s link generation is admitted now.
402 pub(crate) fn peer_admitted(&self, peer: Did) -> bool {
403 self.core.peer_admitted(peer)
404 }
405
406 /// The peers whose link generation is admitted now.
407 pub(crate) fn admitted_peers(&self) -> Vec<Did> {
408 self.core.admitted_peers()
409 }
410
411 /// The read-only view of the Application lane's send credit of `peer`'s connection, for a
412 /// sender that paces its own emission on it (#913): never a transport handle, and it
413 /// reserves nothing.
414 pub(crate) fn application_credit(&self, peer: Did) -> Option<LaneCreditView> {
415 self.core.application_credit(peer)
416 }
417
418 /// This node's active session key followed by any retained unexpired previous keys at
419 /// `now_ms` (#1153, #1223).
420 pub(crate) fn decryption_keys_at(
421 &self,
422 now_ms: u128,
423 ) -> Vec<rings_core::delegation::DelegateeKey> {
424 self.core.decryption_keys_at(now_ms)
425 }
426
427 /// Self-inject `payload` into this interpreter's **own** namespace (`from = this node`).
428 ///
429 /// `pub(crate)`: this is the **long-lived lifecycle sink** for an extension's own engine
430 /// (e.g. the relay's spawned socket tasks reporting `Accepted`/`Untrack` later), and it
431 /// starts a **fresh** [`dispatch`](Core::dispatch) fixpoint with its own
432 /// `MAX_FIXPOINT_STEPS` budget — it is *not* part of the bounded feedback fixpoint that
433 /// drives a single inbound. The synchronous per-effect feedback path is the `Vec<Bytes>`
434 /// returned from [`Interpret::run`], which the runner reduces within its current ordered
435 /// turn and budget.
436 /// A third-party shell therefore gets only that bounded return path, never this re-entrant
437 /// sink, so it cannot recurse `inject` to escape the budget.
438 pub(crate) async fn inject(&self, payload: Bytes) -> Result<()> {
439 self.core.inject(self.namespace.as_str(), payload).await
440 }
441}
442
443/// Capability available while an interpreter applies one committed effect.
444///
445/// It can send overlay messages and return synchronous feedback, but cannot re-enter its own
446/// reducer. Long-lived engines receive a [`Scope`] explicitly through the crate-private
447/// `EffectScope::lifecycle` handoff, making ownership visible at the effect boundary.
448pub struct EffectScope {
449 scope: Scope,
450}
451
452impl EffectScope {
453 pub(crate) fn new(scope: Scope) -> Self {
454 Self { scope }
455 }
456
457 /// This node's DID.
458 pub fn did(&self) -> Did {
459 self.scope.did()
460 }
461
462 /// The namespace this effect is confined to.
463 pub fn namespace(&self) -> &str {
464 self.scope.namespace()
465 }
466
467 /// Put a message on the overlay under this effect's namespace.
468 pub async fn send(&self, to: Did, payload: Bytes) -> Result<()> {
469 self.scope.send(to, payload).await
470 }
471
472 /// Hand the lifecycle capability to an explicitly long-lived engine task.
473 ///
474 /// The interpreter itself must return same-turn feedback from [`Interpret::run`], rather
475 /// than await [`Scope::inject`] while the ordered effect turn is active; a same-task
476 /// re-entrant [`Scope::inject`] fails fast instead of deadlocking on `transition_gate`
477 /// (`Law (Lock order): transition_gate ≺ state`, non-reentrant `transition_gate`).
478 pub(crate) fn lifecycle(&self) -> Scope {
479 self.scope.clone()
480 }
481}
482
483/// Adapter binding a pure [`Protocol`] to its [`Interpret`] shell and owned state; erased to
484/// [`Handler`]. Protocol authors never write this.
485///
486/// Law (Lock order): `transition_gate ≺ state`. `transition_gate` is non-reentrant and spans the
487/// turn's effect application and synchronous feedback fixpoint; `state` is a synchronous leaf
488/// mutex held only across [`Protocol::step`] and never across an `.await`.
489struct Runner<P: Protocol, I> {
490 runner_id: u64,
491 protocol: P,
492 interpret: I,
493 /// Synchronous protocol state (`Law (Lock order): transition_gate ≺ state`, leaf).
494 state: Mutex<P::State>,
495 /// Non-reentrant per-runner turn linearization gate (`Law (Lock order): transition_gate ≺ state`).
496 transition_gate: AsyncMutex<()>,
497 #[cfg(all(test, rings_native))]
498 after_decode_for_test: Option<Arc<dyn Fn() + Send + Sync>>,
499 #[cfg(all(test, rings_native))]
500 after_commit_for_test: Option<Arc<dyn Fn() + Send + Sync>>,
501 #[cfg(all(test, rings_native))]
502 before_gate_wait_for_test: Option<Arc<dyn Fn(bool) + Send + Sync>>,
503}
504
505#[cfg_attr(rings_browser, async_trait::async_trait(?Send))]
506#[cfg_attr(rings_native, async_trait::async_trait)]
507impl<P, I> Handler for Runner<P, I>
508where
509 P: Protocol + MaybeSendSync + 'static,
510 P::State: MaybeSendSync + 'static,
511 P::Effect: MaybeSendSync,
512 I: Interpret<Effect = P::Effect> + MaybeSendSync + 'static,
513{
514 async fn handle(&self, core: &Core, from: Did, payload: Bytes) -> Result<()> {
515 self.ensure_not_reentrant()?;
516 // Boundary: decode raw bytes to a typed event. An undecodable/foreign message is an
517 // explicit drop here, not a silent `Transition::pure` deep in `step`.
518 let event = match self.protocol.decode(Wire {
519 from,
520 me: core.did(),
521 payload: payload.as_ref(),
522 }) {
523 Ok(event) => event,
524 Err(Reject(why)) => {
525 tracing::debug!("drop on {}: {why}", self.protocol.namespace());
526 return Ok(());
527 }
528 };
529
530 #[cfg(all(test, rings_native))]
531 if let Some(observe) = self.after_decode_for_test.as_ref() {
532 observe();
533 }
534 self.run_turn(core, event).await
535 }
536
537 async fn observe_link(&self, core: &Core, fact: LinkFact) -> Result<()> {
538 match self.protocol.link_fact(fact) {
539 Some(event) => self.run_turn(core, event).await,
540 None => Ok(()),
541 }
542 }
543}
544
545impl<P, I> Runner<P, I>
546where
547 P: Protocol + MaybeSendSync + 'static,
548 P::State: MaybeSendSync + 'static,
549 P::Effect: MaybeSendSync,
550 I: Interpret<Effect = P::Effect> + MaybeSendSync + 'static,
551{
552 fn ensure_not_reentrant(&self) -> Result<()> {
553 if is_runner_active(self.runner_id) {
554 return Err(Error::ExtensionError(format!(
555 "re-entrant transition on {:?} while its transition_gate is held by the current task; return synchronous feedback from Interpret::run or spawn a task",
556 self.protocol.namespace()
557 )));
558 }
559 Ok(())
560 }
561
562 /// One turn of `event`: under the transition gate, step it, then run its effects and the
563 /// synchronous feedback fixpoint they produce.
564 ///
565 /// Law (Lock order): `transition_gate ≺ state`; `transition_gate` is non-reentrant and
566 /// same-task re-entry fails fast before awaiting the gate.
567 async fn run_turn(&self, core: &Core, event: P::Event) -> Result<()> {
568 self.ensure_not_reentrant()?;
569 // The transition gate establishes the protocol's linearization order for state commit
570 // and its resulting effect trace. Decode remains outside that order: it has no state or
571 // effects by contract. Holding the gate through interpretation preserves:
572 // commit(A) < commit(B) => applying A's effects ends before applying B's effects begins.
573 // The state mutex itself remains synchronous and never crosses an await.
574 #[cfg(all(test, rings_native))]
575 if let Some(observe) = self.before_gate_wait_for_test.as_ref() {
576 // Witness the real synchronization boundary: false means this task could acquire
577 // the gate immediately; true means another transition owns it at this exact point.
578 observe(self.transition_gate.try_lock().is_none());
579 }
580 let _transition_turn = rings_core::utils::SlowLockGuard::acquire(
581 "Runner::transition_gate",
582 self.transition_gate.lock(),
583 )
584 .await;
585
586 with_active_runner(self.runner_id, async {
587 // Impure region: the state lock is released, while the transition gate keeps this
588 // protocol's effect trace and synchronous feedback fixpoint in commit order. Returned
589 // payloads are reduced before this turn releases the gate, so a later inbound cannot
590 // observe state that predates an effect's own feedback.
591 let namespace = self.protocol.namespace().to_string();
592 let scope = EffectScope::new(Scope::new(core.clone(), namespace.clone()));
593 let mut feedback = VecDeque::new();
594 feedback.push_back(event);
595 let mut feedback_budget = MAX_FIXPOINT_STEPS;
596 while let Some(event) = feedback.pop_front() {
597 if feedback_budget == 0 {
598 return Err(Error::ExtensionError(format!(
599 "feedback fixpoint budget ({MAX_FIXPOINT_STEPS}) exhausted on {namespace:?}"
600 )));
601 }
602 feedback_budget -= 1;
603
604 // Pure region: a brief synchronous state fold. No await crosses `state`; the
605 // feedback queue makes every same-turn effect result part of this fold before a
606 // competing inbound can begin its own transition.
607 let effects = {
608 let mut guard = lock(&self.state)?;
609 let Transition { state, effects } = self.protocol.step(
610 Ctx {
611 did: core.did(),
612 state: guard.deref(),
613 },
614 event,
615 );
616 *guard = state;
617 effects
618 };
619
620 #[cfg(all(test, rings_native))]
621 if let Some(observe) = self.after_commit_for_test.as_ref() {
622 observe();
623 }
624
625 for effect in effects {
626 for payload in self.interpret.run(&scope, effect).await? {
627 match self.protocol.decode(Wire {
628 from: core.did(),
629 me: core.did(),
630 payload: payload.as_ref(),
631 }) {
632 Ok(event) => feedback.push_back(event),
633 Err(Reject(why)) => {
634 tracing::debug!(
635 "drop feedback on {}: {why}",
636 self.protocol.namespace()
637 )
638 }
639 }
640 }
641 }
642 }
643 Ok(())
644 })
645 .await
646 }
647}
648
649/// Registry of `(Protocol, Interpret)` pairs by namespace, plus the router-internal `Core`.
650/// Cheaply cloneable and shared (interior mutability) so the
651/// [`Provider`](crate::provider::Provider) and the [`Backend`](crate::extension::Backend)
652/// serving the core's `ApplicationInbox` see the same table.
653#[derive(Clone)]
654pub struct Extensions {
655 core: Core,
656}
657
658impl Extensions {
659 /// Empty registry over a processor (the source of overlay `send` / `did`), retaining
660 /// `processor` for standalone callers that do not wrap it in a [`Provider`](crate::provider::Provider).
661 pub fn new(processor: Arc<Processor>) -> Self {
662 Self::from_processor_parts(&processor, Some(Arc::clone(&processor)))
663 }
664
665 /// Empty registry holding `processor` weakly so an enclosing [`Provider`](crate::provider::Provider)
666 /// remains the sole strong owner and background [`Backend::serve`](crate::extension::Backend::serve)
667 /// tasks never keep `Processor` or its stores alive after `Provider` drops.
668 pub(crate) fn new_weak(processor: &Arc<Processor>) -> Self {
669 Self::from_processor_parts(processor, None)
670 }
671
672 fn from_processor_parts(
673 processor: &Arc<Processor>,
674 standalone_owner: Option<Arc<Processor>>,
675 ) -> Self {
676 let did = processor.did();
677 let network_id = processor.swarm.network_id();
678 let tasks = processor.tasks().clone();
679 let slot_roster = Arc::clone(processor.swarm.dht().edges());
680 let onion_role = processor.onion_role().clone();
681 let onion_idle_floor = processor.onion_idle_floor();
682 let onion_udp_bind_config = processor.onion_udp_bind_config();
683 let onion_process_epoch = processor.onion_process_epoch();
684 let clock = processor.clock().clone();
685 let rng = processor.rng().clone();
686 Self {
687 core: Core {
688 processor: Arc::downgrade(processor),
689 _standalone_owner: standalone_owner,
690 did,
691 network_id,
692 tasks,
693 slot_roster,
694 onion_role,
695 onion_idle_floor,
696 onion_udp_bind_config,
697 onion_process_epoch,
698 clock,
699 rng,
700 handlers: Arc::new(RwLock::new(HashMap::new())),
701 },
702 }
703 }
704
705 /// The capability handle (overlay `send` / `did` / self-addressed `inject`). `pub(crate)`:
706 /// public holders of an `Extensions` get **registration only** (`register` / `replace` /
707 /// `contains` / `register_many`), never a raw [`Core`]. An extension's local injection is
708 /// exposed through its own typed handle (e.g. `RelayHandle`), so application code cannot use
709 /// a generic inject-any-namespace bus to forge engine-lifecycle commands like the relay's
710 /// `Accepted` / `Untrack`.
711 pub(crate) fn core(&self) -> Core {
712 self.core.clone()
713 }
714
715 /// Register a protocol together with its interpreter under the protocol's namespace.
716 /// Errors if the namespace is already taken — use [`replace`](Extensions::replace) for
717 /// intentional replacement (no more silent overwrite).
718 pub fn register<P, I>(&self, protocol: P, interpret: I) -> Result<()>
719 where
720 P: Protocol + MaybeSendSync + 'static,
721 P::State: MaybeSendSync + 'static,
722 P::Effect: MaybeSendSync,
723 I: Interpret<Effect = P::Effect> + MaybeSendSync + 'static,
724 {
725 self.insert(protocol, interpret, false)
726 }
727
728 /// Like [`register`](Extensions::register) but replaces an existing protocol on the same
729 /// namespace instead of erroring. For deliberate hot-swaps.
730 pub fn replace<P, I>(&self, protocol: P, interpret: I) -> Result<()>
731 where
732 P: Protocol + MaybeSendSync + 'static,
733 P::State: MaybeSendSync + 'static,
734 P::Effect: MaybeSendSync,
735 I: Interpret<Effect = P::Effect> + MaybeSendSync + 'static,
736 {
737 self.insert(protocol, interpret, true)
738 }
739
740 /// Prepare one `(namespace, delegation, runner)` tuple before acquiring the registry write
741 /// lock so `protocol.init()` runs outside the lock and both single and batch registration
742 /// construct `Runner` identically (#1217).
743 fn prepare_runner<P, I>(protocol: P, interpret: I) -> (String, Delegation, Arc<DynHandler>)
744 where
745 P: Protocol + MaybeSendSync + 'static,
746 P::State: MaybeSendSync + 'static,
747 P::Effect: MaybeSendSync,
748 I: Interpret<Effect = P::Effect> + MaybeSendSync + 'static,
749 {
750 let namespace = protocol.namespace().to_string();
751 let delegates = Delegation::of(&protocol);
752 let state = Mutex::new(protocol.init());
753 let runner: Arc<DynHandler> = Arc::new(Runner {
754 runner_id: next_runner_id(),
755 protocol,
756 interpret,
757 state,
758 transition_gate: AsyncMutex::new(()),
759 #[cfg(all(test, rings_native))]
760 after_decode_for_test: None,
761 #[cfg(all(test, rings_native))]
762 after_commit_for_test: None,
763 #[cfg(all(test, rings_native))]
764 before_gate_wait_for_test: None,
765 });
766 (namespace, delegates, runner)
767 }
768
769 /// Register several protocols **atomically**: build every runner, then under a single write
770 /// lock verify that none of their namespaces is taken (by an existing registration or by a
771 /// duplicate within the batch) and insert them all — or change nothing and return `Err`. The
772 /// pairs share the type `P`/`I` (e.g. the relay's TCP + UDP `Relay<T>` instances), so a
773 /// partial install can never leave one namespace claimed while the caller gets no handle.
774 pub fn register_many<P, I>(&self, items: Vec<(P, I)>) -> Result<()>
775 where
776 P: Protocol + MaybeSendSync + 'static,
777 P::State: MaybeSendSync + 'static,
778 P::Effect: MaybeSendSync,
779 I: Interpret<Effect = P::Effect> + MaybeSendSync + 'static,
780 {
781 // Build (namespace, runner) outside the lock.
782 let prepared: Vec<(String, Delegation, Arc<DynHandler>)> = items
783 .into_iter()
784 .map(|(protocol, interpret)| Self::prepare_runner(protocol, interpret))
785 .collect();
786
787 let mut handlers = self.core.handlers.write().map_err(|_| Error::Lock)?;
788 // Check-all (existing table + intra-batch duplicates) before mutating anything.
789 for (index, (namespace, _, _)) in prepared.iter().enumerate() {
790 let duplicate_in_batch = prepared
791 .iter()
792 .take(index)
793 .any(|(seen, _, _)| seen == namespace);
794 if duplicate_in_batch || handlers.contains_key(namespace) {
795 return Err(Error::ExtensionError(format!(
796 "namespace {namespace:?} is already registered"
797 )));
798 }
799 }
800 // All free: publish the declarations and insert the batch under the same write lock.
801 let processor = self.core.upgrade_processor()?;
802 delegation::publish(
803 &processor.swarm,
804 prepared
805 .iter()
806 .map(|(namespace, delegates, _)| (namespace.as_str(), *delegates)),
807 )?;
808 for (namespace, _, runner) in prepared {
809 handlers.insert(namespace, runner);
810 }
811 Ok(())
812 }
813
814 fn insert<P, I>(&self, protocol: P, interpret: I, replace: bool) -> Result<()>
815 where
816 P: Protocol + MaybeSendSync + 'static,
817 P::State: MaybeSendSync + 'static,
818 P::Effect: MaybeSendSync,
819 I: Interpret<Effect = P::Effect> + MaybeSendSync + 'static,
820 {
821 let (namespace, delegates, runner) = Self::prepare_runner(protocol, interpret);
822 let mut handlers = self.core.handlers.write().map_err(|_| Error::Lock)?;
823 if !replace && handlers.contains_key(&namespace) {
824 return Err(Error::ExtensionError(format!(
825 "namespace {namespace:?} is already registered"
826 )));
827 }
828 let processor = self.core.upgrade_processor()?;
829 delegation::publish(&processor.swarm, [(namespace.as_str(), delegates)])?;
830 handlers.insert(namespace, runner);
831 Ok(())
832 }
833
834 /// Whether a namespace is registered.
835 pub fn contains(&self, namespace: &str) -> bool {
836 self.core
837 .handlers
838 .read()
839 .map(|h| h.contains_key(namespace))
840 .unwrap_or(false)
841 }
842
843 /// Whether an encoded envelope's namespace delegates its admission, as core reads it; see
844 /// [`Protocol::delegates_admission`].
845 #[cfg(all(test, rings_native))]
846 pub(crate) fn delegates_admission(&self, envelope: &[u8]) -> bool {
847 self.core
848 .processor
849 .upgrade()
850 .is_some_and(|processor| processor.swarm.delegates_admission(envelope))
851 }
852
853 /// Whether an encoded envelope's namespace delegates its replay, as core reads it; see
854 /// [`Protocol::delegates_replay`].
855 #[cfg(all(test, rings_native))]
856 pub(crate) fn delegates_replay(&self, envelope: &[u8]) -> bool {
857 self.core
858 .processor
859 .upgrade()
860 .is_some_and(|processor| processor.swarm.delegates_replay(envelope))
861 }
862}
863
864#[cfg(all(test, rings_native))]
865mod tests;