Skip to main content

rings_node/processor/
mod.rs

1//! Processor of rings-node rpc server.
2
3use std::collections::BTreeSet;
4use std::num::NonZeroUsize;
5use std::str::FromStr;
6use std::sync::Arc;
7use std::time::Duration;
8
9use bytes::Bytes;
10use futures::future::join_all;
11use rings_core::chunk::ReassemblyLimits;
12use rings_core::dht::Did;
13use rings_core::dht::EntryStorage;
14use rings_core::dht::DEFAULT_FINGER_TABLE_SIZE;
15use rings_core::inspect::DHTInspect;
16use rings_core::lifecycle::StopSource;
17use rings_core::lifecycle::StopToken;
18use rings_core::measure::EvidenceCounters;
19use rings_core::measure::EvidenceDigest;
20use rings_core::measure::EvidenceError;
21use rings_core::measure::EvidencePage;
22use rings_core::measure::MeasureImpl;
23use rings_core::measure::PeerMeasurement;
24use rings_core::measure::PeerMeasurementPage;
25use rings_core::measure::PeerQuality;
26use rings_core::message::DhtProtocolMode;
27use rings_core::message::OriginQuotaConfig;
28use rings_core::message::OriginQuotaCounters;
29use rings_core::message::ReplayStorage;
30use rings_core::storage::MemStorage;
31use rings_core::swarm::storage_api::StoreQuorum;
32use rings_core::swarm::storage_api::StoreReceipt;
33use rings_core::swarm::Swarm;
34use rings_core::swarm::SwarmBuilder;
35#[cfg(all(test, feature = "node"))]
36use rings_core::utils::get_epoch_ms;
37use rings_core::utils::SharedClock;
38use rings_core::utils::SharedRng;
39use rings_rpc::protos::rings_node::*;
40use rings_runtime::sleep;
41use serde::Deserialize;
42use serde::Serialize;
43
44#[cfg(all(test, feature = "node"))]
45use crate::descriptor::RegistryElement;
46use crate::error::Error;
47use crate::error::Result;
48use crate::measure::PeriodicMeasure;
49use crate::observability::HealthSnapshot;
50use crate::observability::MailboxSnapshot;
51use crate::observability::Observability;
52use crate::observability::OperatorSnapshot;
53use crate::observability::PeerRatingSnapshot;
54use crate::observability::SessionKeySnapshot;
55use crate::observability::OPERATOR_SCHEMA_VERSION;
56use crate::observability::PEER_RATING_CAPACITY;
57use crate::onion::circuit::OnionIdleFloor;
58use crate::onion::default_advertise_onion_exit;
59use crate::onion::default_advertise_onion_relay;
60use crate::onion::default_onion_exit_heartbeat_interval_secs;
61use crate::onion::default_onion_exit_policy;
62use crate::onion::default_onion_exit_services;
63use crate::onion::default_onion_exit_ttl_secs;
64use crate::onion::directory;
65use crate::onion::directory::OnionDirectoryReader;
66use crate::onion::proxy::OnionProxyProtocol;
67use crate::onion::proxy::OnionProxyRoute;
68use crate::onion::proxy::OnionProxyTarget;
69use crate::onion::OnionEntryGuardStorage;
70use crate::onion::OnionEntryGuards;
71use crate::onion::OnionExitDescriptor;
72use crate::onion::OnionExitOffer;
73use crate::onion::OnionExitPolicy;
74use crate::onion::OnionExitRegistration;
75use crate::onion::OnionProcessEpoch;
76use crate::onion::OnionProcessEpochCell;
77use crate::onion::OnionRole;
78use crate::onion::OnionServiceName;
79use crate::onion::ONION_EXITS_TOPIC;
80use crate::online::OnlineNodeDescriptor;
81use crate::online::OnlineNodeType;
82use crate::online::ONLINE_NODES_TOPIC;
83use crate::prelude::entry;
84use crate::prelude::wasm_export;
85use crate::prelude::ChordStorageInterface;
86use crate::prelude::ChordStorageInterfaceCacheChecker;
87use crate::prelude::DelegateeKey;
88use crate::registration::default_advertise_presence;
89use crate::registration::default_online_node_heartbeat_interval_secs;
90use crate::registration::default_online_node_ttl_secs;
91use crate::registration::default_online_node_type;
92use crate::registration::early_publish_armed;
93use crate::registration::republish_due;
94use crate::registration::validate_registration_timing;
95use crate::registration::OnlineNodeRegistration;
96use crate::registration::RegistrationContext;
97use crate::registration::RegistrationReadiness;
98use crate::registration::RegistrationTask;
99use crate::release::StoresReleased;
100use crate::tasks::NodeTasks;
101
102const MEASUREMENT_FLUSH_TIMEOUT: Duration = Duration::from_secs(5);
103
104mod builder;
105mod config;
106/// Handshakes: by DID over the overlay, and over a peer's HTTP endpoint.
107pub(crate) mod handshake;
108mod horizon;
109mod messaging;
110mod registration_daemon;
111
112pub use builder::ProcessorBuilder;
113#[cfg(feature = "node")]
114pub(crate) use config::parse_udp_port_range;
115pub use config::register_network_transport_factory;
116pub use config::resolve_network_config_descriptor;
117pub use config::NetworkConfigDescriptor;
118pub use config::NetworkParametersFactory;
119pub use config::NodeNetworkParameters;
120pub use config::ProcessorConfig;
121pub use config::ProcessorConfigSerialized;
122pub use config::SessionRotationCommit;
123pub use config::TransportNetworkConfig;
124pub use config::TurnCredentialMode;
125pub use config::UdpPortRange;
126pub use config::UdpPortRangeError;
127pub use config::WebrtcNetworkParameters;
128pub(crate) use handshake::HandshakeFailure;
129pub(crate) use handshake::HandshakePeer;
130pub use handshake::OfferReplyKind;
131pub use horizon::DelegationHorizon;
132pub(crate) use horizon::SessionKeyRing;
133pub use horizon::SigningState;
134pub use horizon::SIGNING_HORIZON_LEAD_MS;
135pub(crate) use registration_daemon::sleep_unless_stopped;
136
137/// The pause between two reads of the fetch cache while a DHT fetch waits for its reply.
138const DHT_LOOKUP_CACHE_POLL_INTERVAL: Duration = Duration::from_millis(50);
139/// The number of fetch-cache reads a DHT fetch makes before it gives up on a reply.
140const DHT_LOOKUP_CACHE_POLL_ATTEMPTS: u32 = 40;
141
142/// Whether the fetch-cache read numbered `attempt` (from 0) is a DHT fetch's last one.
143const fn is_final_lookup_poll(attempt: u32) -> bool {
144    attempt.saturating_add(1) >= DHT_LOOKUP_CACHE_POLL_ATTEMPTS
145}
146
147/// Processor for rings-node rpc server.
148///
149/// Cloning shares the same node handle; publishes from any clone are serialized
150/// against each other.
151#[derive(Clone)]
152pub struct Processor {
153    /// a swarm instance
154    pub swarm: Arc<Swarm>,
155    /// Live delegatee key and retained unexpired previous keys, shared across clones (#1153).
156    session_keys: Arc<SessionKeyRing>,
157    /// Abstract network parameters customizing this node's transport (#1291).
158    network_parameters: Arc<dyn NodeNetworkParameters>,
159    /// The process epoch `e_n` carried by every onion symbol this process registers (#834 D2):
160    /// drawn fresh at process start, renewed only by the onion admission state.
161    onion_process_epoch: OnionProcessEpochCell,
162    onion_entry_guards: Arc<OnionEntryGuards>,
163    stabilize_interval: Duration,
164    online_node_registration: OnlineNodeRegistration,
165    measure: Option<Arc<PeriodicMeasure>>,
166    /// The release witnesses of the file stores this processor is built over (#1085).
167    stores_released: StoresReleased,
168    /// The stop and the task set of this node (`crate::tasks`), shared by every clone.
169    tasks: NodeTasks,
170    /// Serializes listener generations across every clone and wrapper of this processor.
171    /// Ownership includes graceful maintenance shutdown and measurement flushing.
172    listener_lifecycle_lock: Arc<futures::lock::Mutex<()>>,
173    /// Onion symbols this process registers (#834 D2).
174    onion_role: OnionRole<OnionExitOffer>,
175    /// The cover floor of this node's idle onion links (#880).
176    onion_idle_floor: OnionIdleFloor,
177    /// Socket binding and peer-IP admission settings for native `onion::udp` exits.
178    onion_udp_bind_config: crate::onion::OnionUdpBindConfig,
179    registration_tasks: Vec<Arc<dyn RegistrationTask>>,
180    /// Whether each registration task is stored at its owners (#866), in task order.
181    registration_readiness: Arc<RegistrationReadiness>,
182    /// Process-local bounded recorder backing the authenticated operator surface.
183    observability: Arc<Observability>,
184    /// Optional HTTP(S) proxy for remote JSON-RPC endpoints on native targets.
185    remote_rpc_proxy: Option<crate::remote_endpoint::RemoteRpcProxy>,
186}
187
188impl Drop for Processor {
189    fn drop(&mut self) {
190        self.tasks.stop();
191    }
192}
193
194/// The node error of a DHT operation run under a registration stop: a rerouting wait ended by
195/// the stop is the registration's cooperative stop, anything else an entry error.
196pub(crate) fn stoppable_storage_error(error: rings_core::error::Error) -> Error {
197    match error {
198        rings_core::error::Error::ReroutingStopped => Error::RegistrationStopped,
199        error => Error::EntryError(error),
200    }
201}
202
203impl Processor {
204    /// Get current did
205    pub fn did(&self) -> Did {
206        self.swarm.did()
207    }
208
209    /// Return the [`SharedClock`] capability bound to this processor.
210    pub fn clock(&self) -> &SharedClock {
211        self.swarm.clock()
212    }
213
214    /// Return the [`SharedRng`] capability bound to this processor.
215    pub fn rng(&self) -> &SharedRng {
216        self.swarm.rng()
217    }
218
219    pub(crate) fn delegatee_key(&self) -> DelegateeKey {
220        self.session_keys.current()
221    }
222
223    /// Return the active session key followed by any retained previous keys that have not yet
224    /// expired at `now_ms`, so envelopes sealed to a prior key before descriptor republication
225    /// settles can still be opened (#1153).
226    pub(crate) fn decryption_keys_at(&self, now_ms: u128) -> Vec<DelegateeKey> {
227        self.session_keys.decryption_keys_at(now_ms)
228    }
229
230    /// Mint, validate, persist, and install a replacement session key at `now_ms` through
231    /// [`SessionKeyRing::renew_with`], updating the swarm transport and session-bound transport
232    /// credentials via a strict two-phase commit (#1153, #1291).
233    ///
234    /// # Invariant (Four-Component Two-Phase Transactional Lockstep)
235    ///
236    /// Across every renewal outcome (`MintErr`, `RingValidateErr`, `SwarmValidateErr`,
237    /// `TransportPrepareErr`, `PersistErr`, and `CommitOk`), `(k_ring, k_disk, k_swarm,
238    /// k_transport)` never diverge and **zero compensating rollback** is ever required:
239    /// 1. **Phase 1 (pure validation & preparation, zero side effects)**:
240    ///    - `SessionKeyRing::renew_with` validates delegator DID equality, cryptographic signature,
241    ///      and monotone horizon advancement (`h' > h`).
242    ///    - `Swarm::validate_next_delegatee_key` validates swarm DID and strict horizon monotonicity
243    ///      without mutating swarm state.
244    ///    - `NodeNetworkParameters::prepare_session_key_rotation` derives and strictly parses
245    ///      session-bound transport credentials without mutating live transport state.
246    /// 2. **Single Commit Point**: `persist(next)` writes the validated replacement key to durable
247    ///    storage. If `persist(next)` fails, no in-memory component has been mutated.
248    /// 3. **Phase 2 (infallible in-memory commit)**: `Swarm::commit_delegatee_key_unchecked`,
249    ///    `commit_transport()`, and `SessionKeyRing` state replacement execute infallibly under the
250    ///    session key-ring write lock.
251    pub(crate) fn renew_delegatee_key_with<M, P>(
252        &self,
253        now_ms: u128,
254        mint: M,
255        persist: P,
256    ) -> Result<DelegationHorizon>
257    where
258        M: FnOnce(&DelegateeKey) -> Result<DelegateeKey>,
259        P: FnOnce(&DelegateeKey) -> Result<()>,
260    {
261        let (_next, horizon) = self
262            .session_keys
263            .renew_with(now_ms, mint, |_current, next| {
264                let commit_swarm = self
265                    .swarm
266                    .prepare_delegatee_key_rotation(next)
267                    .map_err(Error::CoreError)?;
268                let commit_transport = self
269                    .network_parameters
270                    .prepare_session_key_rotation(self.swarm.transport(), next)?;
271                persist(next)?;
272                commit_swarm.commit();
273                commit_transport();
274                Ok(())
275            })?;
276        Ok(horizon)
277    }
278
279    /// Return the currently installed session-bound transport credential string on a built-in
280    /// ICE-backed transport, or `None` for custom transports that do not carry ICE credentials.
281    pub fn session_transport_credentials(&self) -> Option<String> {
282        TransportNetworkConfig::session_credentials_of(self.swarm.transport())
283    }
284
285    /// Return the [`NodeNetworkParameters`] customizing this processor's transport.
286    pub fn network_parameters(&self) -> &Arc<dyn NodeNetworkParameters> {
287        &self.network_parameters
288    }
289
290    /// Replace this node's active session key in process at `now_ms`, retaining the previous key
291    /// until its delegation expires and updating the swarm transport (#1153).
292    ///
293    /// Laws:
294    /// - **Monotone horizon**: `h' > h`. A renewal never shortens the signing horizon.
295    /// - **No unsigned gap**: `next` authorizes `self.did()`, verifies at `now_ms`, and is before
296    ///   `h'`.
297    pub fn renew_delegatee_key(
298        &self,
299        next: DelegateeKey,
300        now_ms: u128,
301    ) -> Result<DelegationHorizon> {
302        self.renew_delegatee_key_with(now_ms, |_| Ok(next), |_| Ok(()))
303    }
304
305    /// The signing horizon of this node's own delegation: from it on, the node can send
306    /// nothing unless it renews or restarts with a fresh delegation (#1063, #1153). A native
307    /// daemon renews at `h - lead` when configured with a delegator key and ends at `h`
308    /// otherwise; a browser or FFI embedder reads it here, or as `overlay_ready = false`, and
309    /// acts itself.
310    pub fn signing_horizon(&self) -> DelegationHorizon {
311        self.session_keys.horizon()
312    }
313
314    /// The stop and the task set of this node (`crate::tasks`).
315    pub(crate) fn tasks(&self) -> &NodeTasks {
316        &self.tasks
317    }
318
319    /// The release witnesses of the file stores this processor is built over (#1085).
320    pub(crate) fn stores_released(&self) -> StoresReleased {
321        self.stores_released.clone()
322    }
323
324    #[cfg(all(feature = "browser", target_family = "wasm"))]
325    pub(crate) fn onion_entry_guards(&self) -> &OnionEntryGuards {
326        self.onion_entry_guards.as_ref()
327    }
328
329    pub(crate) fn onion_entry_guards_arc(&self) -> Arc<OnionEntryGuards> {
330        Arc::clone(&self.onion_entry_guards)
331    }
332
333    /// Return the onion symbols this process registers (#834 D2).
334    pub const fn onion_role(&self) -> &OnionRole<OnionExitOffer> {
335        &self.onion_role
336    }
337
338    /// Return the cover floor of this node's idle onion links (#880).
339    pub(crate) const fn onion_idle_floor(&self) -> OnionIdleFloor {
340        self.onion_idle_floor
341    }
342
343    /// Return the socket binding and peer-IP admission settings for native `onion::udp` exits.
344    pub const fn onion_udp_bind_config(&self) -> crate::onion::OnionUdpBindConfig {
345        self.onion_udp_bind_config
346    }
347
348    /// Return the cell of this process's onion epoch `e_n` (#834 D2), shared with the onion
349    /// admission state and the registrations.
350    pub(crate) fn onion_process_epoch(&self) -> OnionProcessEpochCell {
351        self.onion_process_epoch.clone()
352    }
353
354    fn registration_context(&self) -> RegistrationContext<'_> {
355        RegistrationContext::new(self)
356    }
357
358    /// This node's online descriptor under a lease issued at `now_ms` that is fresh for 90 s
359    /// and ends with it, not yet heard.
360    #[cfg(all(test, feature = "node"))]
361    fn online_node_descriptor_at(&self, now_ms: u128) -> Result<OnlineNodeDescriptor> {
362        self.online_node_registration.descriptor_at(
363            &self.registration_context(),
364            crate::registration::LeaseTerms {
365                fresh_for_ms: 90_000,
366                expires_at_ms: now_ms + 90_000,
367            },
368        )
369    }
370
371    /// The registry entry under `topic` whose elements are `descriptors`.
372    #[cfg(all(test, feature = "node"))]
373    pub(crate) fn registry_entry<D: RegistryElement>(
374        topic: &str,
375        descriptors: Vec<D>,
376    ) -> Result<entry::Entry> {
377        let data = descriptors
378            .into_iter()
379            .map(|descriptor| descriptor.to_element().map_err(Error::CoreError))
380            .collect::<Result<Vec<_>>>()?;
381
382        Ok(entry::Entry::new(
383            entry::Entry::gen_did(topic)?,
384            data,
385            entry::EntryKind::Data,
386        ))
387    }
388
389    /// Publish this node's signed online descriptor to the online-node registry.
390    pub async fn publish_online_node_descriptor(&self) -> Result<OnlineNodeDescriptor> {
391        self.online_node_registration
392            .publish_descriptor(&self.registration_context())
393            .await
394    }
395
396    /// List signed online-node descriptors from the registry.
397    ///
398    /// The registry carrier is the join of every reply this node has observed (#864), with its
399    /// own writes applied (#982): it ascends in the lattice order while cached and live, so this
400    /// node lists what it registered itself whichever owner its lookup reaches, but a descriptor
401    /// still leaves it on a tombstone, on an overwrite's reset floor, or at the element cap. Rerouted as [`Self::storage_fetch`] documents.
402    pub async fn lookup_online_nodes(
403        &self,
404        include_expired: bool,
405    ) -> Result<Vec<OnlineNodeDescriptor>> {
406        let entry_key = entry::Entry::gen_did(ONLINE_NODES_TOPIC)?;
407
408        let Some(entry) = self.fetch_storage_entry(entry_key).await? else {
409            return Ok(vec![]);
410        };
411
412        let descriptors = OnlineNodeRegistration::descriptors_from_entry(&entry)
413            .into_iter()
414            .filter(|descriptor| descriptor.matches_dht_protocol(self.swarm.dht_protocol_mode()));
415
416        Ok(OnlineNodeDescriptor::latest_valid_by_did(
417            descriptors,
418            self.clock().now_ms(),
419            self.swarm.network_id(),
420            include_expired,
421        ))
422    }
423
424    /// List signed onion-exit descriptors from the application-layer exit registry.
425    ///
426    /// Like [`Self::lookup_online_nodes`], the carrier read is the join of the observed replies
427    /// (#864) with this node's own writes applied (#982). Rerouted as [`Self::storage_fetch`]
428    /// documents.
429    pub async fn lookup_onion_exits(
430        &self,
431        service: &str,
432        include_expired: bool,
433    ) -> Result<Vec<OnionExitDescriptor>> {
434        let entry_key = entry::Entry::gen_did(ONION_EXITS_TOPIC)?;
435        let service = service.trim();
436
437        let Some(entry) = self.fetch_storage_entry(entry_key).await? else {
438            return Ok(vec![]);
439        };
440
441        Ok(self.select_onion_exits_from_entry(&entry, service, include_expired))
442    }
443
444    /// List signed intermediate `invoke` descriptors from [`crate::onion::ONION_INVOKES_TOPIC`],
445    /// optionally filtered by `shape` and/or canonical `backend` name.
446    pub async fn lookup_onion_invokes(
447        &self,
448        shape: Option<crate::onion::OnionInvokeShape>,
449        backend: &str,
450        include_expired: bool,
451    ) -> Result<Vec<crate::onion::OnionInvokeDescriptor>> {
452        let entry_key = entry::Entry::gen_did(crate::onion::ONION_INVOKES_TOPIC)?;
453        let backend = backend.trim();
454        let Some(entry) = self.fetch_storage_entry(entry_key).await? else {
455            return Ok(vec![]);
456        };
457        Ok(
458            crate::onion::OnionInvokeDescriptor::latest_valid_by_symbol_did(
459                crate::onion::OnionInvokeRegistration::descriptors_from_entry(&entry),
460                self.clock().now_ms(),
461                self.swarm.network_id(),
462                include_expired,
463            )
464            .into_iter()
465            .filter(|desc| shape.is_none_or(|wanted| desc.shape == wanted))
466            .filter(|desc| backend.is_empty() || desc.backend.as_str() == backend)
467            .collect(),
468        )
469    }
470
471    /// Build a guard-closed multi-hop route for an intermediate `invoke` Kleisli pipeline.
472    pub async fn build_onion_pipeline_route(
473        &self,
474        pipeline: &crate::onion::OnionInvokePipeline,
475    ) -> Result<crate::onion::OnionPipelineRoute> {
476        crate::onion::directory::build_onion_pipeline_route(self, pipeline).await
477    }
478
479    /// Build a guard-closed multi-hop route for `pipeline` whose candidate stage
480    /// [`crate::onion::OnionInvokeDescriptor`]s belong to `eligible_stage_dids`.
481    pub async fn build_onion_pipeline_route_for_dids(
482        &self,
483        pipeline: &crate::onion::OnionInvokePipeline,
484        eligible_stage_dids: &std::collections::BTreeSet<Did>,
485    ) -> Result<crate::onion::OnionPipelineRoute> {
486        crate::onion::directory::build_onion_pipeline_route_filtered(self, pipeline, |desc| {
487            eligible_stage_dids.contains(&desc.did)
488        })
489        .await
490    }
491
492    /// Build a guard-closed multi-hop route for `pipeline` whose candidate stage
493    /// [`crate::onion::OnionInvokeDescriptor`]s satisfy `predicate`.
494    pub async fn build_onion_pipeline_route_filtered(
495        &self,
496        pipeline: &crate::onion::OnionInvokePipeline,
497        predicate: impl Fn(&crate::onion::OnionInvokeDescriptor) -> bool,
498    ) -> Result<crate::onion::OnionPipelineRoute> {
499        crate::onion::directory::build_onion_pipeline_route_filtered(self, pipeline, predicate)
500            .await
501    }
502
503    /// Fetch a DHT registry `topic` and return the newest valid [`crate::descriptor::SignedDescriptor`]
504    /// per DID at the processor's current clock (#918).
505    pub async fn lookup_registry_descriptors<D>(
506        &self,
507        topic: &str,
508        include_expired: bool,
509    ) -> Result<Vec<D>>
510    where
511        D: crate::descriptor::SignedDescriptor + crate::descriptor::RegistryElement,
512    {
513        let Some(entry) = self.fetch_topic_entry(topic).await? else {
514            return Ok(Vec::new());
515        };
516        Ok(crate::descriptor::latest_valid_by_did(
517            crate::descriptor::heard_descriptors::<D>(&entry),
518            self.clock().now_ms(),
519            self.swarm.network_id(),
520            include_expired,
521        ))
522    }
523
524    /// Fetch the raw normalized DHT [`entry::Entry`] stored under `topic`, if any.
525    pub async fn fetch_topic_entry(&self, topic: &str) -> Result<Option<entry::Entry>> {
526        let entry_key = entry::Entry::gen_did(topic)?;
527        self.fetch_storage_entry(entry_key).await
528    }
529
530    /// Execute one registration pass for every configured [`RegistrationTask`] on this processor.
531    ///
532    /// Hidden test/simulation helper: production nodes publish registrations exclusively through
533    /// the cooperative daemon started by [`Self::listen`] / [`Self::listen_with`].
534    #[doc(hidden)]
535    pub async fn register_all_once(&self) -> Result<()> {
536        let context = self.registration_context();
537        for task in &self.registration_tasks {
538            task.register_once(&context).await?;
539        }
540        Ok(())
541    }
542
543    /// Select the newest live exit registration per `(DID, service)` of `entry` offering
544    /// `service` (every service when empty).
545    fn select_onion_exits_from_entry(
546        &self,
547        entry: &entry::Entry,
548        service: &str,
549        include_expired: bool,
550    ) -> Vec<OnionExitDescriptor> {
551        OnionExitDescriptor::latest_valid_by_service_did(
552            OnionExitRegistration::descriptors_from_entry(entry),
553            self.clock().now_ms(),
554            self.swarm.network_id(),
555            include_expired,
556        )
557        .into_iter()
558        .filter(|descriptor| service.is_empty() || descriptor.offers_service(service))
559        .collect()
560    }
561
562    pub(crate) async fn fetch_storage_entry(&self, entry_key: Did) -> Result<Option<entry::Entry>> {
563        let stop = StopToken::never();
564        self.fetch_storage_entry_with_stop(entry_key, &stop).await
565    }
566
567    /// Fetch `entry_key` and read the cache once the fetch is answered, stopping early on
568    /// `stop`; the cache holds the join of every reply observed (#864), with this node's own
569    /// writes applied (#982).
570    ///
571    /// A reply is recognised by the fetch's reply marker
572    /// ([`Swarm::storage_fetch_answered_since`] the mark read before the fetch), not by the
573    /// cache holding a value: the cache may hold a value from before this fetch, and a cached
574    /// value is projected at the clock of each read, so it changes with no reply when an element
575    /// crosses its horizon.
576    ///
577    /// A failed fetch is the empty read ([`Self::answer_failed_fetch`]). This serves the
578    /// directory lookups and the registration publisher alike: a publisher whose fetch fails
579    /// chooses what to tombstone from its cached observation instead of abandoning the attempt,
580    /// and its own replaced values are still caught by its record of what it published.
581    ///
582    /// Post: the cache read after the reply, or, if none arrives within the fetch-poll budget,
583    /// the cache read at its end.
584    pub(crate) async fn fetch_storage_entry_with_stop(
585        &self,
586        entry_key: Did,
587        stop: &StopToken,
588    ) -> Result<Option<entry::Entry>> {
589        if stop.should_stop() {
590            return Err(Error::RegistrationStopped);
591        }
592        let mark = self.swarm.storage_fetch_mark();
593        match self
594            .swarm
595            .scoped_storage(stop.clone())
596            .storage_fetch(entry_key)
597            .await
598            .map_err(stoppable_storage_error)
599        {
600            Ok(()) => {}
601            // A stop is the caller's cooperative stop, not a failed read.
602            Err(Error::RegistrationStopped) => return Err(Error::RegistrationStopped),
603            Err(error) => return self.answer_failed_fetch(entry_key, error).await,
604        }
605        for attempt in 0..DHT_LOOKUP_CACHE_POLL_ATTEMPTS {
606            if stop.should_stop() {
607                return Err(Error::RegistrationStopped);
608            }
609            let answered = self
610                .swarm
611                .storage_fetch_answered_since(entry_key, mark)
612                .map_err(Error::EntryError)?;
613            if answered || is_final_lookup_poll(attempt) {
614                break;
615            }
616            if !sleep_unless_stopped(DHT_LOOKUP_CACHE_POLL_INTERVAL, stop, &StopToken::never())
617                .await?
618            {
619                return Err(Error::RegistrationStopped);
620            }
621        }
622        Ok(self.storage_check_cache(entry_key).await)
623    }
624
625    /// Answer a fetch of `entry_key` that failed with `error` as the empty read,
626    /// `cache ⊔ ∅ = cache`: from the live cached carrier, and with `error` only when there is none.
627    async fn answer_failed_fetch(
628        &self,
629        entry_key: Did,
630        error: Error,
631    ) -> Result<Option<entry::Entry>> {
632        let cached = self.storage_check_cache(entry_key).await;
633        if cached.is_some() {
634            tracing::debug!(%entry_key, %error, "storage fetch failed; answering from the cache");
635        }
636        cached.map(Some).ok_or(error)
637    }
638
639    /// Build an onion proxy route for a client target through a target-agnostic proxy config.
640    pub async fn build_onion_proxy_route(
641        &self,
642        proxy: OnionProxyProtocol,
643        target: OnionProxyTarget,
644    ) -> Result<OnionProxyRoute> {
645        directory::build_onion_proxy_route(self, proxy, target).await
646    }
647
648    /// Run stabilization and node registration tasks until this future is dropped or aborted.
649    ///
650    /// This is a long-running task; do not await completion as a readiness signal. Concurrent
651    /// calls on this processor queue, and each call retains ownership through cleanup.
652    pub async fn listen(&self) {
653        self.listen_with(StopToken::never()).await;
654    }
655
656    /// Run stabilization and node registration tasks until `stop` asks them to exit.
657    ///
658    /// Concurrent calls on this processor queue, including calls through any clone or
659    /// provider wrapper. A stop requested while queued is observed after that call acquires
660    /// ownership, so its cleanup cannot overlap the current generation.
661    ///
662    /// The shutdown is cooperative: it waits for the current stabilization or
663    /// registration operation to finish before returning. This avoids dropping
664    /// browser IndexedDB request futures while their JavaScript callbacks are
665    /// still pending.
666    pub async fn listen_with(&self, stop: StopToken) {
667        self.listen_with_started(stop, || {}).await;
668    }
669
670    /// Run one serialized listener generation, notifying `on_started` only after it owns
671    /// the processor lifecycle lock. Ownership remains held through cleanup and measurement
672    /// flushing. Browser promises use this signal to preserve queued-start semantics while
673    /// sharing ownership with native callers.
674    pub(crate) async fn listen_with_started<F>(&self, stop: StopToken, on_started: F)
675    where F: FnOnce() {
676        let _listener_lifecycle_guard = self.listener_lifecycle_lock.lock().await;
677        on_started();
678        self.run_listener_generation_until(stop).await;
679    }
680
681    /// Run one listener generation until `stop` or the node's stop asks it to exit: each is
682    /// forwarded to the one stop the generation observes, so it winds down cooperatively on
683    /// either, and a close (#1085) ends it as the caller's stop does.
684    async fn run_listener_generation_until(&self, stop: StopToken) {
685        let generation = StopSource::new();
686        let node = self.tasks.stop_token();
687        let forward = async {
688            let caller = stop.stopped();
689            let node = node.stopped();
690            futures::pin_mut!(caller, node);
691            let _ = futures::future::select(caller, node).await;
692            generation.request_stop();
693        };
694        let run = self.run_listener_generation(generation.token());
695        futures::pin_mut!(forward, run);
696        if let futures::future::Either::Left(((), run)) =
697            futures::future::select(forward, run).await
698        {
699            run.await;
700        }
701    }
702
703    /// Wait until no listener generation runs: the one running, if any, has ended with its
704    /// cleanup and measurement flush.
705    pub(crate) async fn await_listener_generations(&self) {
706        drop(self.listener_lifecycle_lock.lock().await);
707    }
708
709    /// Run maintenance and registration loops for the generation holding the lifecycle lock.
710    async fn run_listener_generation(&self, stop: StopToken) {
711        let stabilizer = Arc::new(self.swarm.stabilizer());
712        if self.registration_tasks.is_empty() {
713            stabilizer.wait_with(self.stabilize_interval, stop).await;
714        } else {
715            let registration_stop_source = StopSource::new();
716            let registration_stop = registration_stop_source.token();
717            let stabilizer_stop = stop.clone();
718            let stabilization = async {
719                stabilizer
720                    .wait_with(self.stabilize_interval, stabilizer_stop)
721                    .await;
722                registration_stop_source.request_stop();
723            };
724            let _ = futures::future::join(
725                stabilization,
726                self.registration_daemons_with(stop, registration_stop),
727            )
728            .await;
729        }
730        if let Err(error) = self.flush_measurements().await {
731            tracing::error!(%error, "failed to flush measurements during graceful shutdown");
732        }
733    }
734
735    /// Return the processor's listener lifecycle lock for lifecycle tests.
736    #[cfg(test)]
737    pub(crate) fn listener_lifecycle_lock_for_test(&self) -> Arc<futures::lock::Mutex<()>> {
738        self.listener_lifecycle_lock.clone()
739    }
740
741    /// Flush all applied measurement updates with the graceful-shutdown deadline.
742    pub async fn flush_measurements(&self) -> Result<()> {
743        self.flush_measurements_with_timeout(MEASUREMENT_FLUSH_TIMEOUT)
744            .await
745    }
746
747    pub(crate) async fn flush_measurements_with_timeout(&self, timeout: Duration) -> Result<()> {
748        if let Some(measure) = &self.measure {
749            measure.flush_with_timeout(timeout).await?;
750        }
751        Ok(())
752    }
753
754    #[cfg(all(test, rings_native))]
755    pub(crate) async fn record_authenticated_measurement_for_test(
756        &self,
757        peer: Did,
758    ) -> std::result::Result<(), rings_core::measure::MeasureError> {
759        if let Some(measure) = &self.measure {
760            rings_core::measure::Measure::record(
761                measure.as_ref(),
762                peer,
763                rings_core::measure::Authentication::Authenticated,
764                rings_core::measure::MeasurementEvent::Connected,
765            )
766            .await?;
767        }
768        Ok(())
769    }
770
771    /// Disconnect a peer with web3 did.
772    pub async fn disconnect(&self, did: Did) -> Result<()> {
773        self.swarm
774            .disconnect(did)
775            .await
776            .map_err(Error::CloseConnectionError)
777    }
778
779    /// Best-effort voluntary departure (#1057): hand off live relay carriers to remaining
780    /// members and send `Leave { successor_list }` to this node's predecessor and successor head
781    /// before transports close.
782    pub async fn leave(&self) -> Result<()> {
783        self.swarm
784            .leave()
785            .await
786            .map_err(Error::CloseConnectionError)
787    }
788
789    /// Close this node's network: the swarm sends a best-effort departure (`Swarm::leave`,
790    /// #1057), opens no connection from now on and closes every one it has (`Swarm::close`,
791    /// #1098), then the applied measurements are flushed.
792    ///
793    /// These are steps (c) and (d) of [`Provider::close`](crate::provider::Provider::close)
794    /// only: this stops no task and releases no store. A node that stops in a process that
795    /// goes on is closed with `Provider::close`, which also stops the node's tasks and awaits
796    /// the release of its stores (#1085). Each peer sees its connection close at once instead
797    /// of waiting for an ICE timeout.
798    ///
799    /// Both steps run even if the first fails; the first failure is returned.
800    pub async fn close(&self) -> Result<()> {
801        self.close_with_timeout(MEASUREMENT_FLUSH_TIMEOUT).await
802    }
803
804    pub(crate) async fn close_with_timeout(&self, timeout: Duration) -> Result<()> {
805        {
806            let leave = self.leave();
807            let deadline = rings_runtime::sleep(timeout);
808            futures::pin_mut!(leave, deadline);
809            if let futures::future::Either::Right((timer, _)) =
810                futures::future::select(leave, deadline).await
811            {
812                match timer {
813                    Ok(()) => tracing::warn!(
814                        timeout_ms = u64::try_from(timeout.as_millis()).unwrap_or(u64::MAX),
815                        "best-effort departure timed out during processor close"
816                    ),
817                    Err(error) => {
818                        tracing::warn!(?error, "departure timer unavailable during processor close")
819                    }
820                }
821            }
822        }
823        let closed = self
824            .swarm
825            .close()
826            .await
827            .map_err(Error::CloseConnectionError);
828        let flushed = self.flush_measurements_with_timeout(timeout).await;
829        closed.and(flushed)
830    }
831
832    /// check local cache of dht
833    pub async fn storage_check_cache(&self, entry_key: Did) -> Option<entry::Entry> {
834        self.swarm.storage_check_cache(entry_key).await
835    }
836
837    /// Fetch an entry from DHT storage
838    ///
839    /// # Rerouting
840    ///
841    /// Every DHT operation of this processor (fetch, store, append, tombstone, and the
842    /// registry lookups and writes built on them) is rerouted as core's [`ChordStorageInterface`]
843    /// documents (#859): refusals before acceptance are retried on events within a budget, and
844    /// no placement is applied twice. A caller that must bound the wait drops the operation.
845    pub async fn storage_fetch(&self, entry_key: Did) -> Result<()> {
846        self.swarm
847            .storage_fetch(entry_key)
848            .await
849            .map_err(Error::EntryError)
850    }
851
852    /// Store an entry on DHT storage, replacing its payloads.
853    ///
854    /// Each stored payload expires by the element lifetime rule of [`ChordStorageInterface`]
855    /// unless it is written again. Its visibility is that interface's: once this returns `Ok`,
856    /// this node reads the entry (read-your-writes, #982); another node reads it once an owner
857    /// its lookup reaches holds it.
858    ///
859    /// Rerouted as [`Self::storage_fetch`] documents.
860    pub async fn storage_store(&self, entry: entry::Entry) -> Result<()> {
861        self.swarm
862            .storage_store(entry)
863            .await
864            .map_err(Error::EntryError)
865    }
866
867    /// Append data to an entry on DHT storage.
868    ///
869    /// The appended element expires by the element lifetime rule of [`ChordStorageInterface`],
870    /// even while other writes keep the topic alive, unless it is appended again.
871    ///
872    /// Rerouted as [`Self::storage_fetch`] documents.
873    pub async fn storage_append_data(&self, topic: &str, data: Bytes) -> Result<()> {
874        self.swarm
875            .storage_append_data(topic, data)
876            .await
877            .map_err(Error::EntryError)
878    }
879
880    /// Append the elements `data` to the data topic `topic` as one delta, requesting the
881    /// retention bound `now + lifetime_ms`, whose owners report it (core's
882    /// [`storage_extend_reported`](rings_core::swarm::storage_api::ScopedStorage::storage_extend_reported)):
883    /// the receipt resolves once their reports decide `quorum`.
884    ///
885    /// Rerouted as [`Self::storage_fetch`] documents, its rerouting waits ending at `stop`.
886    pub async fn storage_extend_reported(
887        &self,
888        topic: &str,
889        data: Vec<Bytes>,
890        lifetime_ms: u64,
891        quorum: StoreQuorum,
892        stop: &StopToken,
893    ) -> Result<StoreReceipt> {
894        self.swarm
895            .scoped_storage(stop.clone())
896            .storage_extend_reported(topic, data, lifetime_ms, quorum)
897            .await
898            .map_err(Error::EntryError)
899    }
900
901    /// Append `text` to the data topic `topic` as one UTF-8 element: the encoding
902    /// [`Self::fetch_text_elements`] decodes.
903    pub(crate) async fn append_text_element(&self, topic: &str, text: String) -> Result<()> {
904        self.storage_append_data(topic, Bytes::from(text)).await
905    }
906
907    /// The elements of the data topic `topic` past the first `skip`, decoded as UTF-8 text; an
908    /// element that is not UTF-8 is omitted, and a topic not found has no elements.
909    ///
910    /// Law (read-your-writes, #982): on one node, `append_text_element(t, x)` returning `Ok`
911    /// then `fetch_text_elements(t, 0)` contains `x` while the element is live and `t` cached.
912    pub(crate) async fn fetch_text_elements(
913        &self,
914        topic: &str,
915        skip: usize,
916    ) -> Result<Vec<String>> {
917        let Some(entry) = self
918            .fetch_storage_entry(entry::Entry::gen_did(topic)?)
919            .await?
920        else {
921            return Ok(vec![]);
922        };
923        Ok(entry
924            .data
925            .iter()
926            .skip(skip)
927            .filter_map(|element| String::from_utf8(element.to_vec()).ok())
928            .collect())
929    }
930
931    /// Tombstone observed data in an entry on DHT storage.
932    ///
933    /// The removal covers every dot of `data` the storage owner holds, including earlier dots
934    /// forgotten under a later one, and is collected once every add it covers has expired.
935    ///
936    /// Rerouted as [`Self::storage_fetch`] documents.
937    pub async fn storage_tombstone_data(&self, topic: &str, data: Bytes) -> Result<()> {
938        self.swarm
939            .storage_tombstone_data(topic, data)
940            .await
941            .map_err(Error::EntryError)
942    }
943
944    /// Return local measurement counters for a peer, if observed.
945    pub async fn peer_measurement(&self, did: Did) -> Option<PeerMeasurement> {
946        self.swarm.peer_measurement(did).await
947    }
948
949    /// Return every retained local peer measurement.
950    pub async fn peer_measurements(&self) -> Vec<PeerMeasurement> {
951        let mut measurements = self.swarm.peer_measurements().await;
952        measurements.sort_by_key(|measurement| measurement.did);
953        measurements
954    }
955
956    /// Return one bounded page of retained local peer measurements.
957    pub async fn peer_measurements_page(
958        &self,
959        after: Option<Did>,
960        limit: NonZeroUsize,
961    ) -> PeerMeasurementPage {
962        self.swarm.peer_measurements_page(after, limit).await
963    }
964
965    /// Return one bounded page of locally collected provisional receipts.
966    pub async fn provisional_evidence_page(
967        &self,
968        after: Option<EvidenceDigest>,
969        limit: NonZeroUsize,
970    ) -> std::result::Result<EvidencePage<Did>, EvidenceError> {
971        let Some(measure) = &self.measure else {
972            return Err(EvidenceError::StorageUnavailable);
973        };
974        rings_core::measure::Measure::provisional_evidence_page(measure.as_ref(), after, limit)
975            .await
976    }
977
978    /// Return aggregate receipt admission and eviction counters without account labels.
979    pub async fn provisional_evidence_counters(&self) -> EvidenceCounters {
980        match &self.measure {
981            Some(measure) => {
982                rings_core::measure::Measure::provisional_evidence_counters(measure.as_ref()).await
983            }
984            None => EvidenceCounters::default(),
985        }
986    }
987
988    /// Return aggregate final-destination origin-quota drops by lane and reason.
989    pub fn origin_quota_counters(&self) -> OriginQuotaCounters {
990        self.swarm.origin_quota_counters()
991    }
992
993    /// Register this node under the service name `name`.
994    ///
995    /// The registration is one appended element, so it expires by the element lifetime rule of
996    /// [`ChordStorageInterface`] unless it is registered again.
997    pub async fn register_service(&self, name: &str) -> Result<()> {
998        self.append_text_element(name, self.did().to_string())
999            .await
1000            .map_err(|error| match error {
1001                Error::EntryError(error) => Error::ServiceRegisterError(error),
1002                error => error,
1003            })
1004    }
1005
1006    /// get node info
1007    pub async fn get_node_info(&self) -> Result<NodeInfoResponse> {
1008        Ok(NodeInfoResponse {
1009            version: crate::util::build_version(),
1010            swarm: Some(self.swarm.inspect().await.into()),
1011        })
1012    }
1013
1014    /// Assemble the documented v1 operator snapshot without serializing stored entry payloads.
1015    pub async fn operator_snapshot(&self) -> Result<OperatorSnapshot> {
1016        let generated_at_ms = self.clock().now_ms();
1017        let runtime = self.observability.runtime_snapshot(generated_at_ms);
1018        let delegation = self.delegatee_key().delegation();
1019        let expires_at_ms = delegation.expires_at_ms();
1020        let (rotation_succeeded_total, rotation_failed_total) = self.session_keys.rotation_counts();
1021        let mailbox = self
1022            .swarm
1023            .mailbox_storage_inspect()
1024            .await
1025            .map_err(Error::InternalError)?;
1026        let admitted_peer_count = u64::try_from(self.swarm.peers().len()).unwrap_or(u64::MAX);
1027        let has_admitted_peer = admitted_peer_count > 0;
1028        let dht = DHTInspect::inspect(&self.swarm.dht());
1029        let has_successor = !dht.successors.is_empty();
1030        let has_predecessor = dht.predecessor.is_some();
1031        let mut peer_ratings = self.peer_measurements().await;
1032        peer_ratings.sort_unstable_by_key(|measurement| measurement.did);
1033        peer_ratings.truncate(PEER_RATING_CAPACITY);
1034        let peer_ratings = peer_ratings
1035            .into_iter()
1036            .map(|measurement| PeerRatingSnapshot {
1037                peer: measurement.did.to_string(),
1038                reliability: peer_quality_name(measurement.quality),
1039                credit_score: measurement.credit_score.as_f64(),
1040                sent: measurement.evidence.sent,
1041                failed_to_send: measurement.evidence.failed_to_send,
1042                received: measurement.evidence.received,
1043                failed_to_receive: measurement.evidence.failed_to_receive,
1044            })
1045            .collect();
1046
1047        Ok(OperatorSnapshot {
1048            schema_version: OPERATOR_SCHEMA_VERSION,
1049            generated_at_ms,
1050            process_started_at_ms: self.observability.process_started_at_ms(),
1051            counter_scope: "node_local_process_lifetime",
1052            messages: runtime.messages,
1053            recent_messages: runtime.recent_messages,
1054            session_key: SessionKeySnapshot {
1055                valid: !delegation.is_expired_at(generated_at_ms),
1056                created_at_ms: delegation.created_at_ms(),
1057                expires_at_ms,
1058                remaining_ms: expires_at_ms.saturating_sub(generated_at_ms),
1059                rotation_succeeded_total,
1060                rotation_failed_total,
1061                runtime_rotation_supported: true,
1062            },
1063            mailboxes: MailboxSnapshot {
1064                registered: mailbox.registered,
1065                held_messages: mailbox.held_messages,
1066                stored_total: runtime.messages.stored,
1067            },
1068            dht_lookups: runtime.dht_lookups,
1069            peer_ratings,
1070            health: HealthSnapshot {
1071                process_api_healthy: true,
1072                admitted_peer_count,
1073                has_admitted_peer,
1074                has_successor,
1075                has_predecessor,
1076                overlay_ready: has_admitted_peer
1077                    && has_successor
1078                    && self.signing_horizon().signs_at(generated_at_ms),
1079            },
1080        })
1081    }
1082}
1083
1084/// Stable text form of one advisory local peer-quality class.
1085const fn peer_quality_name(quality: PeerQuality) -> &'static str {
1086    match quality {
1087        PeerQuality::Healthy => "healthy",
1088        PeerQuality::Unknown => "unknown",
1089        PeerQuality::Degraded => "degraded",
1090    }
1091}
1092
1093#[cfg_attr(all(feature = "browser", target_family = "wasm"), async_trait::async_trait(?Send))]
1094#[cfg_attr(
1095    not(all(feature = "browser", target_family = "wasm")),
1096    async_trait::async_trait
1097)]
1098impl OnionDirectoryReader for Processor {
1099    fn local_did(&self) -> Did {
1100        self.did()
1101    }
1102
1103    fn dht_protocol_mode(&self) -> DhtProtocolMode {
1104        self.swarm.dht_protocol_mode()
1105    }
1106
1107    async fn live_online_nodes(&self) -> Result<Vec<OnlineNodeDescriptor>> {
1108        self.lookup_online_nodes(false).await
1109    }
1110
1111    async fn live_onion_exits(&self, service: &str) -> Result<Vec<OnionExitDescriptor>> {
1112        self.lookup_onion_exits(service, false).await
1113    }
1114
1115    async fn live_onion_invokes(&self) -> Result<Vec<crate::onion::OnionInvokeDescriptor>> {
1116        self.lookup_onion_invokes(None, "", false).await
1117    }
1118
1119    async fn peer_qualities(&self) -> Vec<(Did, PeerQuality)> {
1120        self.peer_measurements()
1121            .await
1122            .into_iter()
1123            .map(|measurement| (measurement.did, measurement.quality))
1124            .collect()
1125    }
1126
1127    fn direct_peer_dids(&self) -> BTreeSet<Did> {
1128        let local = self.did();
1129        self.swarm
1130            .peer_dids()
1131            .into_iter()
1132            .filter(|did| *did != local)
1133            .collect()
1134    }
1135
1136    fn onion_entry_guards(&self) -> &OnionEntryGuards {
1137        self.onion_entry_guards.as_ref()
1138    }
1139
1140    fn now_ms(&self) -> u128 {
1141        self.clock().now_ms()
1142    }
1143
1144    fn route_rng(&self) -> SharedRng {
1145        self.rng().clone()
1146    }
1147}
1148
1149#[cfg(all(test, feature = "node"))]
1150mod tests;