haematite-cli 0.21.0

The haematite command: serve a store, its door and Studio, answer MCP, query with jq, and host the store's assistant seat
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
//! `haematite call`: ask a running service anything its protocol offers, from the
//! command line; `haematite write` is in [`write`] and `haematite query` in [`query`].
//!
//! The client says hello first and takes the service's `max_frame` as the
//! bound on what it sends and what it reads. Params go out as the text given
//! and a result comes back as the bytes the service sent: no number is parsed
//! into a float and written again. Four outcomes are told apart by exit code:
//! answered (0), could not ask, so nothing was sent (1), refused by the service
//! (2), and outcome not known to the caller (3).

use crate::serve::protocol::{HelloAgreement, PROTOCOL, RECEIPT_CAPABILITY};
use crate::serve::receipt_fragments::{Assembler, VerifiedReceipt, minimum_cap};
use std::io::{self, Read, Write};
use std::num::{NonZeroU32, NonZeroU64};
use std::os::unix::net::UnixStream;
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use std::sync::{Arc, mpsc};
use std::time::Duration;

use serde::{Deserialize, Deserializer, Serialize};
use serde_json::value::RawValue;

use crate::serve::{cli::Config, frame};

pub mod query;
pub mod write;

const USAGE: &str = "\
usage: haematite call (--socket <path> | --config <serve.json>) [--timeout-ms N] <method> [<params> | -]
<params> is one JSON value; - reads it from standard input; absent, the operation has no params.
--timeout-ms bounds connecting, writing and reading; the default is 30000.
Exit 0: answered, the result on standard output. Exit 1: could not ask; nothing was sent.
Exit 2: refused by the service, its code and message on standard error. Exit 3: the outcome
is not known to the caller; the service may have acted.";

const DEFAULT_TIMEOUT_MS: NonZeroU64 = NonZeroU64::MIN.saturating_add(29_999);
/// Hello's answer is read before the service has said its frame limit.
const HELLO_BOUND: NonZeroU32 = NonZeroU32::MIN.saturating_add(65_535);
const ID: &str = "haem-call";

/// Codes which leave the mutation's outcome uncertain.
///
/// Unrecognised codes also retain uncertainty unless the shared refusal table
/// proves otherwise.
pub const MAY_HAVE_APPLIED: &[&str] = &[
    // The commit failed after the branch reference moved: storage/mutations.rs
    // 196 and 476 (a fork); a discard, storage/discards.rs 226, 296, 332, 418
    // and 424; a receipt's confirmation, storage/mutations.rs 71.
    "durability_unknown",
    // The change is durable and the catalogue could not show it:
    // storage/catalogue.rs 37, by publish_record after every commit.
    "committed_unpublished",
    // The reference vanished after its commit: storage.rs 275, the same
    // publish_record; it is also raised before commits, which cannot be told
    // apart from here.
    "reference_missing",
    // A refused discard commit whose intent could not be withdrawn:
    // storage/discards.rs 253.
    "discard_abort_failed",
    // The catalogue could not hide a branch whose discard intent was
    // installed: storage/catalogue.rs 49, called from storage/discards.rs 221
    // and after the commit at 416, 425 and 429.
    "catalogue_unavailable",
    // Raised by Failure::storage everywhere, including after the change, as
    // when the receipt cannot be serialized (serve/service.rs 123-124).
    "storage_unavailable",
    // The answer did not fit after the change was made: serve/service.rs 108
    // and serve/transport.rs 177, which says to reconcile by request id.
    "response_limit",
];

/// The service's shared proof that a refusal applied no mutation.
pub use crate::serve::protocol::NOT_APPLIED_REFUSALS as KNOWN_REFUSALS;

