printobserver-server 0.4.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
//! What every journey here drives: a real server, over a real HTTP client.
//!
//! Nothing below stands in for the layer under test. The router, the policy,
//! the store, the ingress and the vision adapter are the real ones; the two
//! things a journey supplies are the external systems on the far side of a
//! port — the machine and the supervising agent — and the real ones are what
//! this crate's integration tier runs against.

use std::path::{Path, PathBuf};
use std::sync::Arc;

use printobserver_core::store::Stores;
use printobserver_obico::{ObicoVision, ObicoVisionConfig};
use printobserver_server::{Ports, Running, Server, ServerConfig};
use printobserver_store_sqlite::SqliteStore;
use printobserver_types::{PrintId, serde_json};
use tempfile::TempDir;

use crate::agent::StandInAgent;
use crate::printer::RecordingPrinter;

/// The shared secret every journey's ingress requires.
pub const SECRET: &str = "a-shared-secret-nothing-else-knows";

/// The file the configuration is written to under a journey's own root.
pub const CONFIG_FILE: &str = "config.toml";

/// The operator credential every journey's server admits: the base
/// configuration names its verifier, as an operator who ran
/// `printobserver credential issue` puts it there, and nothing the server
/// writes carries the credential itself.
pub const OPERATOR: &str = "a-journeys-own-operator-credential-K4m8Qz2Vx7wR";

/// The `api.credential_verifier` line that admits [`OPERATOR`].
#[must_use]
pub fn operator_verifier() -> String {
    printobserver_server::CredentialVerifier::of(OPERATOR).to_string()
}

/// The committed skill, `skills/printobserver/SKILL.md`: the Agent Skill an
/// installed host takes from `gh skill install`, read here from the tree.
#[must_use]
pub fn committed_skill() -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("..")
        .join("..")
        .join("skills")
        .join("printobserver")
        .join("SKILL.md")
}

/// One configuration document, in the shape the file takes.
///
/// Built from values rather than from a string, so a journey that makes one
/// field unacceptable changes that field and nothing else.
#[must_use]
pub fn document(root: &Path, octoprint_url: &str) -> toml::Value {
    let text = format!(
        r#"
state_dir = {state}
listen = "127.0.0.1:0"

[octoprint]
url = "{octoprint_url}"
api_key = "a-provisioned-key"
fan = "commandable"

[supervisor]
harness = "claude-code"
skill_path = {skill}

[ingress]
shared_secret = "{SECRET}"
answer_bound_ms = 1000

[api]
credential_verifier = "{verifier}"

[safety]
agent_min_interval_s = 0

[safety.allowed]
feedrate = {{ min = 0.5, max = 1.5 }}
flowrate = {{ min = 0.9, max = 1.1 }}
fan = {{ min = 0.0, max = 100.0 }}
bed_target = {{ min = 0.0, max = 110.0 }}
"tool_target:0" = {{ min = 0.0, max = 260.0 }}

[safety.actions]
operator = ["pause", "resume", "cancel", "start_print", "set_feedrate_factor",
            "set_flowrate_factor", "set_tool_target_c", "set_bed_target_c",
            "set_fan_percent", "acknowledge_failure", "register_spool", "load_spool",
            "unload_spool", "adjust_spool", "retire_spool"]
agent = ["pause", "set_feedrate_factor", "set_fan_percent"]
system = ["set_feedrate_factor", "set_flowrate_factor", "set_tool_target_c",
          "set_bed_target_c", "set_fan_percent"]
"#,
        // A TOML string rather than the path spliced between quotes: a Windows
        // path's separators are escapes inside a basic string.
        state = toml::Value::String(root.join("state").display().to_string()),
        skill = toml::Value::String(committed_skill().display().to_string()),
        verifier = operator_verifier(),
    );
    toml::from_str(&text).expect("the base configuration is a document")
}

/// Set one dotted key of a configuration document.
///
/// # Panics
///
/// Panics when the path names no table, which is a journey naming a field the
/// document does not have.
pub fn set(document: &mut toml::Value, dotted: &str, value: toml::Value) {
    let (table, last) = table_of(document, dotted);
    table.insert(last, value);
}

/// Remove one dotted key of a configuration document.
///
/// # Panics
///
/// Panics when the path names no table.
pub fn remove(document: &mut toml::Value, dotted: &str) {
    let (table, last) = table_of(document, dotted);
    table.remove(&last);
}

