Skip to main content

rings_node/processor/
builder.rs

1use rings_core::dht::RemovalStorage;
2use rings_core::utils::SharedClock;
3use rings_core::utils::SharedRng;
4
5use super::config::validate_dht_virtual_nodes;
6use super::config::validate_onion_role_config;
7use super::*;
8use crate::consts::DATA_REDUNDANT;
9#[cfg(rings_native)]
10use crate::dns_relay::ServiceOffer;
11#[cfg(rings_native)]
12use crate::dns_relay::ServiceRegistration;
13use crate::mail::registration::MailOffer;
14use crate::mail::registration::MailRegistration;
15use crate::prelude::rings_core::dht::RelayReplication;
16
17/// ProcessorBuilder is used to initialize a [Processor] instance.
18pub struct ProcessorBuilder {
19    pub(in crate::processor) network_id: u32,
20    pub(in crate::processor) network_parameters: Arc<dyn NodeNetworkParameters>,
21    pub(in crate::processor) delegatee_key: DelegateeKey,
22    pub(in crate::processor) onion_process_epoch: Option<OnionProcessEpoch>,
23    pub(in crate::processor) clock: SharedClock,
24    pub(in crate::processor) rng: SharedRng,
25    pub(in crate::processor) storage: Option<EntryStorage>,
26    pub(in crate::processor) relay_storage: Option<EntryStorage>,
27    pub(in crate::processor) removal_storage: Option<RemovalStorage>,
28    pub(in crate::processor) relay_replication: Option<RelayReplication>,
29    pub(in crate::processor) replay_storage: Option<ReplayStorage>,
30    pub(in crate::processor) origin_quota: OriginQuotaConfig,
31    pub(in crate::processor) onion_entry_guard_storage: Option<OnionEntryGuardStorage>,
32    pub(in crate::processor) measure: Option<Arc<PeriodicMeasure>>,
33    /// The release witnesses of the file stores the processor is built over (#1085).
34    pub(in crate::processor) stores_released: StoresReleased,
35    pub(in crate::processor) stabilize_interval: Duration,
36    pub(in crate::processor) online_node_heartbeat_interval: Duration,
37    pub(in crate::processor) online_node_ttl: Duration,
38    pub(in crate::processor) online_node_type: OnlineNodeType,
39    pub(in crate::processor) advertise_presence: bool,
40    pub(in crate::processor) dht_virtual_nodes: u16,
41    pub(in crate::processor) onion_role: OnionRole<OnionExitOffer>,
42    pub(in crate::processor) onion_exit_heartbeat_interval: Duration,
43    pub(in crate::processor) onion_exit_ttl: Duration,
44    pub(in crate::processor) onion_idle_floor: OnionIdleFloor,
45    pub(in crate::processor) onion_udp_bind_config: crate::onion::OnionUdpBindConfig,
46    pub(in crate::processor) dht_finger_table_size: usize,
47    pub(in crate::processor) reassembly_limits: ReassemblyLimits,
48    /// An observer chained after the processor's own `Observability`.
49    pub(in crate::processor) observer: Option<rings_core::swarm::observer::SharedSwarmObserver>,
50    /// The heartbeat announcing this node's services through DNS relays (#1049), if any.
51    #[cfg(rings_native)]
52    pub(in crate::processor) service_registration: Option<Arc<dyn RegistrationTask>>,
53    /// The heartbeat of this node's mail descriptor (#1117), if it takes mail.
54    pub(in crate::processor) mail_registration: Option<Arc<dyn RegistrationTask>>,
55    /// Custom periodic DHT registration tasks attached by external service crates.
56    pub(in crate::processor) extra_registrations: Vec<Arc<dyn RegistrationTask>>,
57    /// Optional HTTP(S) proxy for remote JSON-RPC endpoints on native targets.
58    pub(in crate::processor) remote_rpc_proxy: Option<crate::remote_endpoint::RemoteRpcProxy>,
59}
60
61impl ProcessorBuilder {
62    /// initialize a [ProcessorBuilder] with a serialized [ProcessorConfig].
63    pub fn from_serialized(config: &str) -> Result<Self> {
64        let config = ProcessorConfig::from_str(config)?;
65        Self::from_config(&config)
66    }
67
68    /// initialize a [ProcessorBuilder] with a [ProcessorConfig].
69    pub fn from_config(config: &ProcessorConfig) -> Result<Self> {
70        Ok(Self {
71            network_id: config.network_id,
72            network_parameters: Arc::clone(&config.network_parameters),
73            delegatee_key: config.delegatee_key.clone(),
74            onion_process_epoch: None,
75            clock: config.clock.clone(),
76            rng: SharedRng::system(),
77            storage: None,
78            relay_storage: None,
79            removal_storage: None,
80            relay_replication: None,
81            replay_storage: None,
82            origin_quota: config.origin_quota,
83            onion_entry_guard_storage: None,
84            measure: None,
85            stores_released: StoresReleased::default(),
86            stabilize_interval: config.stabilize_interval,
87            online_node_heartbeat_interval: config.online_node_heartbeat_interval,
88            online_node_ttl: config.online_node_ttl,
89            online_node_type: config.online_node_type.clone(),
90            advertise_presence: config.advertise_presence,
91            dht_virtual_nodes: config.dht_virtual_nodes,
92            onion_role: config.onion_role.clone(),
93            onion_exit_heartbeat_interval: config.onion_exit_heartbeat_interval,
94            onion_exit_ttl: config.onion_exit_ttl,
95            onion_idle_floor: OnionIdleFloor::DEFAULT,
96            onion_udp_bind_config: crate::onion::OnionUdpBindConfig::default(),
97            dht_finger_table_size: DEFAULT_FINGER_TABLE_SIZE,
98            reassembly_limits: ReassemblyLimits::production(),
99            observer: None,
100            #[cfg(rings_native)]
101            service_registration: None,
102            mail_registration: None,
103            extra_registrations: Vec::new(),
104            remote_rpc_proxy: config.remote_rpc_proxy.clone(),
105        })
106    }
107
108    /// Announce `offer` through DNS relays: the processor publishes this node's service
109    /// descriptor on every heartbeat of the offer (#1049).
110    #[cfg(rings_native)]
111    pub fn announce_services(mut self, offer: ServiceOffer) -> Self {
112        let did = self.delegatee_key.delegator_did();
113        self.service_registration = Some(Arc::new(ServiceRegistration::new(did, offer)));
114        self
115    }
116
117    /// Take mail at `did@domain` through mail gateways (#1117): the processor publishes this
118    /// node's mail descriptor, which names its delegatee key, on every heartbeat of `offer`.
119    pub fn receive_mail(mut self, offer: MailOffer) -> Self {
120        let did = self.delegatee_key.delegator_did();
121        self.mail_registration = Some(Arc::new(MailRegistration::new(did, offer)));
122        self
123    }
124
125    /// Attach an external periodic DHT [`RegistrationTask`] so the processor publishes its lease
126    /// descriptor on every heartbeat and on the first admitted edge (#855, #918).
127    pub fn register_task(mut self, task: Arc<dyn RegistrationTask>) -> Self {
128        self.extra_registrations.push(task);
129        self
130    }
131
132    /// Chain `observer` after the processor's own `Observability`, an open hook for embedders
133    /// to observe the swarm's message and lookup activity. `SwarmBuilder::observer` offers the
134    /// same for a bare swarm.
135    ///
136    /// Contract:
137    /// - **Synchronous and bounded.** The observer is called synchronously on the send and
138    ///   receive paths, so it must not block, wait or do slow work; see
139    ///   [`SwarmObserver`](rings_core::swarm::observer::SwarmObserver).
140    /// - **After the processor's recorder.** It runs after the processor's own
141    ///   `Observability`, which alone feeds `/status?view=observability`, so installing an
142    ///   observer leaves that status output unchanged.
143    /// - **Bounded data.** Message observations carry no payload, key or identifier: only the
144    ///   activity, the scheduling category, the compile-time message class and the outcome.
145    ///   Lookup events carry a correlation key (a transaction id or a resource DID) so start and
146    ///   finish can be paired; an exporter must aggregate or redact it, never use it as a label.
147    /// - **One extra observer.** A later call replaces the observer set by an earlier one.
148    pub fn observer(mut self, observer: rings_core::swarm::observer::SharedSwarmObserver) -> Self {
149        self.observer = Some(observer);
150        self
151    }
152
153    /// Set the storage for the processor.
154    pub fn storage(mut self, storage: EntryStorage) -> Self {
155        self.storage = Some(storage);
156        self
157    }
158
159    /// Set the storage of the relay-inbox namespace (`SwarmBuilder::relay_storage`): a
160    /// `RecordAuthority::Retained` store, so held mail survives a crash and is never evicted
161    /// (#1021). Without one, the node takes custody of no relay carrier.
162    pub fn relay_storage(mut self, storage: EntryStorage) -> Self {
163        self.relay_storage = Some(storage);
164        self
165    }
166
167    /// Set the storage of the data namespace's remove sides (`SwarmBuilder::removal_storage`):
168    /// a `RecordAuthority::Retained` store, so a remove survives a crash and is never evicted
169    /// before it is stable (#920). Without one, the remove sides are kept in memory.
170    pub fn removal_storage(mut self, storage: RemovalStorage) -> Self {
171        self.removal_storage = Some(storage);
172        self
173    }
174
175    /// Set how relay custody is replicated (#777): the members `r` each carrier is replicated
176    /// to, and how long the node is online before it holds relay mail. By default `r` is 8 and
177    /// the age gate is 2 minutes, raised to four stabilization periods when those are longer
178    /// (`Law (Age gate)` of durable-records); a value set here is taken as given.
179    pub fn relay_replication(mut self, replication: RelayReplication) -> Self {
180        self.relay_replication = Some(replication);
181        self
182    }
183
184    /// Set durable destination-scoped transaction replay storage: an authoritative store.
185    /// Without one, the processor refuses every replay transition, so it neither sends nor
186    /// accepts a transaction (`SwarmBuilder::replay_storage`, #1022).
187    pub fn replay_storage(mut self, storage: ReplayStorage) -> Self {
188        self.replay_storage = Some(storage);
189        self
190    }
191
192    /// Set final-destination per-origin message and byte-rate quotas.
193    pub fn origin_quota(mut self, config: OriginQuotaConfig) -> Self {
194        self.origin_quota = config;
195        self
196    }
197
198    /// Set the local entry-guard storage for onion route selection.
199    pub fn onion_entry_guard_storage(mut self, storage: OnionEntryGuardStorage) -> Self {
200        self.onion_entry_guard_storage = Some(storage);
201        self
202    }
203
204    /// Set the measure for the processor.
205    pub fn measure(mut self, implement: PeriodicMeasure) -> Self {
206        self.measure = Some(Arc::new(implement));
207        self
208    }
209
210    /// Name the release witnesses of the file stores this processor is built over, which
211    /// [`Provider::close`](crate::provider::Provider::close) awaits (#1085). A store given to the
212    /// builder without its witness is not awaited by a close.
213    pub fn stores_released(mut self, released: StoresReleased) -> Self {
214        self.stores_released = released;
215        self
216    }
217
218    /// Set the number of DHT finger-table slots for the processor's swarm.
219    pub fn dht_finger_table_size(mut self, size: usize) -> Self {
220        self.dht_finger_table_size = size;
221        self
222    }
223
224    /// Set storage-only virtual positions derived per physical peer.
225    ///
226    /// Serialized configs reject values above
227    /// [`rings_core::dht::MAX_STORAGE_VIRTUAL_POSITIONS_PER_OWNER`]. This
228    /// builder setter is infallible for direct programmatic use; the core swarm
229    /// builder normalizes the value once before storage ownership and protocol
230    /// advertisement are created.
231    pub fn dht_virtual_nodes(mut self, positions_per_peer: u16) -> Self {
232        self.dht_virtual_nodes = positions_per_peer;
233        self
234    }
235
236    /// Set inbound chunk reassembly limits for the processor's swarm.
237    pub fn reassembly_limits(mut self, limits: ReassemblyLimits) -> Self {
238        self.reassembly_limits = limits;
239        self
240    }
241
242    /// Set the runtime family advertised in the online-node registry.
243    pub fn online_node_type(mut self, node_type: OnlineNodeType) -> Self {
244        self.online_node_type = node_type;
245        self
246    }
247
248    /// Set whether listen() advertises this node's presence.
249    pub fn advertise_presence(mut self, advertise: bool) -> Self {
250        self.advertise_presence = advertise;
251        self
252    }
253
254    /// Set the cover floor of this node's idle onion links (#880); the default is one unit per
255    /// second, and a constrained node (a browser) may lower it.
256    pub fn onion_idle_floor(mut self, floor: OnionIdleFloor) -> Self {
257        self.onion_idle_floor = floor;
258        self
259    }
260
261    /// Configure OS UDP socket binding and peer-IP admission for `onion::udp` exit sessions.
262    pub fn onion_udp_bind_config(mut self, config: crate::onion::OnionUdpBindConfig) -> Self {
263        self.onion_udp_bind_config = config;
264        self
265    }
266
267    /// Set the onion symbols this process registers (#834 D2).
268    pub fn onion_role(mut self, role: OnionRole<OnionExitOffer>) -> Self {
269        self.onion_role = role;
270        self
271    }
272
273    /// Return the onion symbols currently configured on this builder.
274    pub const fn configured_onion_role(&self) -> &OnionRole<OnionExitOffer> {
275        &self.onion_role
276    }
277
278    /// Override the initial onion process epoch instead of drawing one from the builder's RNG.
279    pub fn onion_process_epoch(mut self, epoch: OnionProcessEpoch) -> Self {
280        self.onion_process_epoch = Some(epoch);
281        self
282    }
283
284    /// Inject a custom [`SharedClock`] capability for deterministic protocol and session time.
285    pub fn clock(mut self, clock: SharedClock) -> Self {
286        self.clock = clock;
287        self
288    }
289
290    /// Inject a custom [`SharedRng`] capability for deterministic protocol and session randomness.
291    pub fn rng(mut self, rng: SharedRng) -> Self {
292        self.rng = rng;
293        self
294    }
295
296    /// Inject custom [`NodeNetworkParameters`] to customize the processor's transport (#1291).
297    pub fn network_parameters<P>(mut self, params: P) -> Self
298    where P: NodeNetworkParameters + 'static {
299        self.network_parameters = Arc::new(params);
300        self
301    }
302
303    /// Route native remote JSON-RPC requests (`nodeDid`, `answerOffer`, `acceptAnswer`) through
304    /// `proxy` instead of connecting directly.
305    pub fn remote_rpc_proxy(mut self, proxy: crate::remote_endpoint::RemoteRpcProxy) -> Self {
306        self.remote_rpc_proxy = Some(proxy);
307        self
308    }
309
310    /// Build the [Processor].
311    pub fn build(self) -> Result<Processor> {
312        let now_ms = self.clock.now_ms();
313        self.build_at(now_ms)
314    }
315
316    /// Build the [Processor] validating delegation liveness and signing horizon at `now_ms`.
317    pub(crate) fn build_at(self, now_ms: u128) -> Result<Processor> {
318        self.validate()?;
319        self.delegatee_key
320            .verify_at(now_ms)
321            .map_err(|e| Error::VerifyError(e.to_string()))?;
322        let delegation = self.delegatee_key.delegation();
323        // A process that could not send its first frame is refused, not started mute (#1063).
324        DelegationHorizon::of(&delegation).admitted_at(now_ms)?;
325
326        let storage = self.storage.unwrap_or_else(|| Box::new(MemStorage::new()));
327        let onion_entry_guard_storage = self
328            .onion_entry_guard_storage
329            .unwrap_or_else(|| Box::new(MemStorage::new()));
330        let endpoint_hint = self.network_parameters.endpoint_hint().map(str::to_owned);
331        let onion_udp_bind_config = self
332            .onion_udp_bind_config
333            .with_endpoint_hint_fallback(endpoint_hint.as_deref());
334        let initial_epoch = self
335            .onion_process_epoch
336            .unwrap_or_else(|| OnionProcessEpoch::from_rng(&mut self.rng.lock_rng()));
337        let onion_process_epoch = OnionProcessEpochCell::new(initial_epoch);
338        let delegatee_key = self.delegatee_key.clone();
339        let online_node_registration = OnlineNodeRegistration::new_with_clock(
340            self.online_node_heartbeat_interval,
341            self.online_node_ttl,
342            self.online_node_type.clone(),
343            endpoint_hint,
344            self.onion_role
345                .registers_relay()
346                .then(|| onion_process_epoch.clone()),
347            self.clock.clone(),
348        );
349        let mut registration_tasks: Vec<Arc<dyn RegistrationTask>> = Vec::new();
350        if self.advertise_presence {
351            registration_tasks.push(Arc::new(online_node_registration.clone()));
352        }
353        if let Some(offer) = self.onion_role.exit() {
354            let onion_exit_registration = OnionExitRegistration::new_with_clock(
355                self.onion_exit_heartbeat_interval,
356                self.onion_exit_ttl,
357                self.online_node_type.clone(),
358                offer.clone(),
359                onion_process_epoch.clone(),
360                self.clock.clone(),
361            );
362            registration_tasks.push(Arc::new(onion_exit_registration));
363        }
364        if let Some(offer) = self.onion_role.invoke() {
365            let onion_invoke_registration = crate::onion::OnionInvokeRegistration::new_with_clock(
366                self.onion_exit_heartbeat_interval,
367                self.onion_exit_ttl,
368                self.online_node_type,
369                offer.clone(),
370                onion_process_epoch.clone(),
371                self.clock.clone(),
372            );
373            registration_tasks.push(Arc::new(onion_invoke_registration));
374        }
375        #[cfg(rings_native)]
376        registration_tasks.extend(self.service_registration);
377        registration_tasks.extend(self.mail_registration);
378        registration_tasks.extend(self.extra_registrations);
379
380        // One recorder is shared between core protocol hooks and node-level snapshot assembly.
381        let observability = Arc::new(crate::observability::Observability::new_with_clock(
382            self.clock.clone(),
383        ));
384        let shared_transport = self
385            .network_parameters
386            .build_transport(&self.delegatee_key)?;
387
388        let mut swarm_builder = SwarmBuilder::new(
389            self.network_id,
390            shared_transport,
391            storage,
392            self.delegatee_key,
393        );
394        swarm_builder = swarm_builder.dht_storage_redundancy(DATA_REDUNDANT);
395        swarm_builder = swarm_builder.clock(self.clock);
396        swarm_builder = swarm_builder.rng(self.rng);
397        swarm_builder = swarm_builder.dht_finger_table_size(self.dht_finger_table_size);
398        swarm_builder = swarm_builder.dht_virtual_nodes(self.dht_virtual_nodes);
399        swarm_builder = swarm_builder.reassembly_limits(self.reassembly_limits);
400        if let Some(replay_storage) = self.replay_storage {
401            swarm_builder = swarm_builder.replay_storage(replay_storage);
402        }
403        if let Some(relay_storage) = self.relay_storage {
404            swarm_builder = swarm_builder.relay_storage(relay_storage);
405        }
406        if let Some(removal_storage) = self.removal_storage {
407            swarm_builder = swarm_builder.removal_storage(removal_storage);
408        }
409        let stabilization_periods_ms =
410            u64::try_from(self.stabilize_interval.saturating_mul(4).as_millis())
411                .unwrap_or(u64::MAX);
412        let relay_replication = self.relay_replication.unwrap_or_else(|| {
413            let default = RelayReplication::default();
414            RelayReplication {
415                age_gate_ms: default.age_gate_ms.max(stabilization_periods_ms),
416                ..default
417            }
418        });
419        swarm_builder = swarm_builder.relay_replication(relay_replication);
420        swarm_builder = swarm_builder.origin_quota(self.origin_quota);
421        let observer: rings_core::swarm::observer::SharedSwarmObserver = match self.observer {
422            Some(extra) => Arc::new(ChainedObserver {
423                first: observability.clone(),
424                second: extra,
425            }),
426            None => observability.clone(),
427        };
428        swarm_builder = swarm_builder.observer(observer);
429
430        let measure = self.measure;
431        if let Some(measure) = &measure {
432            let implementation: MeasureImpl = measure.clone();
433            swarm_builder = swarm_builder.measure(implementation);
434        }
435        let swarm = Arc::new(swarm_builder.build());
436        let local_did = swarm.did();
437
438        Ok(Processor {
439            swarm,
440            session_keys: Arc::new(SessionKeyRing::new(delegatee_key)),
441            network_parameters: self.network_parameters,
442            onion_process_epoch,
443            onion_entry_guards: Arc::new(OnionEntryGuards::new_for_did(
444                onion_entry_guard_storage,
445                local_did,
446            )),
447            stabilize_interval: self.stabilize_interval,
448            online_node_registration,
449            measure,
450            stores_released: self.stores_released,
451            tasks: NodeTasks::new(),
452            listener_lifecycle_lock: Arc::new(futures::lock::Mutex::new(())),
453            onion_role: self.onion_role,
454            onion_idle_floor: self.onion_idle_floor,
455            onion_udp_bind_config,
456            registration_readiness: Arc::new(RegistrationReadiness::new(registration_tasks.len())),
457            registration_tasks,
458            observability,
459            remote_rpc_proxy: self.remote_rpc_proxy,
460        })
461    }
462
463    /// Validate the complete builder state at the single runtime construction boundary.
464    ///
465    /// Performing these checks after all builder mutations guarantees that every
466    /// native, browser, and programmatic entrance rejects the same illegal role,
467    /// schedule, and virtual-node combinations.
468    fn validate(&self) -> Result<()> {
469        #[cfg(rings_browser)]
470        if self.remote_rpc_proxy.is_some() {
471            return Err(Error::InvalidConfig(
472                "remote_rpc_proxy_url is supported only on native targets".to_string(),
473            ));
474        }
475        validate_dht_virtual_nodes(self.dht_virtual_nodes)?;
476        validate_registration_timing(
477            "online_node",
478            "advertise_presence",
479            self.advertise_presence,
480            self.online_node_heartbeat_interval,
481            self.online_node_ttl,
482        )?;
483        validate_registration_timing(
484            "onion_exit",
485            "advertise_onion_exit",
486            self.onion_role.exit().is_some() || self.onion_role.invoke().is_some(),
487            self.onion_exit_heartbeat_interval,
488            self.onion_exit_ttl,
489        )?;
490        validate_onion_role_config(self.advertise_presence, &self.onion_role)
491    }
492}
493
494/// An observer that forwards every observation to two observers, in order.
495struct ChainedObserver {
496    first: rings_core::swarm::observer::SharedSwarmObserver,
497    second: rings_core::swarm::observer::SharedSwarmObserver,
498}
499
500impl rings_core::swarm::observer::SwarmObserver for ChainedObserver {
501    fn observe_message(&self, observation: rings_core::swarm::observer::MessageObservation) {
502        self.first.observe_message(observation);
503        self.second.observe_message(observation);
504    }
505
506    fn lookup_started(
507        &self,
508        kind: rings_core::swarm::observer::LookupKind,
509        correlation: rings_core::swarm::observer::LookupCorrelation,
510    ) {
511        self.first.lookup_started(kind, correlation);
512        self.second.lookup_started(kind, correlation);
513    }
514
515    fn lookup_finished(
516        &self,
517        kind: rings_core::swarm::observer::LookupKind,
518        correlation: rings_core::swarm::observer::LookupCorrelation,
519        outcome: rings_core::swarm::observer::LookupOutcome,
520    ) {
521        self.first.lookup_finished(kind, correlation, outcome);
522        self.second.lookup_finished(kind, correlation, outcome);
523    }
524}