printobserver-server 0.20.2

The printobserver server.
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
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
//! Every request is the identity its credential authenticated.
//!
//! A supervision turn is issued a credential of its own, bound to the agent
//! class, its session and its print; the operator's credential is the
//! operator. These journeys hold a real turn open — the stand-in agent is
//! issued its credential the way the adapter is, and waits — and drive the
//! real router with that credential and with the operator's, reading what each
//! request left behind off the far side of every port: the machine, the
//! print's history and the action record.

use printobserver_core::store::Stores;
use printobserver_supervisor_api::SupervisorError;
use printobserver_types::PrintId;
use printobserver_types::serde_json::{Value, json};

use crate::agent::{Pass, StandInAgent, session_of};
use crate::authenticating::history;
use crate::printer::RecordingPrinter;
use crate::world::{SECRET, World, failure_alert, presenting, set};

/// The provider identifier the journeys' print carries, which an alert about
/// it names.
const OBICO_PRINT: i64 = 4211;

/// Post one failure alert about the journeys' print, which starts a turn.
async fn alert(world: &World) {
    let status = reqwest::Client::new()
        .post(format!("{}?token={SECRET}", world.server.ingress_url()))
        .header(reqwest::header::CONTENT_TYPE, "application/json")
        .body(failure_alert(OBICO_PRINT, "http://127.0.0.1:1/frame.jpg").to_string())
        .send()
        .await
        .expect("the ingress answers")
        .status();
    assert_eq!(status, reqwest::StatusCode::ACCEPTED);
}

/// A world with a print, and one turn about it held open: what the turn was
/// issued.
pub async fn held_turn(world: &World) -> (PrintId, Pass) {
    let print_id = world.open_print().await;
    world.agent.hold_turns();
    alert(world).await;
    let pass = world
        .agent
        .issued(1)
        .await
        .into_iter()
        .next()
        .expect("one pass");
    (print_id, pass)
}

/// The body of one action, claiming one actor.
fn claiming(actor: &Value, extra: &[(&str, Value)]) -> Value {
    let mut body = json!({
        "reason": "a journey is asking as somebody",
        "actor": actor,
    });
    for (key, value) in extra {
        body[*key] = value.clone();
    }
    body
}

/// A manifest a start or a manifest write carries.
fn manifest() -> Value {
    printobserver_types::serde_json::to_value(crate::world::start_manifest())
        .expect("a manifest renders")
}

/// The actor document of one agent session.
pub fn agent(session_name: &str) -> Value {
    json!({ "agent": { "session_name": session_name } })
}

/// Send one request and read its status and its error text.
pub async fn sent(request: reqwest::RequestBuilder) -> (reqwest::StatusCode, Value) {
    let response = request.send().await.expect("the server answers");
    let status = response.status();
    let body: Value = response.json().await.expect("the answer is JSON");
    (status, body)
}

/// One action's URL on one print.
fn action_url(world: &World, print_id: PrintId, action: &str) -> String {
    world.url(&format!("/prints/{print_id}/actions/{action}"))
}

/// How many events one print's history holds: every action requested, decided
/// on and carried out is written there.
async fn record_of(stores: &Stores, print_id: PrintId) -> usize {
    history(stores, print_id).await
}

/// Assert one answer is a refusal naming who authenticated and what was asked.
fn assert_forbidden(answer: &(reqwest::StatusCode, Value), what: &str, naming: &[&str]) {
    assert_eq!(
        answer.0,
        reqwest::StatusCode::FORBIDDEN,
        "{what} was not refused as forbidden: {}",
        answer.1
    );
    let said = answer.1["error"].as_str().unwrap_or_default();
    for named in naming {
        assert!(
            said.contains(named),
            "the refusal of {what} does not name {named:?}: {said}"
        );
    }
}

