printobserver_server/reconcile.rs
1//! What a supervisor adopts when it starts.
2//!
3//! Restarting loses nothing, because the store and the session directory are
4//! the whole of the state. This is what makes that true rather than merely
5//! claimed: on start the server reads what the store holds and adopts it — a
6//! print left open is the print it goes on watching, a session left open is
7//! resumed rather than replaced, and an intervention already past its expiry is
8//! expired through the ordinary policy so the value it should restore is
9//! restored.
10//!
11//! # The printer is asked first
12//!
13//! A print left open is one nobody saw end, which is not the same as one still
14//! running: the job may have finished, or been cancelled at the machine, while
15//! no supervisor was there to read it. So before anything is adopted the
16//! printer's job is read once, and every open print that read shows is over is
17//! closed through the same close-out a supervision turn takes
18//! ([`Supervisor::settle_with_printer`]); only what is still open after it is
19//! adopted. A printer that cannot be read closes nothing, and every open print
20//! is adopted as it is. An intervention past its expiry on a print closed here
21//! was expired by that close-out, and is not expired a second time.
22//!
23//! # Then the prints nobody watched are accounted
24//!
25//! With the open prints settled, the printer's own per-file print tallies are
26//! read and every print they counted that this system never saw is charged to
27//! the spools loaded ([`Supervisor::account_unobserved_prints`]), which writes
28//! its own record of what it found. A printer that cannot be read skips this
29//! rather than refusing the start, and [`Reconciliation::unobserved`]
30//! says why; the next start that reaches the printer accounts what this one
31//! could not, because the tallies only grow.
32//!
33//! Each of the three is **recorded** as having happened at startup, under the
34//! [`StartupReconciliationPayload`] kind this module declares and alone writes,
35//! because a print that carried on across a restart and one that was started
36//! again are otherwise indistinguishable in the history.
37//!
38//! # The due interventions are read before the supervisor exists
39//!
40//! Building a supervisor starts its expiry driver, which polls for what is due.
41//! So the interventions this reconciliation is about are read from the store
42//! first, and then expired through
43//! [`Supervisor::expire_intervention`](printobserver_core::Supervisor::expire_intervention),
44//! which settles once: if the driver reached one first, this answers the
45//! outcome that won rather than restoring it a second time.
46
47use std::sync::Arc;
48
49use printobserver_core::store::{ActionStore, EventDraft, EventStore, PrintStore, SessionStore};
50use printobserver_core::{CoreError, Supervisor, system_source};
51use printobserver_core::{Intervention, InterventionId, InterventionOutcome};
52use printobserver_printer_api::Adjustable;
53use printobserver_types::contract::Sample;
54use printobserver_types::schemars::JsonSchema;
55use printobserver_types::serde::{Deserialize, Serialize};
56use printobserver_types::{EventBody, EventId, EventPayload, PrintId, Timestamp};
57
58/// What one restart put back the way it found it.
59///
60/// A supervisor that has been restarted adopts whatever the store holds rather
61/// than starting empty, and each of these is one of those adoptions. They are
62/// recorded rather than merely done, because a print that carried on across a
63/// restart and one that was started again look identical afterwards unless the
64/// history says which happened.
65#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
66#[serde(
67 crate = "printobserver_types::serde",
68 rename_all = "snake_case",
69 deny_unknown_fields
70)]
71#[schemars(crate = "printobserver_types::schemars")]
72pub enum StartupOutcome {
73 /// A print left open was adopted as the print this supervisor is watching.
74 PrintAdopted,
75 /// A session left open was resumed rather than replaced.
76 SessionResumed {
77 /// The session's own name in the harness.
78 session_name: String,
79 },
80 /// An intervention already past its expiry was expired on start.
81 InterventionExpired {
82 /// The intervention that had outlived its bound.
83 intervention_id: InterventionId,
84 /// What it had changed.
85 adjustable: Adjustable,
86 /// What became of putting the prior value back.
87 outcome: InterventionOutcome,
88 },
89}
90
91impl Sample for StartupOutcome {
92 fn sample_full() -> Self {
93 Self::InterventionExpired {
94 intervention_id: InterventionId::sample_full(),
95 adjustable: Adjustable::Fan,
96 outcome: InterventionOutcome::Restored,
97 }
98 }
99
100 fn sample_alternates() -> Vec<Self> {
101 vec![
102 Self::PrintAdopted,
103 Self::SessionResumed {
104 session_name: "watch-4211".to_owned(),
105 },
106 ]
107 }
108}
109
110/// A supervisor reconciled one thing the store held when it started.
111#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
112#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
113#[schemars(crate = "printobserver_types::schemars")]
114pub struct StartupReconciliationPayload {
115 /// The print it is about.
116 pub print_id: PrintId,
117 /// What was reconciled.
118 pub outcome: StartupOutcome,
119}
120
121impl EventPayload for StartupReconciliationPayload {
122 const KIND: &'static str = "startup_reconciliation";
123}
124
125impl Sample for StartupReconciliationPayload {
126 fn sample_full() -> Self {
127 Self {
128 print_id: PrintId::sample_full(),
129 outcome: StartupOutcome::sample_full(),
130 }
131 }
132}
133
134/// What one start adopted.
135#[derive(Debug, Clone, Default, PartialEq, Eq)]
136pub struct Reconciliation {
137 /// Every print left open that the printer's job showed was over, and
138 /// which was closed rather than adopted.
139 pub closed: Vec<PrintId>,
140 /// Every print left open, which this supervisor goes on watching.
141 pub adopted: Vec<PrintId>,
142 /// Every print whose session was resumed rather than replaced.
143 pub resumed: Vec<PrintId>,
144 /// Every intervention that had outlived its bound and was expired.
145 pub expired: Vec<InterventionId>,
146 /// What accounting the prints the printer counted and nobody saw came to.
147 pub unobserved: UnobservedAccounting,
148}
149
150/// What one start's accounting of the prints nobody watched came to: done,
151/// writing these events, or skipped, for this reason — and never both.
152#[derive(Debug, Clone, PartialEq, Eq)]
153pub enum UnobservedAccounting {
154 /// It was made, writing these events in this order; none when it found
155 /// nothing new.
156 Accounted(Vec<EventId>),
157 /// It was skipped, because the printer could not be read, so its tallies
158 /// could not be.
159 Skipped(String),
160}
161
162impl Default for UnobservedAccounting {
163 fn default() -> Self {
164 Self::Accounted(Vec::new())
165 }
166}
167
168impl UnobservedAccounting {
169 /// The events it wrote; none when it found nothing new or was skipped.
170 #[must_use]
171 pub fn accounted(&self) -> &[EventId] {
172 match self {
173 Self::Accounted(written) => written,
174 Self::Skipped(_) => &[],
175 }
176 }
177
178 /// Why it was skipped, when it was.
179 #[must_use]
180 pub fn skipped(&self) -> Option<&str> {
181 match self {
182 Self::Accounted(_) => None,
183 Self::Skipped(why) => Some(why),
184 }
185 }
186}
187
188/// The interventions already past their expiry, read before the supervisor
189/// exists to start expiring them.
190///
191/// # Errors
192///
193/// Returns the store's own error when they could not be read.
194pub async fn overdue(
195 actions: &Arc<dyn ActionStore>,
196 at: Timestamp,
197) -> Result<Vec<Intervention>, CoreError> {
198 Ok(actions.due_interventions(at).await?)
199}
200
201/// The three stores a reconciliation reads and writes: the prints it adopts,
202/// the sessions it resumes, and the log it records each adoption in.
203#[derive(Clone)]
204pub struct ReconcileStores {
205 /// The print records.
206 pub prints: Arc<dyn PrintStore>,
207 /// The supervision sessions.
208 pub sessions: Arc<dyn SessionStore>,
209 /// The event log.
210 pub events: Arc<dyn EventStore>,
211}
212
213/// Close what the printer shows is over, adopt what the store holds, and
214/// record each adoption.
215///
216/// # Errors
217///
218/// Returns the store's own error when the open prints could not be read, a
219/// print the printer shows is over could not be closed, or an adoption could
220/// not be recorded. An intervention that could not be expired is
221/// recorded rather than answered here: one that fails does not cost the rest,
222/// which is the same rule the ordinary expiry sweep takes.
223pub async fn reconcile(
224 supervisor: &Arc<Supervisor>,
225 stores: &ReconcileStores,
226 overdue: Vec<Intervention>,
227) -> Result<Reconciliation, CoreError> {
228 let mut found = Reconciliation {
229 closed: supervisor.settle_with_printer().await?.closed,
230 ..Reconciliation::default()
231 };
232
233 // After the close-out, so a print the printer shows ended is settled by it
234 // before its tally is read and is not counted as one nobody saw.
235 match supervisor.account_unobserved_prints().await {
236 Ok(written) => {
237 found.unobserved =
238 UnobservedAccounting::Accounted(written.iter().map(|event| event.id).collect());
239 }
240 Err(CoreError::Printer(error)) => {
241 found.unobserved = UnobservedAccounting::Skipped(format!(
242 "the printer could not be read ({error}), so the prints it counted while \
243 nothing was watching were not accounted on this start; the next start that \
244 reaches it accounts them"
245 ));
246 }
247 Err(error) => return Err(error),
248 }
249
250 for print in stores.prints.open_prints().await? {
251 record(&stores.events, print.id, StartupOutcome::PrintAdopted).await?;
252 found.adopted.push(print.id);
253 let Some(session) = stores.sessions.session(print.id).await? else {
254 continue;
255 };
256 if session.closed_at.is_some() {
257 continue;
258 }
259 record(
260 &stores.events,
261 print.id,
262 StartupOutcome::SessionResumed {
263 session_name: session.session_name,
264 },
265 )
266 .await?;
267 found.resumed.push(print.id);
268 }
269
270 // A print the printer showed was over was closed through the close-out,
271 // which expired every intervention on it already.
272 for intervention in overdue
273 .into_iter()
274 .filter(|overdue| !found.closed.contains(&overdue.print_id))
275 {
276 let outcome = supervisor.expire_intervention(&intervention).await?;
277 record(
278 &stores.events,
279 intervention.print_id,
280 StartupOutcome::InterventionExpired {
281 intervention_id: intervention.id,
282 adjustable: intervention.adjustable,
283 outcome,
284 },
285 )
286 .await?;
287 found.expired.push(intervention.id);
288 }
289
290 Ok(found)
291}
292
293/// Write one adoption down.
294async fn record(
295 events: &Arc<dyn EventStore>,
296 print_id: PrintId,
297 outcome: StartupOutcome,
298) -> Result<(), CoreError> {
299 events
300 .append_event(EventDraft {
301 print_id: Some(print_id),
302 source: system_source(),
303 received_at: Timestamp::now(),
304 body: EventBody::of(&StartupReconciliationPayload { print_id, outcome })?,
305 raw: None,
306 })
307 .await?;
308 Ok(())
309}