printobserver-core 0.16.3

Supervision logic for printobserver.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
//! One assembled supervisor and its four fakes, and the fixtures they drive.

use std::collections::BTreeMap;
use std::sync::Arc;
use std::time::Duration;

use printobserver_core::{
    ActionKind, Actor, ActorClass, JobManifest, PrintAction, PrintRecord, SafetyEnvelope,
};
use printobserver_core::{ActionOutcome, CoreConfig, CoreError, Supervisor, block_on};
use printobserver_printer_api::Adjustable;
use printobserver_types::schemars::JsonSchema;
use printobserver_types::serde::{Deserialize, Serialize};
use printobserver_types::{
    EventBody, EventKind, EventPayload, EventRecord, EventSource, PrintId, Range, RawBytes,
    Timestamp,
};
use printobserver_vision_api::{
    MalformedExternalEventPayload, NormalizedAlert, ProviderPrint, WebAddress,
};

use crate::fakes::{FakeClock, FakePrinter, FakeStore, FakeSupervisor, FakeVision};
use crate::journal::Journal;

/// Where the camera of [`World::with_camera`] answers.
pub const CAMERA_URL: &str = "http://camera.local/frame.jpeg";

/// The instant the fake clock starts at.
pub const EPOCH_SECONDS: i64 = 1_700_000_000;

/// Every action the vocabulary declares, as a kind.
///
/// The walk over the vocabulary asserts this is exactly what the contracts
/// declare, so a variant added there cannot go undriven here.
pub const ACTION_KINDS: [ActionKind; 11] = [
    ActionKind::Pause,
    ActionKind::Resume,
    ActionKind::Cancel,
    ActionKind::StartPrint,
    ActionKind::SetFeedrateFactor,
    ActionKind::SetFlowrateFactor,
    ActionKind::SetToolTargetC,
    ActionKind::SetBedTargetC,
    ActionKind::SetFanPercent,
    ActionKind::AcknowledgeFailure,
    ActionKind::ClosePrint,
];

/// The safety envelope every journey runs under unless it says otherwise.
///
/// It grants every actor class every action, so that a journey reaching a
/// rejection reaches the one it meant to rather than tripping over a grant it
/// did not think about.
#[must_use]
pub fn permissive_envelope() -> SafetyEnvelope {
    let mut allowed = BTreeMap::new();
    allowed.insert(Adjustable::Feedrate, Range::new(0.5, 2.0));
    allowed.insert(Adjustable::Flowrate, Range::new(0.8, 1.2));
    allowed.insert(Adjustable::ToolTarget { tool: 0 }, Range::new(180.0, 250.0));
    allowed.insert(Adjustable::BedTarget, Range::new(0.0, 80.0));
    allowed.insert(Adjustable::Fan, Range::new(0.0, 100.0));
    let mut actions = BTreeMap::new();
    for class in [ActorClass::Agent, ActorClass::Operator, ActorClass::System] {
        actions.insert(class, ACTION_KINDS.to_vec());
    }
    SafetyEnvelope {
        allowed,
        actions,
        agent_min_interval_s: 0,
    }
}

/// One assembled supervisor, its four fakes, its clock and its journal.
pub struct World {
    /// The supervisor under test.
    pub core: Arc<Supervisor>,
    /// The ordered record of every port call.
    pub journal: Arc<Journal>,
    /// The store.
    pub store: Arc<FakeStore>,
    /// The printer.
    pub printer: Arc<FakePrinter>,
    /// The vision port.
    pub vision: Arc<FakeVision>,
    /// The supervising agent's harness.
    pub agent: Arc<FakeSupervisor>,
    /// The one time source.
    pub clock: Arc<FakeClock>,
    /// Where each turn's runs take their credentials from.
    pub turns: Arc<crate::fakes::FakeTurnAuthority>,
    /// The configuration the supervisor was built with.
    pub config: CoreConfig,
}

impl World {
    /// A world under the permissive envelope.
    #[must_use]
    pub fn new() -> Self {
        Self::with_envelope(permissive_envelope())
    }

    /// A world under one envelope.
    #[must_use]
    pub fn with_envelope(envelope: SafetyEnvelope) -> Self {
        Self::built(envelope, true)
    }

    /// A world under the permissive envelope whose supervisor nothing
    /// installed a turn authority on.
    #[must_use]
    pub fn with_no_turn_authority() -> Self {
        Self::built(permissive_envelope(), false)
    }