/// A turn's credential is admitted during its turn for its own print: its
/// reads, the listing beside them, and an action its grants allow, as itself.
#[tokio::test(flavor = "multi_thread")]
async fn a_turn_credential_is_its_own_session_on_its_own_print() {
    let world = World::open().await;
    let (print_id, pass) = held_turn(&world).await;
    let turn = presenting(&pass.credential);
    let session = session_of(print_id);
    assert_eq!(pass.session_name, session);
    assert_eq!(
        pass.server.as_deref(),
        Some(format!("http://{}", world.server.address()).as_str()),
        "the turn was not told the address this server bound"
    );

    // Its own print's reads, and the listing.
    for path in [
        format!("/prints/{print_id}/status"),
        format!("/prints/{print_id}/context"),
        format!("/prints/{print_id}/history"),
        format!("/prints/{print_id}/manifest"),
        format!("/events?print_id={print_id}"),
        "/prints".to_owned(),
    ] {
        let (status, body) = sent(turn.get(world.url(&path))).await;
        assert_eq!(status, reqwest::StatusCode::OK, "{path}: {body}");
    }

    // And an action its grants allow, as itself, on its own print.
    let (status, body) = sent(
        turn.post(action_url(&world, print_id, "pause"))
            .json(&claiming(&agent(&session), &[])),
    )
    .await;
    assert_eq!(status, reqwest::StatusCode::OK, "{body}");
    assert_eq!(
        body["record"]["request"]["actor"],
        agent(&session),
        "{body}"
    );

    world.agent.release_turns();
    world.server.stop().await;
}

/// Every claim a turn's credential makes that is not its own session, every
/// other print and both operator-only writes are refused before anything is
/// decided or recorded.
#[tokio::test(flavor = "multi_thread")]
async fn a_turn_credential_reaching_past_its_own_session_and_print_is_refused() {
    let world = World::open().await;
    let (print_id, pass) = held_turn(&world).await;
    let other = world.open_print().await;
    let turn = presenting(&pass.credential);
    let session = session_of(print_id);
    world.printer.forget();
    let before = record_of(&world.stores, print_id).await;

    // Every claim that is not this turn's own session.
    for (claimed, named) in [
        (json!("operator"), "the operator"),
        (json!("system"), "the system"),
        (agent("print-another-session"), "print-another-session"),
    ] {
        let answer = sent(
            turn.post(action_url(&world, print_id, "cancel"))
                .json(&claiming(&claimed, &[])),
        )
        .await;
        assert_forbidden(
            &answer,
            &format!("a turn claiming {claimed}"),
            &[&session, named],
        );
    }
    // Another print, read or acted on.
    let answer = sent(turn.get(world.url(&format!("/prints/{other}/status")))).await;
    assert_forbidden(
        &answer,
        "a turn reading another print",
        &[&session, &other.to_string()],
    );
    let answer = sent(
        turn.post(action_url(&world, other, "pause"))
            .json(&claiming(&agent(&session), &[])),
    )
    .await;
    assert_forbidden(
        &answer,
        "a turn acting on another print",
        &[&session, &other.to_string()],
    );
    // The two writes that are the operator's alone.
    let answer = sent(
        turn.post(action_url(&world, print_id, "start_print"))
            .json(&claiming(
                &agent(&session),
                &[
                    ("file_name", json!("benchy.gcode")),
                    ("manifest", manifest()),
                ],
            )),
    )
    .await;
    assert_forbidden(
        &answer,
        "a turn starting a print",
        &[&session, "start-print"],
    );
    let answer = sent(
        turn.put(world.url(&format!("/prints/{print_id}/manifest")))
            .json(&json!({"reason": "widening my own bounds", "manifest": manifest()})),
    )
    .await;
    assert_forbidden(
        &answer,
        "a turn replacing a manifest",
        &[&session, "manifest-set"],
    );

    assert!(
        world.printer.calls().is_empty(),
        "a refused request reached the machine: {:?}",
        world.printer.calls()
    );
    assert_eq!(
        record_of(&world.stores, print_id).await,
        before,
        "a refused request was decided on or recorded"
    );

    world.agent.release_turns();
    world.server.stop().await;
}

