printobserver-server 0.3.0

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
//! The composition root: the one place an implementation crate is named.
//!
//! Everything below this file is written against the three ports and the
//! supervision domain's store traits. This is where one implementation is
//! chosen for each — `OctoPrint` behind the printer port, `Obico` behind the
//! vision port, `OneHarness` behind the supervisor port, and `SQLite` behind
//! the store traits — and `just check-repo` refuses any other crate that names
//! one. The store is one implementation held once per aggregate: [`Stores::of`]
//! coerces the one `SQLite` store to each of the five trait objects, and every
//! consumer below is handed the handle for the aggregate it names and no
//! other.
//!
//! [`Server::start`] is that root. [`Server::start_with`] takes ports a caller
//! composed, which is how the tiers that stand in for a machine drive the real
//! surface without one; the two share every line after the ports exist, so what
//! a tier drives is the server this file starts.

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

use axum::Router;
use axum::routing::post;
use printobserver_core::store::Stores;
use printobserver_core::{Clock as _, CoreConfig, Supervisor, SystemClock};
use printobserver_obico::{ObicoVision, ObicoVisionConfig};
use printobserver_octoprint::OctoPrintPrinter;
use printobserver_oneharness::{
    AssessmentSchema, HarnessSignIn, OneharnessSupervisor, SupervisorConfig,
};
use printobserver_printer_api::{PrinterError, PrinterPort};
use printobserver_store_sqlite::SqliteStore;
use printobserver_supervisor_api::SupervisorPort;
use tokio::net::TcpListener;
use tokio::sync::{oneshot, watch};
use tokio::task::JoinHandle;

use crate::api::{ApiState, router};
use crate::config::{ApiCredential, ConfigError, ConfigField, ServerConfig};
use crate::ingress::{IngressState, receive};
use crate::operations::INGRESS_PATH;
use crate::reconcile::{ReconcileStores, Reconciliation, overdue, reconcile};

/// The program a supervision turn runs to read its print's context.
pub const CONTEXT_PROGRAM: &str = "printobserver";

/// The file this server writes the address it took and the credential in force
/// into, under the state directory, for the clients that run beside it.
pub const CLIENT_CONFIG_FILE: &str = "client.toml";

/// The file, under the state directory, holding the API credential this server
/// generated for itself — read when `api.credential` is not configured, and
/// written only when it is not there.
pub const API_CREDENTIAL_FILE: &str = "api-credential";

/// The mode both files carrying the credential are created with.
///
/// Unix alone has one. A file Windows creates carries the access its directory
/// grants rather than a mode, so there the state directory is what keeps both
/// files to the service's own account.
#[cfg(unix)]
const PRIVATE: u32 = 0o600;

/// The command a supervision turn runs to read its print's context.
///
/// This program's own context read, against the print the turn is about and
/// the configuration file naming the address this server took — which is the
/// bound address rather than the configured one, because a configuration may
/// ask for any free port and a turn has to reach the one that was taken — and
/// the credential in force.
/// `printobserver-oneharness` substitutes the print for the placeholder.
///
/// Both travel in a file rather than on the command line because no client
/// command of that program takes either: where a server is and what
/// authenticates to it are configuration, and a command line that could carry
/// them is a command line that could be pointed anywhere — and one that lands a
/// credential in a process table.
#[must_use]
pub fn context_command(client_config: &Path) -> String {
    format!(
        "{CONTEXT_PROGRAM} context --config {} --print-id {{print_id}}",
        client_config.display()
    )
}

/// Write the configuration the clients beside this server read it by.
///
/// One `[client]` table naming the address that was actually bound and the
/// credential in force, so a supervision turn — and an operator on this host
/// who can read the state directory — reaches and authenticates to this server
/// without being told either or copying a secret by hand. It is the one file
/// this program writes the credential into beside the one it generated, so it
/// is private to the service's own user from the moment it exists: created, or
/// narrowed when an earlier start left it, before a byte is written.
fn write_client_config(
    directory: &Path,
    address: SocketAddr,
    credential: &ApiCredential,
) -> Result<PathBuf, StartError> {
    use std::io::Write as _;

    let path = directory.join(CLIENT_CONFIG_FILE);
    let failing = |error: std::io::Error| StartError::State {
        detail: format!("{} could not be written: {error}", path.display()),
    };
    let mut options = std::fs::OpenOptions::new();
    options.write(true).create(true).truncate(true);
    #[cfg(unix)]
    std::os::unix::fs::OpenOptionsExt::mode(&mut options, PRIVATE);
    let mut file = options.open(&path).map_err(failing)?;
    #[cfg(unix)]
    file.set_permissions(std::os::unix::fs::PermissionsExt::from_mode(PRIVATE))
        .map_err(failing)?;
    file.write_all(
        format!(
            "[client]\nserver = \"http://{address}\"\ncredential = \"{}\"\n",
            toml_basic_string(credential.written())
        )
        .as_bytes(),
    )
    .map_err(failing)?;
    Ok(path)
}

