printobserver_core/records/policy.rs
1//! What an actor is allowed to ask for, and the decision taken on one request.
2
3use std::collections::BTreeMap;
4
5use printobserver_printer_api::{Adjustable, PrinterState};
6use printobserver_types::schemars::JsonSchema;
7use printobserver_types::serde::{Deserialize, Serialize};
8use printobserver_types::{EventId, Range};
9
10use super::action::{ActionKind, ActorClass};
11use super::ids::{InterventionId, SpoolId};
12use super::preflight::{MaterialObjection, SheetObjection};
13use super::spool::UnverifiedReason;
14
15/// Server configuration: what any actor may ask for at all.
16///
17/// This is the operator's safety envelope. It is a different contract from the
18/// plausibility ranges [`Reported`](printobserver_types::Reported) fields carry, is narrower
19/// by orders of magnitude, and the two are never intersected, compared or
20/// substituted for one another.
21#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
22#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
23#[schemars(crate = "printobserver_types::schemars")]
24pub struct SafetyEnvelope {
25 /// The range each adjustable may be set to, inclusive.
26 pub allowed: BTreeMap<Adjustable, Range>,
27 /// The actions each actor class may request at all.
28 pub actions: BTreeMap<ActorClass, Vec<ActionKind>>,
29 /// The minimum interval between two agent actions that change the machine,
30 /// in whole seconds. An acknowledgement neither waits on it nor restarts it.
31 pub agent_min_interval_s: i64,
32}
33
34/// The envelope intersected with the print's manifest.
35///
36/// This is what context reports, so that the agent can see its own limits
37/// before it asks. Computing one is the supervision core's; this crate declares
38/// the shape and nothing that produces it.
39#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
40#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
41#[schemars(crate = "printobserver_types::schemars")]
42pub struct EffectiveBounds {
43 /// The range each adjustable may be set to, inclusive.
44 pub allowed: BTreeMap<Adjustable, Range>,
45}
46
47/// Why a request was refused.
48///
49/// Each rejection is a distinct variant, so a consumer distinguishes them by
50/// matching rather than by reading a message.
51#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
52#[serde(
53 crate = "printobserver_types::serde",
54 rename_all = "snake_case",
55 deny_unknown_fields
56)]
57#[schemars(crate = "printobserver_types::schemars")]
58pub enum RejectionReason {
59 /// The value asked for is outside the range allowed for that adjustable.
60 OutOfBounds {
61 /// The adjustable that was asked for.
62 adjustable: Adjustable,
63 /// The value that was asked for.
64 requested: f64,
65 /// The range that was allowed.
66 allowed: Range,
67 },
68 /// This actor class may not request this action at all.
69 ActorMayNotRequest {
70 /// The class of the actor that asked.
71 actor_class: ActorClass,
72 /// The action they asked for.
73 action: ActionKind,
74 },
75 /// There is no active print to act on.
76 NoActivePrint,
77 /// The printer is not in a state this action is valid from.
78 InvalidFromState {
79 /// The state the printer is in.
80 state: PrinterState,
81 },
82 /// The agent's minimum interval has not elapsed.
83 MinIntervalNotElapsed {
84 /// The minimum interval, in whole seconds.
85 interval_s: i64,
86 /// How long it has been since the last agent action, in whole seconds.
87 since_last_s: i64,
88 },
89 /// The adjustable is not one this printer has.
90 UnsupportedAdjustable {
91 /// The adjustable this printer cannot express.
92 adjustable: Adjustable,
93 },
94 /// A start was refused because the spool on one tool holds less than the
95 /// print needs and its buffer.
96 InsufficientFilament {
97 /// The tool whose spool is short.
98 tool: i64,
99 /// The spool loaded on it.
100 spool_id: SpoolId,
101 /// That spool's name.
102 spool_name: String,
103 /// What the print needs from it, in grams.
104 required_g: f64,
105 /// The margin asked for beyond that, in grams.
106 buffer_g: f64,
107 /// What the spool holds, in grams.
108 remaining_g: f64,
109 /// The spool's oldest mark, when the short spool is also unverified.
110 #[serde(default, skip_serializing_if = "Option::is_none")]
111 unverified: Option<UnverifiedReason>,
112 /// The stretch of a file with planned changes the spool is short for;
113 /// absent for a file that plans none.
114 #[serde(default, skip_serializing_if = "Option::is_none")]
115 segment: Option<u32>,
116 },
117 /// A start was refused because the spool on one tool is unverified.
118 UnverifiedSpool {
119 /// The tool whose spool is unverified.
120 tool: i64,
121 /// The spool loaded on it.
122 spool_id: SpoolId,
123 /// That spool's name.
124 spool_name: String,
125 /// The spool's oldest mark.
126 reason: UnverifiedReason,
127 /// The stretch of a file with planned changes the spool is named for;
128 /// absent for a file that plans none.
129 #[serde(default, skip_serializing_if = "Option::is_none")]
130 segment: Option<u32>,
131 },
132 /// A start was refused because `OctoPrint`'s analysis of the file had not
133 /// appeared when the start's wait for it elapsed.
134 AnalysisUnavailable {
135 /// The file that has no analysis.
136 file_name: String,
137 /// How long the start waited for one, in whole seconds.
138 waited_s: u64,
139 },
140 /// A start was refused because its file was sliced for another material
141 /// than the spool loaded on tool 0, names none, or could not be read.
142 MaterialRefused {
143 /// What the material check objected to, with what it compared.
144 objection: MaterialObjection,
145 },
146 /// A start was refused because its declared build sheet does not suit the
147 /// loaded spool's material by the sheet table.
148 SheetRefused {
149 /// What the sheet check objected to, with what it compared.
150 objection: SheetObjection,
151 },
152 /// A start was refused because its manifest declares no `sheet`. No
153 /// override lets this through.
154 SheetNotDeclared,
155 /// A close was refused because the print record has already ended.
156 PrintAlreadyEnded,
157 /// A close was refused because the printer shows a job of the record's
158 /// file printing, paused or cancelling.
159 PrintStillActive {
160 /// The state the printer reported that job in.
161 state: PrinterState,
162 },
163 /// A close was refused because an intervention for the print has neither
164 /// expired nor been restored.
165 InterventionStillActive {
166 /// The intervention still standing.
167 intervention_id: InterventionId,
168 },
169 /// A resume was refused because a recovery action was executed while the
170 /// print was paused: the head moved, and `OctoPrint` restores no position
171 /// on resume, so the rest of the layer would print at the wrong height.
172 PrintNotResumable {
173 /// The `recovery_executed` event that made it so.
174 recovery_event_id: EventId,
175 },
176 /// A pause, a resume or an adjustment was refused because the printer is
177 /// waiting at a change the print's G-code plans, for a person to finish it
178 /// on the printer.
179 #[schemars(transform = crate::gcode_index::null_is_sent)]
180 PlannedChangeWaiting {
181 /// The index of the change it is waiting at.
182 change_index: u32,
183 /// The first layer printed after it.
184 layer: u32,
185 /// That layer's height, in millimetres.
186 z_mm: f64,
187 /// The colour to load, as `#RRGGBB`; null when the file names none.
188 color: Option<String>,
189 },
190 /// A spool command could not be carried out.
191 SpoolRefused {
192 /// Why, in a form a client acts on without reading `message`.
193 cause: SpoolRefusalCause,
194 /// Why, in a sentence naming what to do instead, for a person.
195 message: String,
196 },
197}
198
199/// One field of a spool command, as the command names it.
200#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
201#[serde(crate = "printobserver_types::serde", rename_all = "snake_case")]
202#[schemars(crate = "printobserver_types::schemars")]
203pub enum SpoolField {
204 /// The operator's own label for the spool.
205 Name,
206 /// The material, such as `PLA`.
207 Material,
208 /// The filament's diameter, in millimetres.
209 DiameterMm,
210 /// The material's density, in grams per cubic centimetre.
211 DensityGCm3,
212 /// The net filament on the spool when full, in grams.
213 InitialG,
214 /// The filament on the spool now, in grams.
215 RemainingG,
216 /// The empty spool's own weight, in grams.
217 TareG,
218 /// A scale reading of the spool, in grams.
219 GrossG,
220}
221
222/// Why the spool ledger refused a command, each cause carrying what a client
223/// needs to choose the next valid request.
224#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
225#[serde(
226 crate = "printobserver_types::serde",
227 tag = "cause",
228 rename_all = "snake_case",
229 deny_unknown_fields
230)]
231#[schemars(crate = "printobserver_types::schemars")]
232pub enum SpoolRefusalCause {
233 /// No spool was ever registered under this identifier.
234 UnknownSpool {
235 /// The identifier the command named.
236 spool_id: SpoolId,
237 },
238 /// The spool is retired, and takes no further command.
239 RetiredSpool {
240 /// The retired spool.
241 spool_id: SpoolId,
242 },
243 /// The spool named is already on the tool, and nothing is pending there or
244 /// marked on it for a load to confirm.
245 NothingToConfirm {
246 /// The tool the spool is already on.
247 tool: i64,
248 },
249 /// A figure the command gave is not one the field can hold: not a number,
250 /// or out of the field's range.
251 InvalidAdjustmentFigure {
252 /// The field the figure was given for.
253 field: SpoolField,
254 /// The figure given; always a number, because a figure JSON cannot
255 /// carry is refused as it would be written rather than written as
256 /// `null`.
257 #[serde(serialize_with = "a_number")]
258 value: f64,
259 },
260 /// A scale reading was given for a spool with no tare, so it cannot be
261 /// turned into a figure.
262 TareRequired {
263 /// The spool with no tare.
264 spool_id: SpoolId,
265 },
266 /// The material has no known density, so the command needs one.
267 DensityRequired {
268 /// The spool, when the command was about one that exists; absent for
269 /// a registration.
270 #[serde(default, skip_serializing_if = "Option::is_none")]
271 spool_id: Option<SpoolId>,
272 /// The material, as given and trimmed.
273 material: String,
274 },
275 /// A field the command needs was empty or absent.
276 MissingField {
277 /// The field; for a correction naming neither figure, `remaining_g`,
278 /// which `gross_g` may stand in for.
279 field: SpoolField,
280 },
281 /// The command gave fields only one of which it may carry.
282 ConflictingFields {
283 /// Every field given that conflicts, in the command's own order.
284 fields: Vec<SpoolField>,
285 },
286 /// The command named a tool the printer cannot have.
287 UnknownTool {
288 /// The tool named.
289 tool: i64,
290 },
291 /// The spool is loaded on no tool, so there is nothing to unload.
292 NotLoaded {
293 /// The spool.
294 spool_id: SpoolId,
295 },
296 /// The ledger refused the write the command made, because the spools
297 /// changed under it; reading them again shows how.
298 LedgerRefused,
299}
300
301/// Write a figure as the number it is, refusing one JSON has no number for:
302/// written as `null`, it would be a refusal no reader could read back.
303// serde hands a `serialize_with` a reference to the field; suppressions.toml has the reason.
304#[expect(clippy::trivially_copy_pass_by_ref)]
305fn a_number<S: printobserver_types::serde::Serializer>(
306 value: &f64,
307 serializer: S,
308) -> Result<S::Ok, S::Error> {
309 use printobserver_types::serde::ser::Error as _;
310 if value.is_finite() {
311 serializer.serialize_f64(*value)
312 } else {
313 Err(S::Error::custom(format!(
314 "the figure {value} has no number JSON can carry"
315 )))
316 }
317}
318
319/// The decision policy took on one request.
320#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
321#[serde(
322 crate = "printobserver_types::serde",
323 rename_all = "snake_case",
324 deny_unknown_fields
325)]
326#[schemars(crate = "printobserver_types::schemars")]
327pub enum PolicyDecision {
328 /// The request may proceed.
329 Accepted,
330 /// The request may not, for this reason.
331 Rejected(RejectionReason),
332}