/// Why an exchange gave neither an answer nor a refusal.
#[derive(Debug)]
pub enum Ended {
    /// The command line was not one the command takes; the usage text follows.
    Usage(String),
    /// Nothing the service could act on was sent.
    NotAsked(String),
    /// The request was sent, or may have been; whether the service acted on
    /// it is not known.
    Unknown(String),
    /// The service sent a complete, verified receipt, and whether the change
    /// was applied is still not known: the receipt carried no refusal, or its
    /// code is one that may have applied or that this client does not know.
    /// The receipt is kept as the exact bytes sent, to reconcile by.
    Received {
        why: String,
        receipt: Arc<VerifiedReceipt>,
    },
}

impl Ended {
    /// The cause, without the words for which kind of end it was.
    #[must_use]
    pub fn why(&self) -> &str {
        match self {
            Self::Usage(why)
            | Self::NotAsked(why)
            | Self::Unknown(why)
            | Self::Received { why, .. } => why,
        }
    }
}

impl std::fmt::Display for Ended {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let kind = match self {
            Self::Usage(_) => "usage",
            Self::NotAsked(_) => "not asked",
            Self::Unknown(_) => "outcome unknown",
            Self::Received { .. } => "complete receipt received",
        };
        write!(formatter, "{kind}: {}", self.why())
    }
}

impl std::error::Error for Ended {}

/// What the service said to one request.
#[derive(Debug)]
pub enum Reply {
    /// The bytes the service sent for `result`.
    Answered(Box<RawValue>),
    Refused(Refusal),
}

/// A refusal by name, as the service sent it.
#[derive(Debug, Deserialize)]
pub struct Refusal {
    pub code: String,
    pub message: String,
    #[serde(default)]
    pub path: Option<String>,
    #[serde(skip)]
    pub verified: Option<Arc<VerifiedReceipt>>,
}

/// One connection to a running service, past its hello.
pub struct Client {
    stream: UnixStream,
    hello: Box<RawValue>,
    max_frame: NonZeroU32,
    max_page: NonZeroU32,
}

#[derive(Deserialize)]
struct Limits {
    protocol: String,
    capabilities: Vec<String>,
    max_frame: NonZeroU32,
    max_page: NonZeroU32,
}

impl Client {
    /// Connect to `socket` and say hello, each step bounded by `timeout`.
    ///
    /// # Errors
    ///
    /// `Ended::NotAsked` naming the cause: hello changes nothing, so any
    /// failure up to its answer leaves nothing asked.
    pub fn connect(socket: &Path, timeout: Duration) -> Result<Self, Ended> {
        let mut stream = connect(socket, timeout)?;
        let unset =
            |error: io::Error| Ended::NotAsked(format!("the timeout could not be set: {error}"));
        stream.set_read_timeout(Some(timeout)).map_err(unset)?;
        stream.set_write_timeout(Some(timeout)).map_err(unset)?;
        let agreement = serde_json::value::to_raw_value(&HelloAgreement::client())
            .map_err(|error| Ended::NotAsked(format!("receipt_hello_encode_failed: {error}")))?;
        let hello = match exchange(&mut stream, HELLO_BOUND, "hello", Some(&agreement)) {
            Ok(Reply::Answered(hello)) => hello,
            Ok(Reply::Refused(refusal)) => {
                return Err(Ended::NotAsked(format!(
                    "the service refused hello: {}: {}",
                    refusal.code, refusal.message
                )));
            }
            Err(Ended::Received { why, receipt }) => {
                return Err(Ended::Received {
                    why: format!("hello failed: {why}"),
                    receipt,
                });
            }
            Err(Ended::Unknown(why) | Ended::NotAsked(why) | Ended::Usage(why)) => {
                return Err(Ended::NotAsked(format!("hello failed: {why}")));
            }
        };
        let limits: Limits = serde_json::from_str(hello.get()).map_err(|error| {
            Ended::NotAsked(format!(
                "the service's hello did not give its limits: {error}"
            ))
        })?;
        if limits.protocol != PROTOCOL {
            return Err(Ended::NotAsked(format!(
                "receipt_protocol_mismatch: expected {PROTOCOL}, received {}",
                limits.protocol
            )));
        }
        if !limits
            .capabilities
            .iter()
            .any(|capability| capability == RECEIPT_CAPABILITY)
        {
            return Err(Ended::NotAsked(format!(
                "typed_receipt_capability_missing: required {RECEIPT_CAPABILITY}"
            )));
        }
        let minimum = minimum_cap().map_err(|error| Ended::NotAsked(error.to_string()))?;
        if u64::from(limits.max_frame.get())
            < u64::try_from(minimum).map_err(|error| Ended::NotAsked(error.to_string()))?
        {
            return Err(Ended::NotAsked(format!(
                "receipt_frame_too_small: offered {}, minimum {minimum}",
                limits.max_frame
            )));
        }
        Ok(Self {
            stream,
            hello,
            max_frame: limits.max_frame,
            max_page: limits.max_page,
        })
    }