    /// A world under the permissive envelope whose camera answers at a fixed
    /// address, served by the vision port.
    #[must_use]
    pub fn with_camera() -> Self {
        Self::configured(permissive_envelope(), true, |config| {
            config.camera_snapshot_url =
                Some(WebAddress::new(CAMERA_URL).expect("the camera's address is one"));
        })
    }

    /// A world whose camera answers at a fixed address, served by the vision
    /// port, and whose fetches of it are retried under `retry`.
    #[must_use]
    pub fn with_camera_retry(retry: printobserver_core::CameraRetry) -> Self {
        Self::configured(permissive_envelope(), true, |config| {
            config.camera_snapshot_url =
                Some(WebAddress::new(CAMERA_URL).expect("the camera's address is one"));
            config.camera_retry = retry;
        })
    }

    /// A world under one envelope and a configuration one journey edits, its
    /// turn authority installed.
    #[must_use]
    pub fn with_config(envelope: SafetyEnvelope, edit: impl FnOnce(&mut CoreConfig)) -> Self {
        Self::configured(envelope, true, edit)
    }

    /// A second supervisor over this world's same store, printer, ports and
    /// clock, built as a restart builds one: holding nothing in memory of what
    /// the first saw.
    #[must_use]
    pub fn restarted(&self) -> Arc<Supervisor> {
        self.restarted_on(Arc::clone(&self.clock) as Arc<dyn printobserver_core::Clock>)
    }

    /// A second supervisor over this world's same store, printer and ports,
    /// reading time from `clock`, built as a restart builds one.
    #[must_use]
    pub fn restarted_on(&self, clock: Arc<dyn printobserver_core::Clock>) -> Arc<Supervisor> {
        let core = Supervisor::new(
            self.config.clone(),
            Arc::clone(&self.printer) as Arc<dyn printobserver_printer_api::PrinterPort>,
            printobserver_core::store::Stores::of(Arc::clone(&self.store)),
            Arc::clone(&self.vision) as Arc<dyn printobserver_vision_api::VisionPort>,
            Arc::clone(&self.agent) as Arc<dyn printobserver_supervisor_api::SupervisorPort>,
            clock,
        );
        assert!(
            core.install_turn_authority(Arc::new(crate::fakes::OpensTurns(Arc::clone(
                &self.turns
            ))))
        );
        core
    }

    /// Stop this world's supervisor and go on with a restarted one over the
    /// same store, printer, ports and clock, as a restart of the service does.
    ///
    /// Answers once the first is gone, its expiry driver with it, so nothing
    /// the first was counting down can be expired by it afterwards.
    ///
    /// # Panics
    ///
    /// Panics when the first supervisor does not stop.
    pub fn restart(&mut self) {
        self.restart_on(Arc::clone(&self.clock) as Arc<dyn printobserver_core::Clock>);
    }

    /// Stop this world's supervisor and go on with a restarted one over the
    /// same store, printer and ports, reading time from `clock`.
    ///
    /// # Panics
    ///
    /// Panics when the first supervisor does not stop.
    pub fn restart_on(&mut self, clock: Arc<dyn printobserver_core::Clock>) {
        let stopped = Arc::downgrade(&self.core);
        self.core = self.restarted_on(clock);
        self.agent.attach(&self.core);
        wait_until("the first supervisor to stop", || {
            stopped.upgrade().is_none()
        });
    }

    /// A world under one envelope, its turn authority installed or not.
    fn built(envelope: SafetyEnvelope, authority: bool) -> Self {
        Self::configured(envelope, authority, |_| {})
    }