/// The ticket's own request: an agent holding its turn's credential asks to
/// cancel the print as the operator, which its grants exclude.
#[tokio::test(flavor = "multi_thread")]
async fn a_turn_asking_to_cancel_as_the_operator_is_refused() {
    let world = World::open().await;
    let (print_id, pass) = held_turn(&world).await;
    world.printer.forget();

    let answer = sent(
        presenting(&pass.credential)
            .post(action_url(&world, print_id, "cancel"))
            .json(&claiming(&json!("operator"), &[])),
    )
    .await;

    assert_forbidden(
        &answer,
        "a turn cancelling as the operator",
        &["the operator", &session_of(print_id)],
    );
    assert!(world.printer.calls().is_empty());
    world.agent.release_turns();
    world.server.stop().await;
}

/// The operator's credential is the operator: claiming the agent, or the
/// system, is refused rather than overridden.
#[tokio::test(flavor = "multi_thread")]
async fn the_operators_credential_claiming_anybody_else_is_refused() {
    let world = World::open().await;
    let print_id = world.open_print().await;
    let before = record_of(&world.stores, print_id).await;

    for (claimed, named) in [
        (agent(&session_of(print_id)), "the agent"),
        (json!("system"), "the system"),
    ] {
        let answer = sent(
            world
                .client
                .post(action_url(&world, print_id, "pause"))
                .json(&claiming(&claimed, &[])),
        )
        .await;
        assert_forbidden(
            &answer,
            &format!("the operator claiming {claimed}"),
            &["the operator", named],
        );
    }
    assert!(world.printer.calls().is_empty());
    assert_eq!(record_of(&world.stores, print_id).await, before);

    let (status, body) = sent(
        world
            .client
            .post(action_url(&world, print_id, "pause"))
            .json(&claiming(&json!("operator"), &[])),
    )
    .await;
    assert_eq!(status, reqwest::StatusCode::OK, "{body}");
    world.server.stop().await;
}

/// Whether one server admits one credential, asked through the listing.
async fn admitted(world: &World, credential: &str) -> bool {
    presenting(credential)
        .get(world.url("/prints"))
        .send()
        .await
        .expect("the server answers")
        .status()
        != reqwest::StatusCode::UNAUTHORIZED
}

/// A turn's credential stops being admitted when its turn returns and after a
/// restart, two turns are issued two credentials, and none of them is in any
/// file under the state directory.
#[tokio::test(flavor = "multi_thread")]
async fn a_turn_credential_ends_with_its_turn_and_is_written_nowhere() {
    let world = World::open().await;
    let (_, first) = held_turn(&world).await;
    assert!(admitted(&world, &first.credential).await);
    let mut completions = world.server.completions();
    world.agent.release_turns();
    completions.changed().await.expect("the handling finishes");
    assert!(
        !admitted(&world, &first.credential).await,
        "a turn's credential was admitted after its turn returned"
    );

    world.agent.hold_turns();
    alert(&world).await;
    let second = world.agent.issued(2).await[1].clone();
    assert_ne!(
        first.credential, second.credential,
        "two turns shared a credential"
    );
    assert!(admitted(&world, &second.credential).await);

    // What is on disk after a turn ran and another is running.
    let state = world.state_dir();
    for credential in [&first.credential, &second.credential] {
        let carrying = crate::world::files_carrying(&state, credential);
        assert!(
            carrying.is_empty(),
            "a turn's credential is written under the state directory: {carrying:?}"
        );
    }

    // A restart admits nothing the server before it minted.
    world.agent.release_turns();
    let world = world.restart().await;
    assert!(
        !admitted(&world, &second.credential).await,
        "a turn's credential was admitted after a restart"
    );
    world.server.stop().await;
}