    /// The bytes the service sent for hello's `result`.
    #[must_use]
    pub fn hello(&self) -> &RawValue {
        &self.hello
    }

    /// The largest frame the service reads or sends.
    #[must_use]
    pub const fn max_frame(&self) -> NonZeroU32 {
        self.max_frame
    }

    /// The most rows the service puts on one page.
    #[must_use]
    pub const fn max_page(&self) -> NonZeroU32 {
        self.max_page
    }

    /// Send one request and read its reply.
    ///
    /// # Errors
    ///
    /// `Ended::NotAsked` for a request larger than the service reads, refused
    /// before sending; `Ended::Unknown` for any failure from sending onward,
    /// and for a `mutation.apply` error that is not one of
    /// [`KNOWN_REFUSALS`]: those the service sends when the change may already
    /// have been applied ([`MAY_HAVE_APPLIED`]), and any code this client does
    /// not know.
    pub fn call(&mut self, method: &str, params: Option<&RawValue>) -> Result<Reply, Ended> {
        let reply = exchange(&mut self.stream, self.max_frame, method, params)?;
        let Reply::Refused(refusal) = reply else {
            return Ok(reply);
        };
        // A read changes nothing, so a refusal of a read is a refusal.
        if method != "mutation.apply" || KNOWN_REFUSALS.contains(&refusal.code.as_str()) {
            return Ok(Reply::Refused(refusal));
        }
        let why = if MAY_HAVE_APPLIED.contains(&refusal.code.as_str()) {
            "the change may have been applied"
        } else {
            "this client does not know that code, so whether the change was applied is not known"
        };
        let why = format!(
            "the service answered {}: {}; {why}",
            refusal.code, refusal.message
        );
        match refusal.verified {
            Some(receipt) => Err(Ended::Received { why, receipt }),
            None => Err(Ended::Unknown(why)),
        }
    }

    /// Read the next frame of an answer that is a stream, such as
    /// `head.follow`'s, sent under the same id as its first. A read changes
    /// nothing, so a refusal is a refusal.
    ///
    /// # Errors
    ///
    /// `Ended::Unknown` when the frame could not be read: the connection
    /// closed, failed or timed out.
    pub fn next_reply(&mut self) -> Result<Reply, Ended> {
        receive(&mut self.stream, self.max_frame)
    }

    /// An owned socket handle used only to cancel a disconnected browser's follow.
    pub(crate) fn follow_socket(&self) -> io::Result<UnixStream> {
        self.stream.try_clone()
    }

    /// Bound each later read by `timeout`, or by nothing with `None`.
    ///
    /// # Errors
    ///
    /// `Ended::Unknown` when the bound could not be set.
    pub fn read_within(&self, timeout: Option<Duration>) -> Result<(), Ended> {
        self.stream
            .set_read_timeout(timeout)
            .map_err(|error| Ended::Unknown(format!("the read bound could not be set: {error}")))
    }
}

/// `haematite call`, ending in its exit code.
#[must_use]
pub fn run(args: impl Iterator<Item = String>) -> ExitCode {
    finish(call(args))
}

