Skip to main content

rings_node/processor/
registration_daemon.rs

1//! The registration daemons of a processor, one per registration task. A daemon publishes at
2//! every heartbeat, and early at the first admitted edge after a heartbeat that began alone
3//! (#855). It asks for store reports until its registration is ready (#866).
4
5use super::*;
6
7/// Sleep `interval` unless `stop` or `sibling_stop` fires first: `Ok(true)` once the interval
8/// has elapsed, `Ok(false)` on a stop. The pause of every periodic node task between two runs.
9pub(crate) async fn sleep_unless_stopped(
10    interval: Duration,
11    stop: &StopToken,
12    sibling_stop: &StopToken,
13) -> Result<bool> {
14    use futures::future::select;
15    use futures::pin_mut;
16
17    let stopped = async {
18        let own_stop = stop.stopped();
19        let maintenance_stop = sibling_stop.stopped();
20        pin_mut!(own_stop, maintenance_stop);
21        let _ = select(own_stop, maintenance_stop).await;
22    };
23    let interval_elapsed = sleep(interval);
24    pin_mut!(stopped, interval_elapsed);
25    match select(interval_elapsed, stopped).await {
26        futures::future::Either::Left((result, _)) => {
27            result?;
28            Ok(true)
29        }
30        futures::future::Either::Right(((), _)) => Ok(false),
31    }
32}
33
34/// What starts a registration publish after the first: its heartbeat, or an early publish at
35/// its first admitted edge (#855).
36#[derive(Clone, Copy, Debug, Eq, PartialEq)]
37enum RegistrationTurn {
38    /// The heartbeat interval elapsed.
39    Heartbeat,
40    /// An armed registration saw an admitted edge (`registration::republish_due`).
41    Early,
42}
43
44impl Processor {
45    /// Publish one registration of `task`, the registration task numbered `index`. Until the
46    /// task is ready (`registration::RegistrationReadiness`, #866), its appends ask their owners
47    /// for store reports, and a publish that began with an admitted edge (`edges_at_start`)
48    /// awaits them as a node task, which makes the task ready once all report it stored.
49    async fn run_registration_once(
50        &self,
51        task: &dyn RegistrationTask,
52        index: usize,
53        stop: StopToken,
54        edges_at_start: usize,
55    ) -> Result<()> {
56        let context = RegistrationContext::new_with_stop(self, stop);
57        let context = match self.registration_readiness.is_ready(index) {
58            true => context,
59            false => context.reporting(),
60        };
61        let published = task.register_once(&context).await;
62        if let (Ok(()), Some(receipts)) = (&published, context.into_receipts()) {
63            if edges_at_start > 0 {
64                let wait = self.registration_readiness.wait(index, receipts);
65                if self.tasks.spawn(wait).is_err() {
66                    tracing::debug!("no runtime to await the store reports of a registration");
67                }
68            }
69        }
70        published
71    }
72
73    /// Immediately publish one heartbeat of every configured registration task with the active
74    /// session key, so peers and registries observe a renewed `delegatee_public_key` without
75    /// waiting for the next periodic tick (#1153).
76    pub async fn republish_registrations(&self) {
77        let stop = self.tasks.stop_token();
78        for (index, task) in self.registration_tasks.iter().enumerate() {
79            if stop.should_stop() {
80                return;
81            }
82            let edges_at_start = self.swarm.admitted_edges();
83            let published = self
84                .run_registration_once(task.as_ref(), index, stop.clone(), edges_at_start)
85                .await;
86            #[cfg(all(test, feature = "node"))]
87            crate::tests::activity::record_activity();
88            if let Err(error) = published {
89                if matches!(error, Error::RegistrationStopped) {
90                    return;
91                }
92                tracing::warn!(
93                    "Failed to republish {} registration after delegation renewal: {error:?}",
94                    task.name()
95                );
96            }
97        }
98    }
99
100    pub(super) async fn registration_task_daemon_with(
101        &self,
102        task: &dyn RegistrationTask,
103        index: usize,
104        stop: StopToken,
105        sibling_stop: StopToken,
106    ) {
107        let mut turn = RegistrationTurn::Heartbeat;
108        loop {
109            if stop.should_stop() || sibling_stop.should_stop() {
110                return;
111            }
112            let edges_at_start = self.swarm.admitted_edges();
113            let armed = early_publish_armed(turn == RegistrationTurn::Heartbeat, edges_at_start);
114            let published = self
115                .run_registration_once(task, index, stop.clone(), edges_at_start)
116                .await;
117            // A publish is a state change tests probe for.
118            #[cfg(all(test, feature = "node"))]
119            crate::tests::activity::record_activity();
120            if let Err(error) = published {
121                if matches!(error, Error::RegistrationStopped) {
122                    tracing::debug!(
123                        "Stopping {} registration task after cooperative stop",
124                        task.name()
125                    );
126                    return;
127                }
128                tracing::warn!("Failed to run {} registration task: {error:?}", task.name());
129            }
130            if stop.should_stop() || sibling_stop.should_stop() {
131                return;
132            }
133            match self
134                .next_registration_turn(task.interval(), armed, &stop, &sibling_stop)
135                .await
136            {
137                Ok(Some(next)) => turn = next,
138                Ok(None) => return,
139                Err(error) => {
140                    tracing::warn!(
141                        "Stopping {} registration task after timer error: {error:?}",
142                        task.name()
143                    );
144                    return;
145                }
146            }
147        }
148    }
149
150    /// The next turn of a registration daemon: its heartbeat after `interval`, or earlier, at
151    /// the first admitted edge of an `armed` registration (`registration::republish_due`, #855);
152    /// `None` once a stop is requested. Woken by the timer, an edge change or the stop, never by
153    /// polling.
154    async fn next_registration_turn(
155        &self,
156        interval: Duration,
157        armed: bool,
158        stop: &StopToken,
159        sibling_stop: &StopToken,
160    ) -> Result<Option<RegistrationTurn>> {
161        let heartbeat = sleep_unless_stopped(interval, stop, sibling_stop);
162        let first_edge = self.first_admitted_edge(armed);
163        futures::pin_mut!(heartbeat, first_edge);
164        match futures::future::select(heartbeat, first_edge).await {
165            futures::future::Either::Left((slept, _)) => {
166                Ok(slept?.then_some(RegistrationTurn::Heartbeat))
167            }
168            futures::future::Either::Right(((), _)) => Ok(Some(RegistrationTurn::Early)),
169        }
170    }
171
172    /// Resolves once an early publish is due for an `armed` registration, woken by the swarm's
173    /// edge changes (its edge-watch law); never for one not armed.
174    async fn first_admitted_edge(&self, armed: bool) {
175        if !armed {
176            return std::future::pending().await;
177        }
178        loop {
179            let changed = self.swarm.edges_changed();
180            if republish_due(armed, self.swarm.admitted_edges()) {
181                return;
182            }
183            changed.await;
184        }
185    }
186
187    pub(super) async fn registration_daemons_with(&self, stop: StopToken, sibling_stop: StopToken) {
188        join_all(
189            self.registration_tasks
190                .iter()
191                .enumerate()
192                .map(|(index, task)| {
193                    self.registration_task_daemon_with(
194                        task.as_ref(),
195                        index,
196                        stop.clone(),
197                        sibling_stop.clone(),
198                    )
199                }),
200        )
201        .await;
202    }
203
204    /// Resolves once every registration of this node is stored at its owners, as they
205    /// reported it (#866): for each registration task, a publish that began with an admitted
206    /// edge was reported stored by the owner of every remote placement
207    /// (`registration::RegistrationReadiness`). It resolves at once for a node with no
208    /// registration, and needs a running listener otherwise. A registry read by another node
209    /// then reaches the registrations at their owners, unless an owner has lost its placement
210    /// since.
211    pub async fn registrations_published(&self) {
212        self.registration_readiness.all().await
213    }
214}