/// The agent's minimum interval holds every machine-changing action a turn's
/// credential asks for, and claiming the operator to step around it is refused.
#[tokio::test(flavor = "multi_thread")]
async fn the_agent_interval_holds_every_turn_whatever_it_claims() {
    let world = World::configured(
        RecordingPrinter::printing(),
        StandInAgent::new(),
        |document| {
            set(
                document,
                "safety.agent_min_interval_s",
                toml::Value::Integer(30),
            );
        },
    )
    .await;
    let (print_id, pass) = held_turn(&world).await;
    let turn = presenting(&pass.credential);
    let session = session_of(print_id);

    let (status, body) = sent(
        turn.post(action_url(&world, print_id, "set_fan_percent"))
            .json(&claiming(&agent(&session), &[("percent", json!(40.0))])),
    )
    .await;
    assert_eq!(status, reqwest::StatusCode::OK, "{body}");

    let (status, body) = sent(
        turn.post(action_url(&world, print_id, "set_feedrate_factor"))
            .json(&claiming(&agent(&session), &[("factor", json!(1.1))])),
    )
    .await;
    assert_eq!(status, reqwest::StatusCode::CONFLICT, "{body}");
    assert!(
        body["record"]["decision"]["rejected"]
            .get("min_interval_not_elapsed")
            .is_some(),
        "the second change was not held by the agent's interval: {body}"
    );

    let answer = sent(
        turn.post(action_url(&world, print_id, "set_feedrate_factor"))
            .json(&claiming(&json!("operator"), &[("factor", json!(1.1))])),
    )
    .await;
    assert_forbidden(
        &answer,
        "a turn stepping around its interval as the operator",
        &[&session, "the operator"],
    );
    world.agent.release_turns();
    world.server.stop().await;
}

/// A turn whose run fails, or times out, has its credential revoked when it
/// returns exactly as a turn that answered does.
#[tokio::test(flavor = "multi_thread")]
async fn a_turn_that_fails_or_times_out_is_revoked_when_it_returns() {
    for (what, error) in [
        ("timed out", SupervisorError::TimedOut),
        (
            "failed",
            SupervisorError::Unavailable {
                detail: "the harness could not be reached".to_owned(),
            },
        ),
    ] {
        let world = World::open().await;
        world.agent.fail_turns_with(error);
        let (_, pass) = held_turn(&world).await;
        assert!(
            admitted(&world, &pass.credential).await,
            "the credential of a turn that {what} was not admitted while it ran"
        );

        let mut completions = world.server.completions();
        world.agent.release_turns();
        completions.changed().await.expect("the handling finishes");

        assert!(
            !admitted(&world, &pass.credential).await,
            "the credential of a turn that {what} was admitted after it returned"
        );
        world.server.stop().await;
    }
}

/// A turn moved into a second session — as the adapter moves one whose
/// session the harness refused to continue — is issued that session's
/// credential, and the first session's is refused from that moment: a turn
/// holds one live credential, for the session it is running in.
#[tokio::test(flavor = "multi_thread")]
async fn a_turn_moved_to_a_second_session_holds_only_that_sessions_credential() {
    let world = World::open().await;
    world.agent.move_turns_to_a_second_session();
    let print_id = world.open_print().await;
    world.agent.hold_turns();
    alert(&world).await;
    let passes = world.agent.issued(2).await;
    let (first, second) = (&passes[0], &passes[1]);
    assert_eq!(first.session_name, session_of(print_id));
    assert_eq!(second.session_name, format!("{}-2", session_of(print_id)));

    assert!(
        !admitted(&world, &first.credential).await,
        "the first session's credential is still admitted once the second is issued"
    );
    let turn = presenting(&second.credential);
    let answer = sent(
        turn.post(action_url(&world, print_id, "pause"))
            .json(&claiming(&agent(&first.session_name), &[])),
    )
    .await;
    assert_forbidden(
        &answer,
        "the second session claiming the first",
        &[&first.session_name, &second.session_name],
    );
    let (status, body) = sent(
        turn.post(action_url(&world, print_id, "pause"))
            .json(&claiming(&agent(&second.session_name), &[])),
    )
    .await;
    assert_eq!(status, reqwest::StatusCode::OK, "{body}");
    world.agent.release_turns();
    world.server.stop().await;
}