/// Print what an exchange came to and give its exit code: 0 answered, 1 could
/// not ask, 2 refused, 3 outcome not known to the caller.
fn finish(outcome: Result<Reply, Ended>) -> ExitCode {
    match outcome {
        Ok(Reply::Answered(result)) => {
            let mut output = io::stdout().lock();
            match writeln!(output, "{}", result.get()).and_then(|()| output.flush()) {
                Ok(()) => ExitCode::SUCCESS,
                Err(error) => {
                    // The service acted and the caller did not get its answer.
                    eprintln!(
                        "haematite: answer received, but the result could not be written to stdout: {error}"
                    );
                    ExitCode::from(3)
                }
            }
        }
        Ok(Reply::Refused(refusal)) => {
            if let Err(error) = print_refusal(&refusal) {
                eprintln!("haematite: receipt_output_failed: {error}");
            }
            ExitCode::from(2)
        }
        Err(ended) => {
            if let Err(error) = print_ended(&ended) {
                eprintln!("haematite: receipt_output_failed: {error}");
            }
            ExitCode::from(exit_code(&ended))
        }
    }
}

/// 1 when nothing was sent, so asking again is safe; 3 when it may have been.
#[must_use]
pub const fn exit_code(ended: &Ended) -> u8 {
    match ended {
        Ended::Usage(_) | Ended::NotAsked(_) => 1,
        Ended::Unknown(_) | Ended::Received { .. } => 3,
    }
}

/// The standard error line for a refusal.
#[must_use]
pub fn refused(refusal: &Refusal) -> String {
    let at = refusal
        .path
        .as_deref()
        .map_or_else(String::new, |path| format!(" at {path}"));
    let (code, message) = (&refusal.code, &refusal.message);
    format!("haematite: refused {code}: {message}{at}")
}

/// The standard error line for an exchange that gave no reply.
#[must_use]
pub fn words(ended: &Ended) -> String {
    match ended {
        Ended::Usage(why) => format!("haematite: {why}"),
        Ended::NotAsked(why) => format!("haematite: could not ask: {why}"),
        Ended::Unknown(why) => format!("haematite: the outcome is not known: {why}"),
        Ended::Received { why, .. } => format!("haematite: complete receipt received: {why}"),
    }
}

pub(super) fn print_refusal(refusal: &Refusal) -> io::Result<()> {
    let mut output = io::stderr().lock();
    writeln!(output, "{}", refused(refusal))?;
    if let Some(receipt) = &refusal.verified {
        output.write_all(receipt.bytes())?;
        output.write_all(b"\n")?;
    }
    output.flush()
}
pub(super) fn print_ended(ended: &Ended) -> io::Result<()> {
    let mut output = io::stderr().lock();
    writeln!(output, "{}", words(ended))?;
    if let Ended::Received { receipt, .. } = ended {
        output.write_all(receipt.bytes())?;
        output.write_all(b"\n")?;
    }
    output.flush()
}

enum Target {
    Socket(PathBuf),
    Config(PathBuf),
}

/// The flags every client command takes: where the service is, and how long
/// to wait for it.
#[derive(Default)]
struct Common {
    target: Option<Target>,
    timeout: Option<NonZeroU64>,
}

impl Common {
    /// Take `arg`, and its value from `args`, when it is a shared flag.
    fn take(&mut self, arg: &str, args: &mut impl Iterator<Item = String>) -> Result<bool, String> {
        match arg {
            "--socket" | "--config" if self.target.is_none() => {
                let path = PathBuf::from(args.next().ok_or_else(|| format!("{arg} needs a path"))?);
                self.target = Some(if arg == "--socket" {
                    Target::Socket(path)
                } else {
                    Target::Config(path)
                });
                Ok(true)
            }
            "--socket" | "--config" => Err("give exactly one of --socket and --config".to_owned()),
            "--timeout-ms" if self.timeout.is_none() => {
                let text = args
                    .next()
                    .ok_or("--timeout-ms needs a number of milliseconds")?;
                let millis = text
                    .parse::<NonZeroU64>()
                    .map_err(|error| format!("--timeout-ms {text:?}: {error}"))?;
                self.timeout = Some(millis);
                Ok(true)
            }
            _ => Ok(false),
        }
    }