/// The table one dotted key lives in, and the key's own last segment.
fn table_of<'a>(document: &'a mut toml::Value, dotted: &str) -> (&'a mut toml::Table, String) {
    let mut segments: Vec<&str> = dotted.split('.').collect();
    let last = segments
        .pop()
        .expect("a key has at least one segment")
        .to_owned();
    let mut here = document;
    for segment in segments {
        here = here
            .get_mut(segment)
            .unwrap_or_else(|| panic!("the document has no `{segment}` table"));
    }
    (
        here.as_table_mut()
            .unwrap_or_else(|| panic!("`{dotted}` does not name a table entry")),
        last,
    )
}

/// Write one configuration document into a root, and answer its path.
pub fn write(root: &Path, document: &toml::Value) -> PathBuf {
    let path = root.join(CONFIG_FILE);
    std::fs::write(
        &path,
        toml::to_string(document).expect("a configuration document renders"),
    )
    .expect("the configuration is writable");
    path
}

/// One journey's own world: a running server, and what it was composed from.
pub struct World {
    /// The journey's root, removed when it is dropped.
    pub root: TempDir,
    /// The server, serving.
    pub server: Running,
    /// The machine it is acting on.
    pub printer: Arc<RecordingPrinter>,
    /// The agent it is supervising through.
    pub agent: Arc<StandInAgent>,
    /// Durable state, as the server holds it.
    pub stores: Stores,
    /// The client a journey drives the real surface with, presenting the
    /// operator's credential on every request.
    pub client: reqwest::Client,
    /// That credential: [`OPERATOR`], whose verifier the configuration names.
    pub credential: String,
}

impl World {
    /// A server over a fresh root, with a machine part-way through a print.
    pub async fn open() -> Self {
        Self::open_with(RecordingPrinter::printing(), StandInAgent::new()).await
    }

    /// A server over a fresh root, over the machine and agent given.
    ///
    /// The base configuration names the verifier of [`OPERATOR`], which is
    /// what an operator who issued a credential configures, and every
    /// journey's client presents that credential.
    pub async fn open_with(printer: Arc<RecordingPrinter>, agent: Arc<StandInAgent>) -> Self {
        Self::configured(printer, agent, |_| {}).await
    }

    /// A server over a fresh root, over the machine and agent given, under the
    /// base configuration as one journey edits it.
    pub async fn configured(
        printer: Arc<RecordingPrinter>,
        agent: Arc<StandInAgent>,
        edit: impl FnOnce(&mut toml::Value),
    ) -> Self {
        Self::configured_over(printer, agent, edit, |stores| stores).await
    }

    /// The same, with the durable stores as one journey stands something
    /// between them and the server.
    pub async fn configured_over(
        printer: Arc<RecordingPrinter>,
        agent: Arc<StandInAgent>,
        edit: impl FnOnce(&mut toml::Value),
        between: impl FnOnce(Stores) -> Stores,
    ) -> Self {
        let root = TempDir::new().expect("a journey's own root");
        let mut configured = document(root.path(), "http://127.0.0.1:1");
        edit(&mut configured);
        let path = write(root.path(), &configured);
        let config = ServerConfig::load(&path).expect("the base configuration is accepted");
        let (server, stores) = start(&config, &printer, &agent, between).await;
        let credential = OPERATOR.to_owned();
        Self {
            root,
            server,
            printer,
            agent,
            stores,
            client: presenting(&credential),
            credential,
        }
    }

    /// Stop this server and start another over the same state directory.
    ///
    /// This is what a restart is: the store and the session directory are the
    /// whole of the state, and nothing else is carried across.
    pub async fn restart(self) -> Self {
        self.restart_over(|stores| stores).await
    }

    /// The same, with the durable stores of the new server as one journey
    /// stands something between them and it.
    pub async fn restart_over(self, between: impl FnOnce(Stores) -> Stores) -> Self {
        let Self {
            root,
            server,
            printer,
            agent,
            client,
            credential,
            ..
        } = self;
        let config = server.config().clone();
        server.stop().await;
        let (server, stores) = start(&config, &printer, &agent, between).await;
        Self {
            root,
            server,
            printer,
            agent,
            stores,
            client,
            credential,
        }
    }

    /// Stop this server, attempt a start over the same state directory with
    /// something stood between the store and it that the start is refused
    /// over, and then start again with nothing between them — answering why
    /// the attempt was refused.
    ///
    /// # Panics
    ///
    /// Panics when the attempt started, which is a journey whose refusal did
    /// not happen.
    pub async fn restart_refused_over(
        self,
        between: impl FnOnce(Stores) -> Stores,
    ) -> (Self, String) {
        let config = self.server.config().clone();
        let Self {
            root,
            server,
            printer,
            agent,
            client,
            credential,
            ..
        } = self;
        server.stop().await;
        let stores = between(Stores::of(Arc::new(
            SqliteStore::open(&config.state_dir).expect("the store opens on the state directory"),
        )));
        let vision = Arc::new(
            ObicoVision::new(ObicoVisionConfig::default())
                .expect("the adapter is built")
                .with_api(config.obico_api.clone()),
        );
        let refused = Server::start_with(
            config.clone(),
            Ports {
                printer: Arc::clone(&printer) as Arc<dyn printobserver_printer_api::PrinterPort>,
                stores,
                vision,
                agent: Arc::clone(&agent) as Arc<dyn printobserver_supervisor_api::SupervisorPort>,
            },
        )
        .await
        .expect_err("the start was refused");
        let (server, stores) = start(&config, &printer, &agent, |stores| stores).await;
        (
            Self {
                root,
                server,
                printer,
                agent,
                stores,
                client,
                credential,
            },
            refused.to_string(),
        )
    }

