Skip to main content

printobserver_core/records/
spool.rs

1//! A registered spool, and how far its remaining figure can be trusted.
2//!
3//! A spool's remaining figure is only worth having when it can be explained, so
4//! a spool carries every reason its figure is in doubt rather than one flag: a
5//! mark is added when something happened that could not be charged exactly,
6//! and is cleared only by the command that settles that doubt. The rule for
7//! which command clears which mark is implemented once, by
8//! [`marks_cleared_by`](crate::filament::marks_cleared_by).
9
10use printobserver_types::schemars::JsonSchema;
11use printobserver_types::serde::de::Error as _;
12use printobserver_types::serde::{Deserialize, Deserializer, Serialize};
13use printobserver_types::{PrintId, Timestamp};
14
15use super::ids::SpoolId;
16
17/// One spool the operator registered, and what is known of it now.
18#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
19#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
20#[schemars(crate = "printobserver_types::schemars")]
21pub struct SpoolRecord {
22    /// This spool's identifier, minted when it was registered.
23    pub id: SpoolId,
24    /// The operator's own label for the spool; never empty.
25    pub name: String,
26    /// The material, as given and trimmed, such as `PLA`; never empty.
27    pub material: String,
28    /// The filament's colour, when the operator gave one.
29    #[serde(default, skip_serializing_if = "Option::is_none")]
30    pub color: Option<String>,
31    /// The filament's diameter, in millimetres; above zero.
32    pub diameter_mm: f64,
33    /// The material's density, in grams per cubic centimetre; above zero.
34    pub density_g_cm3: f64,
35    /// The net filament on the spool when it was full, in grams; above zero.
36    pub initial_g: f64,
37    /// The filament left, in grams.
38    ///
39    /// Always the initial figure less every charge plus every correction. A
40    /// charge is never refused or clamped, so this may go below zero.
41    pub remaining_g: f64,
42    /// The empty spool's own weight, in grams, when the operator gave it.
43    #[serde(default, skip_serializing_if = "Option::is_none")]
44    pub tare_g: Option<f64>,
45    /// Where the spool is in its life: on the shelf, loaded on a tool, or
46    /// retired — and never both of the last two.
47    pub lifecycle: SpoolLifecycle,
48    /// How far the remaining figure can be trusted.
49    pub trust: SpoolTrust,
50    /// When the spool was registered.
51    pub registered_at: Timestamp,
52    /// When anything about the spool last changed.
53    pub updated_at: Timestamp,
54}
55
56impl SpoolRecord {
57    /// The tool the spool is loaded on, when it is loaded.
58    #[must_use]
59    pub const fn loaded_tool(&self) -> Option<i64> {
60        match self.lifecycle {
61            SpoolLifecycle::Loaded { tool } => Some(tool),
62            SpoolLifecycle::Shelved | SpoolLifecycle::Retired { .. } => None,
63        }
64    }
65
66    /// Whether the spool has been retired.
67    #[must_use]
68    pub const fn is_retired(&self) -> bool {
69        matches!(self.lifecycle, SpoolLifecycle::Retired { .. })
70    }
71}
72
73/// Where a spool is in its life.
74///
75/// One state rather than a loaded tool beside a retirement instant, because a
76/// retired spool is on no tool: retiring a loaded spool takes it off.
77#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
78#[serde(
79    crate = "printobserver_types::serde",
80    tag = "state",
81    rename_all = "snake_case",
82    deny_unknown_fields
83)]
84#[schemars(crate = "printobserver_types::schemars")]
85pub enum SpoolLifecycle {
86    /// Registered, and loaded on no tool.
87    Shelved,
88    /// Loaded on one tool.
89    Loaded {
90        /// The tool, in the printer's own numbering.
91        tool: i64,
92    },
93    /// Retired: it takes no further command, and is on no tool.
94    Retired {
95        /// When it was retired.
96        at: Timestamp,
97    },
98}
99
100/// How far a spool's remaining figure can be trusted.
101#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
102#[serde(
103    crate = "printobserver_types::serde",
104    tag = "state",
105    rename_all = "snake_case",
106    deny_unknown_fields
107)]
108#[schemars(crate = "printobserver_types::schemars")]
109pub enum SpoolTrust {
110    /// Every charge against the spool was taken exactly.
111    Verified,
112    /// At least one thing happened that could not be charged exactly.
113    Unverified {
114        /// Every reason the figure is in doubt, oldest first, at most one per
115        /// distinct reason; never empty.
116        marks: UnverifiedMarks,
117    },
118}
119
120/// Every reason a spool's figure is in doubt, oldest first: never empty.
121///
122/// A spool holding no mark is verified, and one called unverified with nothing
123/// to say why is not a state this ledger has, so this list cannot be built
124/// empty and an empty one is refused on read. On the wire it is an array the
125/// schema bounds with `minItems: 1`.
126#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
127#[serde(crate = "printobserver_types::serde", transparent)]
128pub struct UnverifiedMarks(Vec<UnverifiedMark>);
129
130impl UnverifiedMarks {
131    /// These marks, when there is at least one.
132    #[must_use]
133    pub fn new(marks: Vec<UnverifiedMark>) -> Option<Self> {
134        (!marks.is_empty()).then_some(Self(marks))
135    }
136
137    /// The mark held longest.
138    #[must_use]
139    pub fn oldest(&self) -> &UnverifiedMark {
140        &self.0[0]
141    }
142
143    /// Every mark, oldest first, as a list of its own.
144    #[must_use]
145    pub fn into_vec(self) -> Vec<UnverifiedMark> {
146        self.0
147    }
148}
149
150impl core::ops::Deref for UnverifiedMarks {
151    type Target = [UnverifiedMark];
152
153    fn deref(&self) -> &[UnverifiedMark] {
154        &self.0
155    }
156}
157
158impl<'de> Deserialize<'de> for UnverifiedMarks {
159    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
160        Self::new(Vec::<UnverifiedMark>::deserialize(deserializer)?).ok_or_else(|| {
161            D::Error::custom(
162                "an unverified spool carries at least one mark; one with none is verified",
163            )
164        })
165    }
166}
167
168impl JsonSchema for UnverifiedMarks {
169    fn inline_schema() -> bool {
170        true
171    }
172
173    fn schema_name() -> std::borrow::Cow<'static, str> {
174        "UnverifiedMarks".into()
175    }
176
177    fn json_schema(
178        generator: &mut printobserver_types::schemars::SchemaGenerator,
179    ) -> printobserver_types::schemars::Schema {
180        let mut schema = Vec::<UnverifiedMark>::json_schema(generator);
181        schema.insert("minItems".to_owned(), 1.into());
182        schema
183    }
184}
185
186/// One reason a spool's figure is in doubt, and since when.
187#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
188#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
189#[schemars(crate = "printobserver_types::schemars")]
190pub struct UnverifiedMark {
191    /// Why the figure is in doubt.
192    pub reason: UnverifiedReason,
193    /// When the spool was marked for it.
194    pub since: Timestamp,
195}
196
197/// Why a spool's figure is in doubt.
198#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
199#[serde(
200    crate = "printobserver_types::serde",
201    tag = "reason",
202    rename_all = "snake_case",
203    deny_unknown_fields
204)]
205#[schemars(crate = "printobserver_types::schemars")]
206pub enum UnverifiedReason {
207    /// A print ran on the spool's tool and nothing could be charged, because
208    /// the file had no analysis — an SD-card file, for one.
209    UnchargedPrint {
210        /// The print nothing could be charged for.
211        print_id: PrintId,
212    },
213    /// A print this system never saw ran and did not complete.
214    UnaccountedPrint {
215        /// The file that was printed.
216        file_name: String,
217        /// When it was printed.
218        printed_at: Timestamp,
219    },
220    /// A filament change was signalled and nobody has said which spool is now
221    /// loaded. The spool was charged up to a position read when the signal was
222    /// handled.
223    FilamentChangeUnconfirmed {
224        /// The print the change was signalled during.
225        print_id: PrintId,
226    },
227    /// A filament change was signalled, nobody has said which spool is now
228    /// loaded, and no fresh position could be read at the signal: the spool was
229    /// charged only up to the last recorded position, so its figure may be
230    /// overstated.
231    FilamentChangeUnconfirmedPosition {
232        /// The print the change was signalled during.
233        print_id: PrintId,
234    },
235    /// A file's print tally was reset, and it cannot be told which of the
236    /// prints since the re-upload were already settled.
237    TallyReset {
238        /// The file whose tally was reset.
239        file_name: String,
240        /// Where the file lives, in the printer's own vocabulary.
241        origin: String,
242    },
243}
244
245/// The five reasons a spool may be marked for, without their payloads.
246#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
247#[serde(crate = "printobserver_types::serde", rename_all = "snake_case")]
248pub enum UnverifiedReasonKind {
249    /// [`UnverifiedReason::UnchargedPrint`].
250    UnchargedPrint,
251    /// [`UnverifiedReason::UnaccountedPrint`].
252    UnaccountedPrint,
253    /// [`UnverifiedReason::FilamentChangeUnconfirmed`].
254    FilamentChangeUnconfirmed,
255    /// [`UnverifiedReason::FilamentChangeUnconfirmedPosition`].
256    FilamentChangeUnconfirmedPosition,
257    /// [`UnverifiedReason::TallyReset`].
258    TallyReset,
259}
260
261impl UnverifiedReason {
262    /// Which reason this is, without its payload.
263    #[must_use]
264    pub const fn kind(&self) -> UnverifiedReasonKind {
265        match self {
266            Self::UnchargedPrint { .. } => UnverifiedReasonKind::UnchargedPrint,
267            Self::UnaccountedPrint { .. } => UnverifiedReasonKind::UnaccountedPrint,
268            Self::FilamentChangeUnconfirmed { .. } => {
269                UnverifiedReasonKind::FilamentChangeUnconfirmed
270            }
271            Self::FilamentChangeUnconfirmedPosition { .. } => {
272                UnverifiedReasonKind::FilamentChangeUnconfirmedPosition
273            }
274            Self::TallyReset { .. } => UnverifiedReasonKind::TallyReset,
275        }
276    }
277}
278
279/// One mark a spool command cleared, and the spool it was cleared from.
280#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
281#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
282#[schemars(crate = "printobserver_types::schemars")]
283pub struct ClearedMark {
284    /// The spool the mark was cleared from.
285    pub spool_id: SpoolId,
286    /// The reason that no longer stands.
287    pub reason: UnverifiedReason,
288}
289
290/// One spool loaded on one tool, as a print started.
291#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
292#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
293#[schemars(crate = "printobserver_types::schemars")]
294pub struct LoadedSpool {
295    /// The tool, in the printer's own numbering.
296    pub tool: i64,
297    /// The spool loaded on it.
298    pub spool_id: SpoolId,
299}