/// One image stored against one print, as the ingress stores an alert's.
async fn an_image_of(world: &World, print_id: PrintId) -> printobserver_core::ImageRecord {
    let event = world
        .stores
        .events
        .append_event(printobserver_core::store::EventDraft {
            print_id: Some(print_id),
            source: printobserver_core::system_source(),
            received_at: printobserver_types::Timestamp::now(),
            body: printobserver_types::EventBody {
                kind: printobserver_types::EventKind::new("malformed_external_event")
                    .expect("a kind name"),
                payload: json!({ "detail": "a journey's own event" }),
            },
            raw: None,
        })
        .await
        .expect("an event is appended");
    world
        .stores
        .images
        .put_image(
            print_id,
            event.id,
            None,
            "image/jpeg".to_owned(),
            printobserver_types::RawBytes::new(b"the bytes of a frame".to_vec()),
        )
        .await
        .expect("an image is stored")
}

/// Every read about another print is refused for a turn — its context, a look
/// at it, its history, its manifest, and an image of it, whether or not that
/// image's file is still there — while an image of its own print is served.
#[tokio::test(flavor = "multi_thread")]
async fn a_turn_credential_reads_nothing_of_another_print() {
    let world = World::open().await;
    let (print_id, pass) = held_turn(&world).await;
    let other = world.open_print().await;
    let turn = presenting(&pass.credential);
    let session = session_of(print_id);

    for path in [
        format!("/prints/{other}/context"),
        format!("/prints/{other}/look"),
        format!("/prints/{other}/history"),
        format!("/prints/{other}/manifest"),
        format!("/events?print_id={other}"),
    ] {
        let answer = sent(turn.get(world.url(&path))).await;
        assert_forbidden(
            &answer,
            &format!("a turn reading {path}"),
            &[&session, &other.to_string()],
        );
    }

    // Every print's events at once are the operator's to read.
    let answer = sent(turn.get(world.url("/events"))).await;
    assert_forbidden(
        &answer,
        "a turn reading every print's events",
        &[&print_id.to_string(), "print_id"],
    );

    let own = an_image_of(&world, print_id).await;
    let (status, body) = sent(turn.get(world.url(&format!("/images/{}", own.id)))).await;
    assert_eq!(status, reqwest::StatusCode::OK, "{body}");
    let foreign = an_image_of(&world, other).await;
    let answer = sent(turn.get(world.url(&format!("/images/{}", foreign.id)))).await;
    assert_forbidden(&answer, "a turn reading another print's image", &[&session]);
    std::fs::remove_file(world.state_dir().join(&foreign.relative_path))
        .expect("the image's file is removable");
    let answer = sent(turn.get(world.url(&format!("/images/{}", foreign.id)))).await;
    assert_forbidden(
        &answer,
        "a turn reading another print's image whose file is gone",
        &[&session],
    );
    world.agent.release_turns();
    world.server.stop().await;
}

/// What a turn's credential may never ask for is refused `403` whatever body
/// it carries: a start, a manifest replacement and an action on another print
/// with a body that is not one are refused for who asked rather than for the
/// body.
#[tokio::test(flavor = "multi_thread")]
async fn a_turn_credentials_forbidden_requests_are_refused_whatever_their_bodies() {
    let world = World::open().await;
    let (print_id, pass) = held_turn(&world).await;
    let other = world.open_print().await;
    let turn = presenting(&pass.credential);
    let session = session_of(print_id);
    let not_a_body = "{ this is not a body";

    for (what, request) in [
        (
            "a start",
            turn.post(action_url(&world, print_id, "start_print")),
        ),
        (
            "a manifest replacement",
            turn.put(world.url(&format!("/prints/{print_id}/manifest"))),
        ),
        (
            "an action on another print",
            turn.post(action_url(&world, other, "pause")),
        ),
    ] {
        let answer = sent(
            request
                .header(reqwest::header::CONTENT_TYPE, "application/json")
                .body(not_a_body),
        )
        .await;
        assert_forbidden(&answer, &format!("{what} with no body"), &[&session]);
    }
    world.agent.release_turns();
    world.server.stop().await;
}