    /// The state directory this world's store lives in.
    #[must_use]
    pub fn state_dir(&self) -> PathBuf {
        self.server.config().state_dir.clone()
    }

    /// One URL beneath the versioned prefix.
    #[must_use]
    pub fn url(&self, path: &str) -> String {
        format!("{}{path}", self.server.base_url())
    }

    /// One whole path on this server, prefix included.
    #[must_use]
    pub fn at(&self, whole_path: &str) -> String {
        format!("http://{}{whole_path}", self.server.address())
    }

    /// One operation's URL, with the print substituted into it.
    ///
    /// The path an operation declares already carries the versioned prefix, so
    /// this is taken as a whole path rather than beneath one.
    #[must_use]
    ///
    /// A spool command's path names a spool rather than a print, and is given
    /// one nothing holds: a journey about a spool it registered names that one
    /// with [`World::spool_url`].
    pub fn operation_url(&self, path: &str, print_id: PrintId) -> String {
        self.at(&path.replace("{print_id}", &print_id.to_string()).replace(
            "{spool_id}",
            &printobserver_core::SpoolId::new().to_string(),
        ))
    }

    /// One spool operation's URL, about one spool.
    #[must_use]
    pub fn spool_url(&self, operation: &str, spool_id: &str) -> String {
        let declared =
            printobserver_server::operation(operation).expect("the operation is declared");
        self.at(&declared.full_path().replace("{spool_id}", spool_id))
    }

    /// Open one print to act on.
    pub async fn open_print(&self) -> PrintId {
        self.stores
            .prints
            .open_print(Some(4211), Some("benchy.gcode".to_owned()))
            .await
            .expect("a print opens")
            .id
    }

    /// Read one answer without asking it to be JSON, for a journey about a
    /// path this server serves nothing at.
    pub async fn raw_get(&self, url: &str) -> (reqwest::StatusCode, String, String) {
        let response = self
            .client
            .get(url)
            .send()
            .await
            .expect("the server answers");
        let status = response.status();
        let media = response
            .headers()
            .get(reqwest::header::CONTENT_TYPE)
            .and_then(|value| value.to_str().ok())
            .unwrap_or_default()
            .to_owned();
        let text = response.text().await.expect("an answer has a body");
        (status, media, text)
    }

    /// Read one JSON answer, and the status it came under.
    pub async fn get(&self, url: &str) -> (reqwest::StatusCode, serde_json::Value) {
        let response = self
            .client
            .get(url)
            .header(reqwest::header::ACCEPT, printobserver_server::MEDIA_TYPE)
            .send()
            .await
            .expect("the server answers");
        read(response).await
    }

    /// Send one JSON body, and read the JSON answer.
    pub async fn post(
        &self,
        url: &str,
        body: &serde_json::Value,
    ) -> (reqwest::StatusCode, serde_json::Value) {
        let response = self
            .client
            .post(url)
            .json(body)
            .send()
            .await
            .expect("the server answers");
        read(response).await
    }

    /// Replace one record with a JSON body, and read the JSON answer.
    pub async fn put(
        &self,
        url: &str,
        body: &serde_json::Value,
    ) -> (reqwest::StatusCode, serde_json::Value) {
        let response = self
            .client
            .put(url)
            .json(body)
            .send()
            .await
            .expect("the server answers");
        read(response).await
    }
}

/// A client presenting one credential on every request it makes.
///
/// # Panics
///
/// Panics when the credential cannot be a header value, which no credential a
/// server accepts is.
#[must_use]
pub fn presenting(credential: &str) -> reqwest::Client {
    let mut headers = reqwest::header::HeaderMap::new();
    headers.insert(
        reqwest::header::AUTHORIZATION,
        reqwest::header::HeaderValue::from_str(&format!("Bearer {credential}"))
            .expect("a credential is a header value"),
    );
    reqwest::Client::builder()
        .default_headers(headers)
        .build()
        .expect("a client is built")
}