/// Text as the body of a TOML basic string.
///
/// A credential is printable ASCII by construction, so the quote and the
/// backslash are the only two characters that need an escape.
fn toml_basic_string(text: &str) -> String {
    text.replace('\\', "\\\\").replace('"', "\\\"")
}

/// The API credential this start serves under.
///
/// The configured one when `api.credential` names one, in which case the state
/// directory's file is neither read nor written. Otherwise the file: created
/// with a fresh credential when it is not there — exclusively, so that nothing
/// already at that path is ever replaced — and read as it is when it is.
///
/// # Errors
///
/// Returns [`StartError::Credential`] naming the file, and never what it holds,
/// when it cannot be created or read or holds nothing a header could present.
fn credential_in_force(config: &ServerConfig) -> Result<ApiCredential, StartError> {
    use std::io::Write as _;

    if let Some(configured) = &config.api_credential {
        return Ok(configured.clone());
    }
    let path = config.state_dir.join(API_CREDENTIAL_FILE);
    let refusing = |detail: String| StartError::Credential {
        path: path.clone(),
        detail,
    };
    let mut options = std::fs::OpenOptions::new();
    options.write(true).create_new(true);
    #[cfg(unix)]
    std::os::unix::fs::OpenOptionsExt::mode(&mut options, PRIVATE);
    match options.open(&path) {
        Ok(mut file) => {
            let generated = ApiCredential::generate().map_err(|error| {
                refusing(format!(
                    "no credential could be generated for it, because the operating system's \
                     random source refused: {error}"
                ))
            });
            let written = generated.and_then(|credential| {
                file.write_all(credential.written().as_bytes())
                    .and_then(|()| file.sync_all())
                    .map(|()| credential)
                    .map_err(|error| refusing(format!("it could not be written: {error}")))
            });
            if written.is_err() {
                // The file is this start's own and holds nothing usable, so it
                // is taken back rather than left for the next start to refuse.
                let _ = std::fs::remove_file(&path);
            }
            written
        }
        Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
            // llmlint: ignore[least_privilege_grants] The contract reuses an existing credential file's contents unchanged and never rewrites a file this start did not write, so the server does not change a hand-provisioned file's mode. The installed path keeps the file private by its directory: the installer creates the state directory at mode 0700, owned by the service user, and a file this server generates is created 0600. A mode check on hand-provisioned files is recorded as a follow-up.
            let held = std::fs::read(&path)
                .map_err(|error| refusing(format!("it cannot be read: {error}")))?;
            let text = core::str::from_utf8(&held).ok().map(without_terminator);
            text.ok_or("it is not text")
                .and_then(ApiCredential::new)
                .map_err(|why| {
                    refusing(format!(
                        "{why}. This server does not replace a credential it did not write \
                         just now: correct the file, or remove it to have a new one generated"
                    ))
                })
        }
        Err(error) => Err(refusing(format!("it cannot be created: {error}"))),
    }
}

/// A credential file's text with the one line terminator a person's editor or
/// shell ends it with set aside.
///
/// Exactly one, `\n` or `\r\n`: that terminator is not part of the credential,
/// and anything else in the text — a second one included — is left for the
/// character rule to refuse.
fn without_terminator(text: &str) -> &str {
    text.strip_suffix("\r\n")
        .or_else(|| text.strip_suffix('\n'))
        .unwrap_or(text)
}

/// The file name the agent's prompt template is materialized under.
pub const PROMPT_FILE: &str = "turn-prompt.md";

/// The file name the assessment schema is materialized under.
pub const SCHEMA_FILE: &str = "assessment-schema.json";

/// The prompt template this program carries and materializes.
///
/// The adapter's own committed asset rather than a copy of it, so what an
/// installed program fills a turn with and what `just check-repo` reads are one
/// file.
pub const TURN_PROMPT: &str = printobserver_oneharness::DEFAULT_TURN_PROMPT;