    /// Where the service is and how long to wait, once every flag is read.
    fn finish(self) -> Result<(Target, Duration), String> {
        let target = self
            .target
            .ok_or("give exactly one of --socket and --config")?;
        let millis = self.timeout.unwrap_or(DEFAULT_TIMEOUT_MS);
        Ok((target, Duration::from_millis(millis.get())))
    }
}

struct Call {
    target: Target,
    timeout: Duration,
    method: String,
    /// `None` when the operation has no params.
    params: Option<Text>,
}

/// One JSON value as given on the command line, or `-` for standard input.
enum Text {
    Given(String),
    Stdin,
}

impl Text {
    fn of(text: String) -> Self {
        if text == "-" {
            Self::Stdin
        } else {
            Self::Given(text)
        }
    }
}

fn call(args: impl Iterator<Item = String>) -> Result<Reply, Ended> {
    let asked = parse(args).map_err(|why| Ended::Usage(format!("{why}\n{USAGE}")))?;
    let params = asked
        .params
        .map(|text| one_value(text, "params"))
        .transpose()?;
    let socket = socket_of(&asked.target)?;
    let mut client = Client::connect(&socket, asked.timeout)?;
    if asked.method == "hello" && params.is_none() {
        return Ok(Reply::Answered(client.hello().to_owned()));
    }
    client.call(&asked.method, params.as_deref())
}

fn parse(mut args: impl Iterator<Item = String>) -> Result<Call, String> {
    let mut common = Common::default();
    let mut rest = Vec::new();
    while let Some(arg) = args.next() {
        if common.take(&arg, &mut args)? {
            continue;
        }
        if arg.starts_with("--") {
            return Err(format!("unknown or repeated flag {arg:?}"));
        }
        rest.push(arg);
    }
    let (target, timeout) = common.finish()?;
    let mut rest = rest.into_iter();
    let method = rest.next().ok_or("name the method to call")?;
    let params = rest.next().map(Text::of);
    if let Some(extra) = rest.next() {
        return Err(format!("unexpected argument {extra:?}"));
    }
    Ok(Call {
        target,
        timeout,
        method,
        params,
    })
}

/// `given` as one JSON value, kept as the text given; `what` names it.
fn one_value(given: Text, what: &str) -> Result<Box<RawValue>, Ended> {
    let text = match given {
        Text::Given(text) => text,
        Text::Stdin => {
            let mut text = String::new();
            io::stdin().read_to_string(&mut text).map_err(|error| {
                Ended::NotAsked(format!(
                    "the {what} could not be read from standard input: {error}"
                ))
            })?;
            text
        }
    };
    serde_json::from_str(&text)
        .map_err(|error| Ended::NotAsked(format!("the {what} is not one JSON value: {error}")))
}

/// The socket named, or the one a service config names, read by the
/// service's own config parser.
fn socket_of(target: &Target) -> Result<PathBuf, Ended> {
    match target {
        Target::Socket(path) => Ok(path.clone()),
        Target::Config(path) => {
            let named = path.display();
            let bytes = std::fs::read(path).map_err(|error| {
                Ended::NotAsked(format!(
                    "the service config {named} could not be read: {error}"
                ))
            })?;
            let config: Config = serde_json::from_slice(&bytes)
                .map_err(|error| Ended::NotAsked(format!("the service config {named}: {error}")))?;
            config
                .endpoint(false)
                .map(|endpoint| endpoint.socket)
                .map_err(|error| Ended::NotAsked(format!("the service config {named}: {error}")))
        }
    }
}