    /// A world under one envelope and a configuration one journey edits.
    fn configured(
        envelope: SafetyEnvelope,
        authority: bool,
        edit: impl FnOnce(&mut CoreConfig),
    ) -> Self {
        let journal = Arc::new(Journal::default());
        let clock = Arc::new(FakeClock::new(EPOCH_SECONDS));
        let store = Arc::new(FakeStore::new(Arc::clone(&journal), Arc::clone(&clock)));
        let printer = Arc::new(FakePrinter::new(Arc::clone(&journal)));
        let vision = Arc::new(FakeVision::new(Arc::clone(&journal)));
        let agent = Arc::new(FakeSupervisor::new(
            Arc::clone(&journal),
            Arc::clone(&clock),
        ));
        let mut config = CoreConfig::new(
            envelope,
            format!(
                "printobserver context {}",
                printobserver_core::PRINT_ID_PLACEHOLDER
            ),
        );
        config.expiry_poll = Duration::from_millis(5);
        edit(&mut config);
        let core = Supervisor::new(
            config.clone(),
            Arc::clone(&printer) as Arc<dyn printobserver_printer_api::PrinterPort>,
            printobserver_core::store::Stores::of(Arc::clone(&store)),
            Arc::clone(&vision) as Arc<dyn printobserver_vision_api::VisionPort>,
            Arc::clone(&agent) as Arc<dyn printobserver_supervisor_api::SupervisorPort>,
            Arc::clone(&clock) as Arc<dyn printobserver_core::Clock>,
        );
        agent.attach(&core);
        let turns = Arc::new(crate::fakes::FakeTurnAuthority::default());
        if authority {
            assert!(
                core.install_turn_authority(Arc::new(crate::fakes::OpensTurns(Arc::clone(&turns))))
            );
        }
        agent.reads_authority(&turns);
        Self {
            core,
            journal,
            store,
            printer,
            vision,
            agent,
            clock,
            turns,
            config,
        }
    }

    /// Open one print directly at the store, the way an earlier event would.
    ///
    /// # Panics
    ///
    /// Panics when the store refuses to open it.
    pub fn open_print(&self, provider_print_id: i64) -> PrintRecord {
        block_on(printobserver_core::store::PrintStore::open_print(
            self.store.as_ref(),
            Some(provider_print_id),
            Some("benchy.gcode".to_owned()),
        ))
        .expect("the store opens a print")
    }

    /// Drive one event through the real loop.
    pub fn handle(&self, alert: NormalizedAlert) -> Result<EventRecord, CoreError> {
        block_on(self.core.handle_event(alert))
    }

    /// Request one action through the real action path.
    pub fn request(
        &self,
        print_id: PrintId,
        action: PrintAction,
    ) -> Result<ActionOutcome, CoreError> {
        block_on(self.core.request_action(print_id, action))
    }

    /// Read one print's context back the way the context command does.
    pub fn context(
        &self,
        print_id: PrintId,
    ) -> Result<printobserver_core::PrintContext, CoreError> {
        block_on(self.core.context(print_id))
    }

    /// Read one print's context the way a supervision turn does, since an
    /// event or not.
    pub fn agent_context(
        &self,
        print_id: PrintId,
        since: Option<printobserver_types::EventId>,
    ) -> Result<printobserver_core::AgentContext, CoreError> {
        block_on(self.core.agent_context(print_id, since))
    }

    /// Wait until a condition the fakes can observe holds, or give up.
    ///
    /// # Panics
    ///
    /// Panics when the condition has not held within the deadline, which is a
    /// property the run never reached rather than a slow machine.
    pub fn wait_until(&self, what: &str, condition: impl FnMut() -> bool) {
        let _ = &self.core;
        wait_until(what, condition);
    }
}

/// Wait until a condition holds, or give up naming what never happened.
///
/// # Panics
///
/// Panics when the condition has not held within the deadline.
pub fn wait_until(what: &str, mut condition: impl FnMut() -> bool) {
    let deadline = std::time::Instant::now() + Duration::from_secs(10);
    while std::time::Instant::now() < deadline {
        if condition() {
            return;
        }
        std::thread::sleep(Duration::from_millis(2));
    }
    panic!("{what} did not happen within the deadline");
}

/// Assert two reported values are the **same** value, bit for bit.
///
/// A value this system carries from a printer snapshot into an intervention and
/// back out to the printer is never arithmetic on: it is the same number, and
/// an approximate comparison would hide exactly the drift that would matter.
#[track_caller]
pub fn assert_same(actual: f64, expected: f64) {
    assert!(
        actual.to_bits() == expected.to_bits(),
        "expected {expected}, found {actual}"
    );
}

impl Default for World {
    fn default() -> Self {
        Self::new()
    }
}

/// The instant `seconds` after the fake clock's own epoch.
///
/// # Panics
///
/// Panics when that instant is not representable, which it is by construction.
#[must_use]
pub fn at(seconds: i64) -> Timestamp {
    Timestamp::from_unix_seconds(EPOCH_SECONDS + seconds).expect("a representable instant")
}

/// The agent, as an actor naming its session.
#[must_use]
pub fn agent_actor(print_id: PrintId) -> Actor {
    Actor::Agent {
        session_name: format!("print-{print_id}"),
    }
}