/// The four implementations one running server was composed from.
///
/// A tier that stands in for a machine hands these in; [`Server::start`] builds
/// them from the configuration.
pub struct Ports {
    /// The printer.
    pub printer: Arc<dyn PrinterPort>,
    /// Durable state, one handle per aggregate onto one store.
    pub stores: Stores,
    /// External observations, and the snapshot fetch.
    pub vision: Arc<ObicoVision>,
    /// The supervising agent's harness.
    pub agent: Arc<dyn SupervisorPort>,
}

impl core::fmt::Debug for Ports {
    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        formatter.debug_struct("Ports").finish_non_exhaustive()
    }
}

/// Why this server did not start.
#[derive(Debug)]
pub enum StartError {
    /// The configuration will not do, naming the field that will not.
    Configuration(ConfigError),
    /// The state directory could not be prepared.
    State {
        /// What went wrong.
        detail: String,
    },
    /// The API credential file in the state directory cannot be used.
    Credential {
        /// The file.
        path: PathBuf,
        /// Why it cannot be used, in words that never quote what it holds.
        detail: String,
    },
    /// The address could not be listened on.
    Listen {
        /// The address that was asked for.
        address: SocketAddr,
        /// What went wrong.
        detail: String,
    },
    /// The store could not be opened.
    Store {
        /// What the store said.
        detail: String,
    },
    /// The supervising agent's harness could not be reached at all.
    Supervisor {
        /// What the harness said.
        detail: String,
    },
    /// Reconciling what the store held failed.
    Reconciliation {
        /// What went wrong.
        detail: String,
    },
}

impl StartError {
    /// The configuration field this refusal is about, when it is about one.
    #[must_use]
    pub const fn field(&self) -> Option<ConfigField> {
        match self {
            Self::Configuration(error) => error.field(),
            _ => None,
        }
    }
}

impl core::fmt::Display for StartError {
    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::Configuration(error) => write!(formatter, "{error}"),
            Self::State { detail } => {
                write!(
                    formatter,
                    "the state directory could not be prepared: {detail}"
                )
            }
            Self::Credential { path, detail } => write!(
                formatter,
                "the API credential file {} cannot be used: {detail}",
                path.display()
            ),
            Self::Listen { address, detail } => {
                write!(formatter, "{address} could not be listened on: {detail}")
            }
            Self::Store { detail } => write!(formatter, "the store could not be opened: {detail}"),
            Self::Supervisor { detail } => write!(
                formatter,
                "the supervising agent's harness could not be reached: {detail}"
            ),
            Self::Reconciliation { detail } => write!(
                formatter,
                "what the store held could not be reconciled: {detail}"
            ),
        }
    }
}

impl core::error::Error for StartError {}

impl From<ConfigError> for StartError {
    fn from(error: ConfigError) -> Self {
        Self::Configuration(error)
    }
}

/// The composition root.
#[derive(Debug)]
pub struct Server;

impl Server {
    /// Read one configuration file, compose the four implementations, and serve.
    ///
    /// # Errors
    ///
    /// Returns [`StartError::Configuration`] naming the field that will not do
    /// — including the two only the machine can rule on, an `OctoPrint` address
    /// nothing answers at and a key that instance refuses — and the other
    /// variants for a host that will not let this server come up.
    pub async fn start(config_path: impl AsRef<Path>) -> Result<Running, StartError> {
        let config = ServerConfig::load(config_path)?;
        let stores = Stores::of(Arc::new(SqliteStore::open(&config.state_dir).map_err(
            |error| StartError::Store {
                detail: error.to_string(),
            },
        )?));
        let printer = Arc::new(OctoPrintPrinter::new(config.octoprint.clone()));
        probe(printer.as_ref()).await?;
        let vision = Arc::new(
            ObicoVision::new(ObicoVisionConfig::default()).map_err(|error| StartError::State {
                detail: error.to_string(),
            })?,
        );
        let agent = Arc::new(agent_for(&config)?);
        Self::start_with(
            config,
            Ports {
                printer,
                stores,
                vision,
                agent,
            },
        )
        .await
    }