/// The status, the media type and the body of one answer.
async fn read(response: reqwest::Response) -> (reqwest::StatusCode, serde_json::Value) {
    let status = response.status();
    let media = response
        .headers()
        .get(reqwest::header::CONTENT_TYPE)
        .and_then(|value| value.to_str().ok())
        .unwrap_or_default()
        .to_owned();
    let text = response.text().await.expect("an answer has a body");
    assert!(
        media.starts_with(printobserver_server::MEDIA_TYPE),
        "the server answered under {media:?} rather than JSON: {text}"
    );
    let value = serde_json::from_str(&text)
        .unwrap_or_else(|error| panic!("the answer is not JSON ({error}): {text}"));
    (status, value)
}

/// Start one server over the ports a journey supplies, with whatever it
/// stands between the durable stores and the server.
async fn start(
    config: &ServerConfig,
    printer: &Arc<RecordingPrinter>,
    agent: &Arc<StandInAgent>,
    between: impl FnOnce(Stores) -> Stores,
) -> (Running, Stores) {
    let stores = between(Stores::of(Arc::new(
        SqliteStore::open(&config.state_dir).expect("the store opens on the state directory"),
    )));
    let vision = Arc::new(
        ObicoVision::new(ObicoVisionConfig::default())
            .expect("the adapter is built")
            .with_api(config.obico_api.clone()),
    );
    let server = Server::start_with(
        config.clone(),
        Ports {
            printer: Arc::clone(printer) as Arc<dyn printobserver_printer_api::PrinterPort>,
            stores: stores.clone(),
            vision,
            agent: Arc::clone(agent) as Arc<dyn printobserver_supervisor_api::SupervisorPort>,
        },
    )
    .await
    .expect("the server starts");
    (server, stores)
}

/// A body one spool command takes, carrying a reason, the operator as its
/// actor, and whatever else the command needs: the registration of a spool of
/// PLA, a load onto tool 0, an adjustment to a figure.
#[must_use]
pub fn spool_body(kind: printobserver_core::ActionKind) -> serde_json::Value {
    use printobserver_core::ActionKind;
    let mut body = serde_json::json!({
        "reason": "a journey is asking the ledger",
        "actor": "operator",
    });
    let object = body.as_object_mut().expect("the body is an object");
    match kind {
        ActionKind::RegisterSpool => {
            object.insert("name".to_owned(), serde_json::json!("a journey's spool"));
            object.insert("material".to_owned(), serde_json::json!("PLA"));
            object.insert("initial_g".to_owned(), serde_json::json!(1000.0));
        }
        ActionKind::LoadSpool => {
            object.insert("tool".to_owned(), serde_json::json!(0));
        }
        ActionKind::AdjustSpool => {
            object.insert("remaining_g".to_owned(), serde_json::json!(500.0));
        }
        _ => {}
    }
    body
}

/// The body a manifest write takes: the manifest, and why it is being written.
///
/// A manifest narrows what any actor may ask for, so replacing one carries a
/// reason exactly as every other change does.
#[must_use]
pub fn manifest_write(manifest: &serde_json::Value) -> serde_json::Value {
    serde_json::json!({
        "reason": "a journey is writing the bounds this print runs under",
        "manifest": manifest,
    })
}

/// One `Obico` failure alert, as the producer posts it.
///
/// The committed sample is what the ingress journeys post; this is what a
/// journey that needs a *second* alert about the same print, or an alert naming
/// an image host it controls, builds from it.
#[must_use]
pub fn failure_alert(obico_print_id: i64, image_url: &str) -> serde_json::Value {
    let mut sample: serde_json::Value =
        serde_json::from_str(committed_sample()).expect("the committed sample is JSON");
    sample["print"]["id"] = serde_json::json!(obico_print_id);
    sample["img_url"] = serde_json::json!(image_url);
    sample
}

/// The committed `Obico` failure alert sample, read from the adapter's own file.
#[must_use]
pub fn committed_sample() -> &'static str {
    include_str!("../../../printobserver-obico/samples/obico/failure-alert.json")
}

/// Every file under a directory whose bytes carry `needle`, for a journey about
/// what is written nowhere.
#[must_use]
pub fn files_carrying(root: &Path, needle: &str) -> Vec<PathBuf> {
    let mut found = Vec::new();
    let Ok(entries) = std::fs::read_dir(root) else {
        return found;
    };
    for entry in entries.flatten() {
        let path = entry.path();
        if path.is_dir() {
            found.extend(files_carrying(&path, needle));
        } else if std::fs::read(&path).is_ok_and(|bytes| {
            bytes
                .windows(needle.len())
                .any(|window| window == needle.as_bytes())
        }) {
            found.push(path);
        }
    }
    found
}