/// `UnixStream` has no connect timeout, so the connect runs on its own thread
/// and is waited for at most `timeout`.
fn connect(socket: &Path, timeout: Duration) -> Result<UnixStream, Ended> {
    let (sender, receiver) = mpsc::channel();
    let path = socket.to_path_buf();
    std::thread::Builder::new()
        .name("haem-call-connect".to_owned())
        .spawn(move || {
            // The receiver is gone only when the connect outlived the timeout.
            let _unwaited = sender.send(UnixStream::connect(path));
        })
        .map_err(|error| Ended::NotAsked(format!("the connect could not start: {error}")))?;
    match receiver.recv_timeout(timeout) {
        Ok(Ok(stream)) => Ok(stream),
        Ok(Err(error)) => Err(Ended::NotAsked(format!(
            "could not connect to {}: {error}",
            socket.display()
        ))),
        Err(_) => Err(Ended::NotAsked(format!(
            "could not connect to {} within {} ms",
            socket.display(),
            timeout.as_millis()
        ))),
    }
}

#[derive(Serialize)]
struct Outgoing<'a> {
    id: &'a str,
    operation: Operation<'a>,
}

#[derive(Serialize)]
struct Operation<'a> {
    method: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")]
    params: Option<&'a RawValue>,
}

#[derive(Deserialize)]
struct Incoming {
    id: String,
    /// Present-and-null is an answer of null, so `null` is kept as its bytes.
    #[serde(default, deserialize_with = "present")]
    result: Option<Box<RawValue>>,
    #[serde(default)]
    error: Option<Refusal>,
}

fn present<'de, D: Deserializer<'de>>(input: D) -> Result<Option<Box<RawValue>>, D::Error> {
    Box::<RawValue>::deserialize(input).map(Some)
}

/// The first answer frame read only for whether it opens a sealed receipt.
#[derive(Deserialize)]
struct Probe {
    #[serde(default)]
    receipt: Option<Box<RawValue>>,
}

fn exchange(
    stream: &mut UnixStream,
    limit: NonZeroU32,
    method: &str,
    params: Option<&RawValue>,
) -> Result<Reply, Ended> {
    let operation = Operation { method, params };
    let request = serde_json::to_vec(&Outgoing { id: ID, operation })
        .map_err(|error| Ended::NotAsked(format!("the request could not be written: {error}")))?;
    if !u32::try_from(request.len()).is_ok_and(|length| length <= limit.get()) {
        return Err(Ended::NotAsked(format!(
            "request_too_large: the request is {} bytes and the service reads at most {limit}",
            request.len()
        )));
    }
    frame::write(stream, &request, limit).map_err(|error| lost("sending the request", &error))?;
    receive(stream, limit)
}

/// Read one answer frame, and the rest of a sealed receipt it opens.
fn receive(stream: &mut UnixStream, limit: NonZeroU32) -> Result<Reply, Ended> {
    let bytes = match frame::read(stream, limit) {
        Ok(Some(bytes)) => bytes,
        Ok(None) => {
            return Err(Ended::Unknown(
                "the service closed the connection before answering".to_owned(),
            ));
        }
        Err(error) => return Err(lost("waiting for the answer", &error)),
    };
    let probe: Probe = serde_json::from_slice(&bytes)
        .map_err(|error| Ended::Unknown(format!("receipt_frame_decode_failed: {error}")))?;
    if probe.receipt.is_none() {
        return reply(&bytes);
    }
    let mut assembler =
        Assembler::new(ID, limit.get()).map_err(|error| Ended::Unknown(error.to_string()))?;
    let mut body = bytes;
    loop {
        if let Some(complete) = assembler
            .accept(&body)
            .map_err(|error| Ended::Unknown(error.to_string()))?
        {
            let complete = Arc::new(complete);
            let refusal = complete.refusal().ok_or_else(|| Ended::Received {
                why: "receipt_refusal_missing".to_owned(),
                receipt: Arc::clone(&complete),
            })?;
            return Ok(Reply::Refused(Refusal {
                code: refusal.code.clone(),
                message: refusal.message.clone(),
                path: refusal.path.clone(),
                verified: Some(complete),
            }));
        }
        body = match frame::read(stream, limit) {
            Ok(Some(body)) => body,
            Ok(None) => return Err(Ended::Unknown("receipt_connection_closed".to_owned())),
            Err(error) => {
                return Err(Ended::Unknown(format!(
                    "receipt_connection_failed: {error}"
                )));
            }
        };
    }
}