    /// Serve over ports a caller composed.
    ///
    /// # Errors
    ///
    /// The same as [`Server::start`], less the refusals that belong to building
    /// the implementations.
    pub async fn start_with(config: ServerConfig, ports: Ports) -> Result<Running, StartError> {
        // The credential is settled before anything listens, so there is no
        // moment at which this server answers a request it has nothing to
        // check against.
        let credential = credential_in_force(&config)?;
        // The listener is taken next, because the command a supervision turn
        // runs to read its context names the address this server is answering
        // on — and a configuration may ask for any free port.
        let listener =
            TcpListener::bind(config.listen)
                .await
                .map_err(|error| StartError::Listen {
                    address: config.listen,
                    detail: error.to_string(),
                })?;
        let address = listener.local_addr().map_err(|error| StartError::Listen {
            address: config.listen,
            detail: error.to_string(),
        })?;
        let client_config = write_client_config(&config.state_dir, address, &credential)?;
        let clock = Arc::new(SystemClock);
        let due = overdue(&ports.stores.actions, clock.now())
            .await
            .map_err(|error| StartError::Reconciliation {
                detail: error.to_string(),
            })?;
        let supervisor = Supervisor::new(
            CoreConfig::new(config.safety.clone(), context_command(&client_config)),
            Arc::clone(&ports.printer),
            ports.stores.clone(),
            Arc::clone(&ports.vision) as Arc<dyn printobserver_vision_api::VisionPort>,
            Arc::clone(&ports.agent),
            clock,
        );
        let reconciliation = reconcile(
            &supervisor,
            &ReconcileStores {
                prints: Arc::clone(&ports.stores.prints),
                sessions: Arc::clone(&ports.stores.sessions),
                events: Arc::clone(&ports.stores.events),
            },
            due,
        )
        .await
        .map_err(|error| StartError::Reconciliation {
            detail: error.to_string(),
        })?;

        let ingress = IngressState::start(
            Arc::clone(&supervisor),
            Arc::clone(&ports.stores.events),
            Arc::clone(&ports.vision),
            config.ingress_shared_secret.clone(),
            config.ingress_answer_bound,
        );
        let completions = ingress.completions();
        let application = router(ApiState {
            supervisor: Arc::clone(&supervisor),
            prints: Arc::clone(&ports.stores.prints),
            events: Arc::clone(&ports.stores.events),
            images: Arc::clone(&ports.stores.images),
            sessions: Arc::clone(&ports.stores.sessions),
            credential: Arc::new(credential),
        })
        .merge(
            Router::new()
                .route(INGRESS_PATH, post(receive))
                .with_state(ingress),
        );

        let (stop, stopped) = oneshot::channel::<()>();
        let serving = tokio::spawn(async move {
            let _ = axum::serve(listener, application)
                .with_graceful_shutdown(async move {
                    let _ = stopped.await;
                })
                .await;
        });
        Ok(Running {
            address,
            config,
            supervisor,
            stores: ports.stores,
            reconciliation,
            completions,
            stop: Some(stop),
            serving,
        })
    }
}

/// Ask the machine whether the address and the key are the ones it answers to.
///
/// Only the two answers that are *about the configuration* refuse a start. A
/// printer that is off, in an error state, or answering something this adapter
/// cannot read is a machine having a bad day rather than a file with the wrong
/// value in it, and a supervisor that would not come up for one of those could
/// not be used to find out why.
async fn probe(printer: &dyn PrinterPort) -> Result<(), StartError> {
    match printer.snapshot().await {
        Err(PrinterError::Unreachable { detail }) => {
            Err(StartError::Configuration(ConfigError::about(
                ConfigField::OctoprintUrl,
                format!("nothing answers there: {detail}"),
            )))
        }
        Err(PrinterError::Unauthorized { detail }) => {
            Err(StartError::Configuration(ConfigError::about(
                ConfigField::OctoprintApiKey,
                format!("the OctoPrint instance refused it: {detail}"),
            )))
        }
        _ => Ok(()),
    }
}

/// Write one of the agent's committed assets into the state directory.
///
/// The port reads its template and its schema from paths, so that editing one
/// on a running host is a restart rather than a rebuild. An installed program
/// has no checkout to read them out of, so the bytes it carries are written
/// here — and an operator who configured a template of their own is pointed at
/// theirs instead.
fn materialize(
    directory: &Path,
    name: &str,
    contents: &str,
) -> Result<std::path::PathBuf, StartError> {
    let path = directory.join(name);
    std::fs::write(&path, contents).map_err(|error| StartError::State {
        detail: format!("{} could not be written: {error}", path.display()),
    })?;
    Ok(path)
}

/// The directory the harness runs in: the one holding the configured skill.
///
/// An installed skill is a directory — its `SKILL.md` and the `reference/`
/// documents that file links to by relative paths — so the agent stands where
/// those links resolve. A skill named by a bare file name sits in this
/// process's own working directory.
fn beside_the_skill(skill_path: &Path) -> std::path::PathBuf {
    match skill_path.parent() {
        Some(directory) if !directory.as_os_str().is_empty() => directory.to_path_buf(),
        _ => std::path::PathBuf::from("."),
    }
}