/// Status and context reflect an operator's completed action even while the
/// event's supervision turn remains open; a refused action changes neither.
#[tokio::test(flavor = "multi_thread")]
async fn reads_during_a_turn_reflect_the_operators_latest_action() {
    let world = World::open().await;
    let (print_id, pass) = held_turn(&world).await;
    let action = action_url(&world, print_id, "set_feedrate_factor");
    let (accepted, answer) = world
        .post(
            &action,
            &claiming(
                &json!("operator"),
                &[("factor", json!(1.2)), ("duration_s", json!(120))],
            ),
        )
        .await;
    assert_eq!(accepted, reqwest::StatusCode::OK, "{answer}");
    let intervention = answer["intervention"]["id"].clone();
    assert!(intervention.is_string(), "{answer}");
    for credential in [&world.credential, &pass.credential] {
        for read in ["status", "context"] {
            let (status, answer) =
                sent(presenting(credential).get(world.url(&format!("/prints/{print_id}/{read}"))))
                    .await;
            assert_eq!(status, reqwest::StatusCode::OK, "{answer}");
            let context = if read == "context" {
                &answer["context"]
            } else {
                &answer
            };
            // A context states no printer's reported factors: what is in force
            // is the intervention.
            if read == "status" {
                assert_eq!(
                    context["printer"]["feedrate_factor"]["value"],
                    json!(1.2),
                    "{answer}"
                );
            }
            assert!(
                context["interventions"]
                    .as_array()
                    .expect("interventions")
                    .iter()
                    .any(|held| held["id"] == intervention),
                "the operator's intervention is absent during the held turn: {answer}"
            );
        }
    }
    let (refused, answer) = world
        .post(
            &action,
            &claiming(&json!("operator"), &[("factor", json!(9.0))]),
        )
        .await;
    assert_eq!(refused, reqwest::StatusCode::CONFLICT, "{answer}");
    let (_, unchanged) = world
        .get(&world.url(&format!("/prints/{print_id}/status")))
        .await;
    assert_eq!(
        unchanged["printer"]["feedrate_factor"]["value"],
        json!(1.2),
        "{unchanged}"
    );
    assert_eq!(
        unchanged["interventions"][0]["id"], intervention,
        "{unchanged}"
    );
    let (_, history) = world
        .get(&world.url(&format!("/prints/{print_id}/history")))
        .await;
    assert!(
        history.to_string().contains("9.0"),
        "the refused action is absent: {history}"
    );
    world.agent.release_turns();
    world.server.stop().await;
}