fn lost(doing: &str, error: &io::Error) -> Ended {
    match error.kind() {
        io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut => {
            Ended::Unknown(format!("timed out {doing}: {error}"))
        }
        _ => Ended::Unknown(format!("the connection failed {doing}: {error}")),
    }
}

fn reply(bytes: &[u8]) -> Result<Reply, Ended> {
    let unreadable = |why: String| Ended::Unknown(format!("the answer could not be read: {why}"));
    let incoming: Incoming =
        serde_json::from_slice(bytes).map_err(|error| unreadable(error.to_string()))?;
    if incoming.id != ID {
        return Err(unreadable(format!(
            "it answers {:?}, not {ID:?}",
            incoming.id
        )));
    }
    match (incoming.result, incoming.error) {
        (Some(result), None) => Ok(Reply::Answered(result)),
        (None, Some(refusal)) => Ok(Reply::Refused(refusal)),
        _ => Err(unreadable(
            "it carries neither or both of result and error".to_owned(),
        )),
    }
}

#[cfg(test)]
mod nonzero_tests {
    use super::{Common, DEFAULT_TIMEOUT_MS, NonZeroU64, PathBuf, Target};

    #[test]
    fn nonzero_timeout_readback() -> Result<(), Box<dyn std::error::Error>> {
        let cases = [
            (None, DEFAULT_TIMEOUT_MS.get()),
            (Some(1), 1),
            (Some(37), 37),
            (Some(u64::MAX), u64::MAX),
        ];
        for (given, expected) in cases {
            let timeout = given
                .map(|value| NonZeroU64::new(value).ok_or("zero timeout"))
                .transpose()?;
            let common = Common {
                target: Some(Target::Socket(PathBuf::from("unused.sock"))),
                timeout: std::hint::black_box(timeout),
            };
            let (_, actual) = common.finish()?;
            assert_eq!(actual.as_millis(), u128::from(expected));
        }
        Ok(())
    }
}

#[cfg(test)]
mod json_text_refusal_tests {
    use super::{KNOWN_REFUSALS, Refusal, Reply, finish, refused};
    use std::process::ExitCode;

    #[test]
    fn json_text_invalid_is_a_named_client_refusal() {
        let refusal = Refusal {
            code: "json_text_invalid".to_owned(),
            message: "value is not JSON".to_owned(),
            path: Some("/payload".to_owned()),
            verified: None,
        };
        assert!(KNOWN_REFUSALS.contains(&refusal.code.as_str()));
        assert_eq!(
            refused(&refusal),
            "haematite: refused json_text_invalid: value is not JSON at /payload"
        );
        assert_eq!(finish(Ok(Reply::Refused(refusal))), ExitCode::from(2));
    }
}

#[cfg(test)]
mod access_refusal_tests {
    use super::KNOWN_REFUSALS;

    /// A change a Lys-served service refused before it ran is a refusal, not
    /// an unknown outcome: the client says it was not applied.
    #[test]
    fn every_access_refusal_is_known_not_to_have_applied() {
        for code in [
            "route_unclassified",
            "permission_refused",
            "held_for_approval",
            "pass_missing",
            "lys_could_not_be_asked",
            "signature_refused",
            "pass_expired",
        ] {
            assert!(KNOWN_REFUSALS.contains(&code), "{code} is not known");
        }
    }
}