/// The supervising agent's harness, over the configured skill and the assets
/// this program carries.
fn agent_for(config: &ServerConfig) -> Result<OneharnessSupervisor, StartError> {
    OneharnessSupervisor::open(agent_config(config)?).map_err(|error| StartError::Supervisor {
        detail: error.to_string(),
    })
}

/// The supervising agent's configuration, as [`Server::start`] composes it.
///
/// The template and the assessment schema are written into the assets
/// directory; the skill is the installed one `supervisor.skill_path` names, and
/// every turn runs in the directory holding it — where an installed skill's
/// `reference/` documents sit, so the links the skill carries resolve from
/// where the agent stands. The harness is the one `supervisor.harness` names,
/// found by name, and a harness this program can sign in is pointed at the
/// sign-in kept under the state directory.
///
/// # Errors
///
/// Returns [`StartError::State`] when the assets or the sign-in directory
/// cannot be written, and [`StartError::Supervisor`] when the schema it wrote
/// constrains nothing.
pub fn agent_config(config: &ServerConfig) -> Result<SupervisorConfig, StartError> {
    let assets = config.assets_dir();
    std::fs::create_dir_all(&assets).map_err(|error| StartError::State {
        detail: format!("{} could not be created: {error}", assets.display()),
    })?;
    let prompt_template_path = match &config.prompt_template_path {
        Some(path) => path.clone(),
        None => materialize(&assets, PROMPT_FILE, TURN_PROMPT)?,
    };
    let schema_path = materialize(
        &assets,
        SCHEMA_FILE,
        &printobserver_types::serde_json::to_string_pretty(
            &printobserver_types::contract::schema_of::<
                printobserver_supervisor_api::AgentAssessment,
            >(),
        )
        .map_err(|error| StartError::State {
            detail: error.to_string(),
        })?,
    )?;
    let assessment_schema =
        AssessmentSchema::at(&schema_path).map_err(|error| StartError::Supervisor {
            detail: error.to_string(),
        })?;
    // A harness this program can sign in keeps that sign-in under the state
    // directory — the one place the service's unit lets it write — and every
    // turn is pointed at the directory `printobserver sign-in` wrote it to. A
    // harness outside the table is handed nothing extra.
    let harness_env = match HarnessSignIn::of(&config.harness) {
        Some(sign_in) => {
            let directory =
                sign_in
                    .prepare(&config.state_dir)
                    .map_err(|error| StartError::State {
                        detail: format!(
                            "{} could not be created: {error}",
                            sign_in.directory(&config.state_dir).display()
                        ),
                    })?;
            vec![
                sign_in
                    .assignment(&directory)
                    .map_err(|error| StartError::Supervisor {
                        detail: error.to_string(),
                    })?,
            ]
        }
        None => Vec::new(),
    };
    Ok(SupervisorConfig {
        state_dir: config.state_dir.clone(),
        skill_path: config.skill_path.clone(),
        prompt_template_path,
        assessment_schema,
        harness: config.harness.clone(),
        model: config.model.clone(),
        // The skill's own directory rather than the state or assets directory,
        // so that the skill's relative links to the reference documents beside
        // it resolve from where the agent is standing as well as from the skill.
        working_dir: beside_the_skill(&config.skill_path),
        turn_timeout: printobserver_oneharness::TurnTimeout::DEFAULT,
        harness_bin: None,
        harness_env,
    })
}

/// One server, serving.
///
/// Dropping this stops it, and so does [`Running::stop`]; nothing here outlives
/// the handle a caller holds.
pub struct Running {
    /// Where it is answering.
    address: SocketAddr,
    /// What it was configured with.
    config: ServerConfig,
    /// The supervision core.
    supervisor: Arc<Supervisor>,
    /// Durable state, one handle per aggregate.
    stores: Stores,
    /// What this start adopted.
    reconciliation: Reconciliation,
    /// How many posts the ingress worker has finished handling.
    completions: watch::Receiver<u64>,
    /// The graceful-shutdown signal, taken when it is sent.
    stop: Option<oneshot::Sender<()>>,
    /// The task serving requests.
    serving: JoinHandle<()>,
}

impl core::fmt::Debug for Running {
    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        formatter
            .debug_struct("Running")
            .field("address", &self.address)
            .field("reconciliation", &self.reconciliation)
            .finish_non_exhaustive()
    }
}