/// What belongs to no print is the operator's: a turn's credential is refused
/// a look at the printer and a frame of the printer, before anything is
/// looked at, while the operator's is served both.
#[tokio::test(flavor = "multi_thread")]
async fn a_turn_credential_is_refused_what_belongs_to_no_print() {
    let world = World::open().await;
    let (print_id, pass) = held_turn(&world).await;
    let turn = presenting(&pass.credential);
    let session = session_of(print_id);

    let answer = sent(turn.get(world.url("/look"))).await;
    assert_forbidden(&answer, "a turn's look at the printer", &[&session]);

    let (status, look) = world.get(&world.url("/look")).await;
    assert_eq!(status, reqwest::StatusCode::OK, "{look}");
    assert!(look["event"].get("print_id").is_none(), "{look}");
    let printless = world
        .stores
        .events
        .append_event_with_image(
            printobserver_core::store::EventDraft {
                print_id: None,
                source: printobserver_core::system_source(),
                received_at: printobserver_types::Timestamp::now(),
                body: printobserver_types::EventBody {
                    kind: printobserver_types::EventKind::new("camera_look").expect("a kind"),
                    payload: json!({ "waited_s": 0, "delivered": [] }),
                },
                raw: None,
            },
            printobserver_core::store::ImageDraft {
                source_url: None,
                content_type: "image/jpeg".to_owned(),
                bytes: printobserver_types::RawBytes::new(b"a frame of the printer".to_vec()),
            },
        )
        .await
        .expect("a frame of no print is stored");
    let frame = printless.image.expect("the frame is the event's image");
    let path = format!("/images/{}", frame.id);
    let answer = sent(turn.get(world.url(&path))).await;
    assert_forbidden(
        &answer,
        "a turn reading a frame of the printer",
        &[&session, "no print"],
    );
    let (status, image) = world.get(&world.url(&path)).await;
    assert_eq!(status, reqwest::StatusCode::OK, "{image}");
    assert!(image["record"].get("print_id").is_none(), "{image}");
    assert!(image["path"].is_string(), "{image}");
    world.agent.release_turns();
    world.server.stop().await;
}

/// A turn's acknowledgement before its look is refused, naming the look to run,
/// and recorded nowhere; a look its camera fails to give a frame for is still a
/// look the turn took, after which the same acknowledgement is taken.
#[tokio::test(flavor = "multi_thread")]
async fn a_turn_acknowledges_only_after_a_look_even_one_its_camera_failed() {
    let camera = crate::http_host::Host::answering(
        "500 Internal Server Error",
        "text/plain",
        b"no".to_vec(),
    )
    .await;
    let world = World::configured(
        RecordingPrinter::printing(),
        crate::agent::StandInAgent::new(),
        |document| {
            let mut table = toml::Table::new();
            table.insert("snapshot_url".to_owned(), toml::Value::String(camera.url()));
            set(document, "camera", toml::Value::Table(table));
            set(
                document,
                "safety.actions.agent",
                toml::Value::Array(vec![toml::Value::String("acknowledge_failure".to_owned())]),
            );
        },
    )
    .await;
    let (print_id, pass) = held_turn(&world).await;
    let turn = presenting(&pass.credential);
    let alerted = world
        .stores
        .events
        .history(printobserver_core::store::HistoryQuery {
            print_id,
            kinds: Vec::new(),
            since: None,
            until: None,
            limit: Some(50),
        })
        .await
        .expect("the history reads")
        .into_iter()
        .find(|event| event.body.kind.as_str() == "obico_failure_alert")
        .expect("the alert is in the history");
    let acknowledgement = claiming(
        &agent(&pass.session_name),
        &[
            ("event_id", json!(alerted.id.to_string())),
            ("disposition", json!("stop")),
        ],
    );

    let before = record_of(&world.stores, print_id).await;
    let early = sent(
        turn.post(action_url(&world, print_id, "acknowledge_failure"))
            .json(&acknowledgement),
    )
    .await;
    assert_forbidden(
        &early,
        "an acknowledgement before the turn's look",
        &[
            "before the turn has taken a look",
            &format!("printobserver look --print-id {print_id}"),
        ],
    );
    assert_eq!(
        record_of(&world.stores, print_id).await,
        before,
        "a refused acknowledgement was recorded"
    );

    let (status, look) =
        sent(turn.get(world.url(&format!("/prints/{print_id}/look?wait_s=0")))).await;
    assert_eq!(status, reqwest::StatusCode::OK, "{look}");
    assert!(
        look.get("frame").is_none(),
        "the failing camera gave a frame: {look}"
    );

    let (status, body) = sent(
        turn.post(action_url(&world, print_id, "acknowledge_failure"))
            .json(&acknowledgement),
    )
    .await;
    assert_eq!(status, reqwest::StatusCode::OK, "{body}");
    assert_eq!(body["record"]["decision"], "accepted", "{body}");
    world.agent.release_turns();
    world.server.stop().await;
}