/// The source name of the provider these journeys stand in for.
///
/// No crate of this workspace declares it: what the loop is proven against is
/// an adapter it has never heard of, which is what makes it provider-neutral.
pub const TEST_PROVIDER_SOURCE: &str = "test_provider";

/// A failure alert from the provider these journeys stand in for.
///
/// Declared here, under a kind no crate ships, because the supervision loop
/// reads nothing an adapter declares: it correlates on the
/// [`ProviderPrint`] beside the body and carries the body through untouched.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde")]
#[schemars(crate = "printobserver_types::schemars")]
pub struct TestProviderAlert {
    /// How sure the provider was.
    pub severity: String,
    /// Whether the provider paused the print itself.
    pub paused: bool,
}

impl EventPayload for TestProviderAlert {
    const KIND: &'static str = "test_provider_alert";
}

/// A printer notification from the provider these journeys stand in for.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde")]
#[schemars(crate = "printobserver_types::schemars")]
pub struct TestProviderNotification {
    /// What the provider said happened.
    pub what: String,
}

impl EventPayload for TestProviderNotification {
    const KIND: &'static str = "test_provider_notification";
}

/// The kind the test provider's failure alerts are written under.
#[must_use]
pub fn alert_kind() -> EventKind {
    TestProviderAlert::kind()
}

/// The kind the test provider's notifications are written under.
#[must_use]
pub fn notification_kind() -> EventKind {
    TestProviderNotification::kind()
}

/// One failure alert about a print, carrying no image.
#[must_use]
pub fn failure_alert(provider_print_id: i64) -> NormalizedAlert {
    NormalizedAlert {
        source: EventSource::new(TEST_PROVIDER_SOURCE),
        received_at: at(0),
        body: EventBody::of(&TestProviderAlert {
            severity: "failure".to_owned(),
            paused: false,
        })
        .expect("a payload renders"),
        raw: RawBytes::new(br#"{"event":"print_failure"}"#.to_vec()),
        image_url: None,
        print: Some(ProviderPrint {
            id: provider_print_id,
            file_name: Some("benchy.gcode".to_owned()),
            started_at: None,
        }),
        detection: None,
        signal: None,
    }
}

/// The provider's own identifier for the printer its detections are about.
pub const DETECTOR_PRINTER_ID: i64 = 41;

/// A failure alert whose detector paused the print itself before alerting.
#[must_use]
pub fn detector_paused_alert(provider_print_id: i64) -> NormalizedAlert {
    NormalizedAlert {
        detection: Some(printobserver_vision_api::Detection {
            warning: false,
            paused_the_print: true,
            provider_printer_id: DETECTOR_PRINTER_ID,
        }),
        ..failure_alert(provider_print_id)
    }
}

/// The same alert, naming an image for the loop to fetch and store.
#[must_use]
pub fn failure_alert_with_image(provider_print_id: i64) -> NormalizedAlert {
    NormalizedAlert {
        image_url: Some("https://provider.example/snapshot.png".to_owned()),
        ..failure_alert(provider_print_id)
    }
}

/// One printer notification about a print, carrying no image.
#[must_use]
pub fn notification_alert(provider_print_id: i64) -> NormalizedAlert {
    NormalizedAlert {
        body: EventBody::of(&TestProviderNotification {
            what: "paused".to_owned(),
        })
        .expect("a payload renders"),
        ..failure_alert(provider_print_id)
    }
}

/// One alert naming no print this system knows.
///
/// An externally sourced body may name no print at all, and the history holds
/// it rather than dropping it.
#[must_use]
pub fn unattributed_alert() -> NormalizedAlert {
    NormalizedAlert {
        body: EventBody::of(&MalformedExternalEventPayload {
            detail: "the body is not JSON: expected value at line 1 column 1".to_owned(),
        })
        .expect("a payload renders"),
        print: None,
        ..failure_alert(7)
    }
}

/// A manifest naming the ranges given for it, and nothing else.
#[must_use]
pub fn manifest(allowed: &[(Adjustable, Range)]) -> JobManifest {
    JobManifest {
        file_name: "benchy.gcode".to_owned(),
        material: "PLA".to_owned(),
        nozzle_diameter_mm: 0.4,
        slicer_profile: "0.20mm SPEED".to_owned(),
        sheet: Some("smooth-pei".to_owned()),
        allowed: allowed.iter().copied().collect(),
        metadata: BTreeMap::new(),
        segment_spools: Vec::new(),
    }
}