impl Running {
    /// Where this server is answering.
    #[must_use]
    pub const fn address(&self) -> SocketAddr {
        self.address
    }

    /// The base URL of its versioned surface.
    #[must_use]
    pub fn base_url(&self) -> String {
        format!(
            "http://{}{}",
            self.address,
            crate::operations::VERSION_PREFIX
        )
    }

    /// The URL its ingress endpoint answers on.
    #[must_use]
    pub fn ingress_url(&self) -> String {
        format!("http://{}{INGRESS_PATH}", self.address)
    }

    /// What it was configured with.
    #[must_use]
    pub const fn config(&self) -> &ServerConfig {
        &self.config
    }

    /// What this start adopted from the store.
    #[must_use]
    pub const fn reconciliation(&self) -> &Reconciliation {
        &self.reconciliation
    }

    /// The supervision core it is serving over.
    #[must_use]
    pub const fn supervisor(&self) -> &Arc<Supervisor> {
        &self.supervisor
    }

    /// Durable state, as it is serving over it.
    #[must_use]
    pub const fn stores(&self) -> &Stores {
        &self.stores
    }

    /// How many posts the ingress worker has finished handling, watchable while
    /// it works.
    #[must_use]
    pub fn completions(&self) -> watch::Receiver<u64> {
        self.completions.clone()
    }

    /// Stop serving, and wait for the last request to finish.
    pub async fn stop(mut self) {
        if let Some(stop) = self.stop.take() {
            let _ = stop.send(());
        }
        let _ = (&mut self.serving).await;
    }

    /// Serve until the operating system asks this process to stop.
    ///
    /// This is what the `server` subcommand runs. It answers however this
    /// platform asks a process to stop — see [`stop_requested`] — and every one
    /// of those ways enters the same shutdown: [`Running::stop`].
    ///
    /// # Errors
    ///
    /// Returns [`StartError::State`] when the stop handlers cannot be
    /// installed, which is a process that could not be stopped cleanly.
    pub async fn serve_until_signalled(self) -> Result<(), StartError> {
        stop_requested().await?;
        self.stop().await;
        Ok(())
    }
}

/// A stop handler that could not be installed, naming which.
fn unhandled(what: &str, error: &std::io::Error) -> StartError {
    StartError::State {
        detail: format!("{what} cannot be handled: {error}"),
    }
}

/// Wait until the operating system asks this process to stop.
///
/// On Unix that is the signal a service manager stops a unit with, or the
/// interrupt from the terminal that started it.
#[cfg(unix)]
async fn stop_requested() -> Result<(), StartError> {
    use tokio::signal::unix::{SignalKind, signal};

    let mut terminate = signal(SignalKind::terminate())
        .map_err(|error| unhandled("the termination signal", &error))?;
    let mut interrupt = signal(SignalKind::interrupt())
        .map_err(|error| unhandled("the interrupt signal", &error))?;
    tokio::select! {
        _ = terminate.recv() => {}
        _ = interrupt.recv() => {}
    }
    Ok(())
}

/// Wait until the operating system asks this process to stop.
///
/// Windows has no signals: a console process is stopped by a console control
/// event. `CTRL_C` and `CTRL_BREAK` are the terminal's interrupt — the second is
/// the one another process can send a process group started apart from its own
/// — and `CTRL_CLOSE` and `CTRL_SHUTDOWN` are the console closing and the
/// machine shutting down.
#[cfg(windows)]
async fn stop_requested() -> Result<(), StartError> {
    use tokio::signal::windows::{ctrl_break, ctrl_c, ctrl_close, ctrl_shutdown};

    let mut interrupt = ctrl_c().map_err(|error| unhandled("the CTRL_C event", &error))?;
    let mut breaking = ctrl_break().map_err(|error| unhandled("the CTRL_BREAK event", &error))?;
    let mut closing = ctrl_close().map_err(|error| unhandled("the CTRL_CLOSE event", &error))?;
    let mut shutting_down =
        ctrl_shutdown().map_err(|error| unhandled("the CTRL_SHUTDOWN event", &error))?;
    tokio::select! {
        _ = interrupt.recv() => {}
        _ = breaking.recv() => {}
        _ = closing.recv() => {}
        _ = shutting_down.recv() => {}
    }
    Ok(())
}

impl Drop for Running {
    fn drop(&mut self) {
        if let Some(stop) = self.stop.take() {
            let _ = stop.send(());
        }
        self.serving.abort();
    }
}