isothrum_client/proto.rs
1//! The service's wire protocol, version [`PROTOCOL`]: newline-delimited JSON (one object per
2//! line, UTF-8, at most [`MAX_LINE`] bytes) over the home's local endpoint.
3//!
4//! The client writes [`Request`]s, each with an id of its choosing; the service answers each with
5//! one [`Reply`] carrying that id. The first request of a connection is [`Command::Hello`]; the
6//! service refuses any other before it. An operation command (`up`, `down`, `park`, `resume`,
7//! `update`, `attach`, `detach`, `retire`, `provision`, `check`) is answered at once with
8//! [`Reply::Accepted`], or refused (`locked`) while another of its run is queued or running: one
9//! operation per run, but for one asked once the running one was cancelled, queued behind it; the operation's events, ending with its `result` or
10//! `error` and an `operation` event of phase `ended`, arrive on a subscription: after `subscribe`,
11//! the connection carries [`Reply::Event`] frames until it closes or `unsubscribe`.
12//!
13//! Everything else an embedder asks of a home goes through the service too, never through the
14//! home's files: a run's record (`record`), forgetting it (`forget`), the runs past their lifetime
15//! (`expired`), the way into a machine (`console_command`), its screen (`graphical_console`, whose
16//! tunnel, when it has one, stays open as long as the connection that asked) or its hypervisor's
17//! app (`native_console`), where its published services are reached (`service_endpoints`), what its machines use
18//! (`usage`), the
19//! runner's SSH key (`public_key`), and what the runs' own downloads fetched (`downloads`) and their
20//! removal (`remove_downloads`).
21//!
22//! # What every protocol keeps
23//!
24//! A client of one release meets services of others: an app that bundles Isothrum finds the
25//! service an older (or newer) release started. So that it can always tell which service runs and
26//! replace it, every protocol, this one and every later one, keeps these two frames as they are:
27//!
28//! - `{"id":N,"cmd":"hello","protocol":P}` is answered `{"reply":"hello","id":N,"protocol":Q,
29//! "version":"…"}` whatever `P` is: `Q` is the protocol the service speaks, `version` its
30//! release. When `P` isn't `Q`, the connection then takes only `shutdown_if_idle` (any other
31//! request is refused).
32//! - `{"id":N,"cmd":"shutdown_if_idle"}` is answered `{"reply":"ok","id":N}` (the service stops,
33//! and takes no operation meanwhile) or `{"reply":"busy","id":N,"operations":[…]}` (it has
34//! operations queued or running, and goes on).
35
36use isothrum_runner::{
37 Download, DownloadRemoval, DownloadToAdopt, DownloadsToRemove, InputVariable, MachineUsage, NativeConsole, Op, Park, RunName, ServiceEndpoint,
38 ShellCommand, Status,
39};
40use serde::{Deserialize, Serialize};
41
42use crate::v1::{Event, EventCursor, OperationId, OperationRow, RunRow};
43
44mod console;
45mod target;
46pub use console::{ConsoleEndpoint, ReachedConsole};
47pub use target::{OpOptions, Target};
48
49/// The protocol's version: a service refuses a `hello` with another.
50pub const PROTOCOL: u32 = 1;
51
52/// The longest line either side accepts, in bytes (a longer one ends the connection).
53pub const MAX_LINE: usize = 16 * 1024 * 1024;
54
55/// One request: its id and what it asks.
56#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
57pub struct Request {
58 /// The id its reply carries.
59 pub id: u64,
60 /// What it asks.
61 #[serde(flatten)]
62 pub command: Command,
63}
64
65/// What a request asks of the service.
66#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
67#[serde(tag = "cmd", rename_all = "snake_case")]
68#[non_exhaustive]
69pub enum Command {
70 /// Opens the conversation (must come first).
71 Hello {
72 /// The protocol the client speaks ([`PROTOCOL`]).
73 protocol: u32,
74 },
75 /// Start the run (a parked run is resumed).
76 Up {
77 /// The run.
78 target: Target,
79 /// The values it runs with.
80 #[serde(default)]
81 options: OpOptions,
82 /// How long a run that stops itself may live, in seconds.
83 #[serde(default, skip_serializing_if = "Option::is_none")]
84 lifetime_s: Option<u64>,
85 },
86 /// Remove everything the run created.
87 Down {
88 /// The run.
89 target: Target,
90 /// The values it runs with.
91 #[serde(default)]
92 options: OpOptions,
93 },
94 /// Stop the run, keeping what it created.
95 Park {
96 /// The run.
97 target: Target,
98 /// The values it runs with.
99 #[serde(default)]
100 options: OpOptions,
101 /// Paused or shut down.
102 mode: Park,
103 },
104 /// Start a parked run again.
105 Resume {
106 /// The run.
107 target: Target,
108 /// The values it runs with.
109 #[serde(default)]
110 options: OpOptions,
111 },
112 /// Bring the running run up to date with its project.
113 Update {
114 /// The run.
115 target: Target,
116 /// The values it runs with.
117 #[serde(default)]
118 options: OpOptions,
119 },
120 /// Bring a machine of the project that isn't running into the running run.
121 Attach {
122 /// The run.
123 target: Target,
124 /// The values it runs with.
125 #[serde(default)]
126 options: OpOptions,
127 /// The machine.
128 machine: String,
129 },
130 /// Take a machine out of the running run.
131 Retire {
132 /// The run.
133 target: Target,
134 /// The values it runs with.
135 #[serde(default)]
136 options: OpOptions,
137 /// The machine.
138 machine: String,
139 },
140 /// Save a machine of the running run as a box file (Vagrant's `package`).
141 Package {
142 /// The run.
143 target: Target,
144 /// The values it runs with.
145 #[serde(default)]
146 options: OpOptions,
147 /// The machine.
148 machine: String,
149 /// The box file written.
150 output: std::path::PathBuf,
151 },
152 /// Run the set-up again on the running machines.
153 Provision {
154 /// The run.
155 target: Target,
156 /// The values it runs with.
157 #[serde(default)]
158 options: OpOptions,
159 /// Only this machine.
160 #[serde(default, skip_serializing_if = "Option::is_none")]
161 machine: Option<String>,
162 /// Only the provisioner of this name (Vagrant's `--provision-with`).
163 #[serde(default, skip_serializing_if = "Option::is_none")]
164 with: Option<String>,
165 },
166 /// Runs a command in a machine of the run, with no terminal; its result says how it ended.
167 Exec {
168 /// The run.
169 target: Target,
170 /// The values it runs with.
171 #[serde(default)]
172 options: OpOptions,
173 /// The machine.
174 machine: String,
175 /// The command and its arguments.
176 argv: Vec<String>,
177 },
178 /// The run's status (not queued: it reads). `target` is needed for a run not recorded yet;
179 /// without it the run is reopened as recorded.
180 Status {
181 /// The run.
182 run: RunName,
183 /// Where it is opened from (default: where its record says).
184 #[serde(default, skip_serializing_if = "Option::is_none")]
185 target: Option<Target>,
186 /// The values and secrets its read gives the tools, beside the recorded ones (a
187 /// server's API token, for its machines' states there).
188 #[serde(default, skip_serializing_if = "OpOptions::is_empty")]
189 options: OpOptions,
190 },
191 /// The input variables a Terraform folder declares (not queued: it reads the folder's
192 /// files, and runs nothing).
193 Variables {
194 /// The folder (its `name` is unused).
195 target: Target,
196 },
197 /// Every recorded run.
198 List,
199 /// One run's record (not queued: it reads the store); none for a run never recorded.
200 Record {
201 /// The run.
202 run: RunName,
203 },
204 /// Forgets a run's record: what the run created is left as it is. Refused while an operation
205 /// of the run is queued or running.
206 Forget {
207 /// The run.
208 run: RunName,
209 },
210 /// The recorded runs whose lifetime passed and that may still hold something: what a reaper
211 /// takes down (a `down` each, given the values and secrets the run needs).
212 Expired,
213 /// The command that opens an interactive console into a machine of a run (not queued:
214 /// nothing runs), for the client to run in its own terminal.
215 ConsoleCommand {
216 /// The run.
217 run: RunName,
218 /// Where it is opened from (default: where its record says).
219 #[serde(default, skip_serializing_if = "Option::is_none")]
220 target: Option<Target>,
221 /// The machine.
222 machine: String,
223 /// The account to open it as.
224 #[serde(default, skip_serializing_if = "Option::is_none")]
225 user: Option<String>,
226 },
227 /// A running machine's graphical console (not queued: it reads). Reached through an SSH
228 /// tunnel, the tunnel stays open for as long as the connection that asked: a client asks on a
229 /// connection of its own, closed when the viewer is done; the service writes
230 /// [`Reply::ConsoleClosed`] and closes it when the tunnel ends first.
231 GraphicalConsole {
232 /// The run.
233 run: RunName,
234 /// Where it is opened from (default: where its record says).
235 #[serde(default, skip_serializing_if = "Option::is_none")]
236 target: Option<Target>,
237 /// The values and secrets the hypervisor is asked with (a server's address and token).
238 #[serde(default, skip_serializing_if = "OpOptions::is_empty")]
239 options: OpOptions,
240 /// The machine.
241 machine: String,
242 },
243 /// What opens a running machine in its hypervisor's own app (not queued: it reads).
244 NativeConsole {
245 /// The run.
246 run: RunName,
247 /// Where it is opened from (default: where its record says).
248 #[serde(default, skip_serializing_if = "Option::is_none")]
249 target: Option<Target>,
250 /// The values and secrets the hypervisor is asked with.
251 #[serde(default, skip_serializing_if = "OpOptions::is_empty")]
252 options: OpOptions,
253 /// The machine.
254 machine: String,
255 },
256 /// The service endpoints a run publishes, each where this computer reaches it: as the run
257 /// gives it, or at a local forward through the run's jump host, which the service keeps open
258 /// (not queued: it reads).
259 ServiceEndpoints {
260 /// The run.
261 run: RunName,
262 /// Where it is opened from (default: where its record says).
263 #[serde(default, skip_serializing_if = "Option::is_none")]
264 target: Option<Target>,
265 /// The values and secrets its outputs are read with.
266 #[serde(default, skip_serializing_if = "OpOptions::is_empty")]
267 options: OpOptions,
268 },
269 /// What each running machine of a run uses now (CPU and memory), as its engine samples it
270 /// once; none for a format whose tool reports no per-machine figure (not queued: it reads).
271 Usage {
272 /// The run.
273 run: RunName,
274 /// Where it is opened from (default: where its record says).
275 #[serde(default, skip_serializing_if = "Option::is_none")]
276 target: Option<Target>,
277 /// The values and secrets its tools are run with.
278 #[serde(default, skip_serializing_if = "OpOptions::is_empty")]
279 options: OpOptions,
280 },
281 /// The public half of the runner's SSH key, one line (the key is made when there is none):
282 /// what the client authorizes where a run's SSH goes.
283 PublicKey,
284 /// What the runs' own downloads fetched and the home's store records (the images a Compose
285 /// start's pull pulled, the boxes a Vagrant `up` added), each with its size when it can be read
286 /// (not queued: it reads).
287 Downloads,
288 /// Removes the recorded downloads `which` names, each on its own: one its tool refuses (in
289 /// use) is said in its outcome and kept, the others go on. Nothing the store doesn't record is
290 /// removed (not queued).
291 RemoveDownloads {
292 /// All, or those of the given ids.
293 which: DownloadsToRemove,
294 },
295 /// Adopts downloads fetched outside the runs (by an earlier program's own record) into the
296 /// home's record, each one on this computer now as it was fetched: they are listed and
297 /// removed like the runs' own (not queued).
298 AdoptDownloads {
299 /// The downloads to adopt.
300 adopted: Vec<DownloadToAdopt>,
301 },
302 /// The IPv4 address blocks the engine's networks hold, but those of a run's own networks:
303 /// what a deployment's networks must stay clear of (not queued).
304 AddressBlocksInUse {
305 /// The run whose own networks don't count.
306 #[serde(default, skip_serializing_if = "Option::is_none")]
307 except: Option<RunName>,
308 /// The Docker context of the engine asked; the current one when none.
309 #[serde(default, skip_serializing_if = "Option::is_none")]
310 docker_context: Option<String>,
311 },
312 /// The run's latest operations, newest first.
313 Operations {
314 /// The run.
315 run: RunName,
316 /// At most this many.
317 limit: u32,
318 },
319 /// Cancels an operation: a queued one never begins, a running one is cut short (its tools
320 /// stopped).
321 Cancel {
322 /// The operation.
323 operation: OperationId,
324 },
325 /// Turns the connection into a subscription: the events after `after` (every one the
326 /// service keeps when `None`), then the live ones, of one run or every run.
327 Subscribe {
328 /// Only this run's.
329 #[serde(default, skip_serializing_if = "Option::is_none")]
330 run: Option<RunName>,
331 /// Resumes after this cursor (a reconnecting client's last).
332 #[serde(default, skip_serializing_if = "Option::is_none")]
333 after: Option<EventCursor>,
334 },
335 /// Ends the connection's subscription.
336 Unsubscribe,
337 /// Stops the service: queued operations are dropped, running ones cancelled and their tools
338 /// stopped, then it exits.
339 Shutdown,
340 /// Stops the service only when no operation is queued or running ([`Reply::Ok`]: it takes no
341 /// new one, and exits); else refused with [`Reply::Busy`], and nothing changes. Every protocol
342 /// takes it, from a client of any protocol (see the module's documentation).
343 ShutdownIfIdle,
344}
345
346impl Command {
347 /// The operation it queues, when it queues one.
348 #[must_use]
349 pub fn op(&self) -> Option<Op> {
350 Some(match self {
351 Command::Up { .. } => Op::Up,
352 Command::Down { .. } => Op::Down,
353 Command::Park { .. } => Op::Park,
354 Command::Resume { .. } => Op::Resume,
355 Command::Update { .. } => Op::Update,
356 Command::Attach { .. } => Op::Attach,
357 Command::Retire { .. } => Op::Retire,
358 Command::Package { .. } => Op::Package,
359 Command::Provision { .. } => Op::Provision,
360 Command::Exec { .. } => Op::Check,
361 // Not an operation: a question about the home, or the conversation's own.
362 _ => return None,
363 })
364 }
365
366 /// Whether it asks the service about the home, running no operation: a run's status or
367 /// record, forgetting it, the expired runs, a way into a machine, its endpoints, the key, the
368 /// downloads and their removal.
369 #[must_use]
370 pub fn is_question(&self) -> bool {
371 matches!(
372 self,
373 Command::Status { .. }
374 | Command::Record { .. }
375 | Command::Forget { .. }
376 | Command::Expired
377 | Command::ConsoleCommand { .. }
378 | Command::GraphicalConsole { .. }
379 | Command::NativeConsole { .. }
380 | Command::PublicKey
381 | Command::ServiceEndpoints { .. }
382 | Command::Usage { .. }
383 | Command::Downloads
384 | Command::RemoveDownloads { .. }
385 | Command::AdoptDownloads { .. }
386 | Command::AddressBlocksInUse { .. }
387 )
388 }
389
390 /// The run and the options of an operation command.
391 #[must_use]
392 pub fn target(&self) -> Option<(&Target, &OpOptions)> {
393 match self {
394 Command::Up { target, options, .. }
395 | Command::Down { target, options }
396 | Command::Park { target, options, .. }
397 | Command::Resume { target, options }
398 | Command::Update { target, options }
399 | Command::Attach { target, options, .. }
400 | Command::Retire { target, options, .. }
401 | Command::Package { target, options, .. }
402 | Command::Provision { target, options, .. }
403 | Command::Exec { target, options, .. } => Some((target, options)),
404 _ => None,
405 }
406 }
407}
408
409/// What the service writes.
410#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
411#[serde(tag = "reply", rename_all = "snake_case")]
412#[non_exhaustive]
413pub enum Reply {
414 /// To `hello`.
415 Hello {
416 /// The request's id.
417 id: u64,
418 /// The protocol it speaks.
419 protocol: u32,
420 /// Its version.
421 version: String,
422 },
423 /// An operation command was accepted: its id, and its place on its run (0: it begins now; 1:
424 /// it waits for the run's cancelled operation to end).
425 Accepted {
426 /// The request's id.
427 id: u64,
428 /// The operation's id.
429 operation: OperationId,
430 /// Its run.
431 run: RunName,
432 /// How many of the run's operations are ahead of it.
433 position: u32,
434 },
435 /// To `status`.
436 Status {
437 /// The request's id.
438 id: u64,
439 /// The status.
440 status: Box<Status>,
441 },
442 /// To `variables`.
443 Variables {
444 /// The request's id.
445 id: u64,
446 /// The folder's input variables, by name.
447 variables: Vec<InputVariable>,
448 },
449 /// To `list` (every recorded run) and `expired` (those past their lifetime).
450 Runs {
451 /// The request's id.
452 id: u64,
453 /// The runs.
454 runs: Vec<RunRow>,
455 },
456 /// To `record`.
457 Run {
458 /// The request's id.
459 id: u64,
460 /// The run's record; none for a run never recorded.
461 run: Option<Box<RunRow>>,
462 },
463 /// To `console_command`.
464 Shell {
465 /// The request's id.
466 id: u64,
467 /// The command that opens the console.
468 command: ShellCommand,
469 },
470 /// To `graphical_console`.
471 Console {
472 /// The request's id.
473 id: u64,
474 /// Where the console answers, and how to sign in.
475 console: Box<ReachedConsole>,
476 },
477 /// After a `graphical_console` reached through a tunnel, once the tunnel ended on its own
478 /// (its `ssh` exited): the service closes the connection after it.
479 ConsoleClosed {
480 /// The `graphical_console` request's id.
481 id: u64,
482 /// How the tunnel ended.
483 reason: String,
484 },
485 /// To `native_console`.
486 Native {
487 /// The request's id.
488 id: u64,
489 /// What opens the machine in its hypervisor's app.
490 console: NativeConsole,
491 },
492 /// To `service_endpoints`.
493 Endpoints {
494 /// The request's id.
495 id: u64,
496 /// The endpoints, by name.
497 endpoints: Vec<ServiceEndpoint>,
498 },
499 /// To `usage`.
500 Usage {
501 /// The request's id.
502 id: u64,
503 /// Each running machine's use, by name.
504 machines: Vec<MachineUsage>,
505 },
506 /// To `public_key`.
507 PublicKey {
508 /// The request's id.
509 id: u64,
510 /// The key's public half, one line.
511 key: String,
512 },
513 /// To `downloads`.
514 Downloads {
515 /// The request's id.
516 id: u64,
517 /// The recorded downloads, oldest first.
518 downloads: Vec<Download>,
519 },
520 /// To `remove_downloads`: how each removal went, in the order asked.
521 DownloadsRemoved {
522 /// The request's id.
523 id: u64,
524 /// Each removal.
525 removed: Vec<DownloadRemoval>,
526 },
527 /// To `adopt_downloads`: the downloads recorded for those asked, new or not.
528 DownloadsAdopted {
529 /// The request's id.
530 id: u64,
531 /// The recorded downloads.
532 adopted: Vec<Download>,
533 },
534 /// To `address_blocks_in_use`: the blocks, in CIDR form.
535 AddressBlocks {
536 /// The request's id.
537 id: u64,
538 /// The blocks.
539 blocks: Vec<String>,
540 },
541 /// To `operations`.
542 Operations {
543 /// The request's id.
544 id: u64,
545 /// The operations, newest first.
546 operations: Vec<OperationRow>,
547 },
548 /// Done (`subscribe`, `unsubscribe`, `cancel`, `shutdown`, `shutdown_if_idle`).
549 Ok {
550 /// The request's id.
551 id: u64,
552 },
553 /// Refused, or failed.
554 Error {
555 /// The request's id (0 for a line that couldn't be read as a request).
556 id: u64,
557 /// Why: its code, message and typed fields, as the runner reports a failure.
558 #[serde(flatten)]
559 report: isothrum_runner::ErrorReport,
560 },
561 /// To `shutdown_if_idle`, refused: the operations queued or running, which the service goes on
562 /// with.
563 Busy {
564 /// The request's id.
565 id: u64,
566 /// The operations, oldest first.
567 operations: Vec<OperationId>,
568 },
569 /// A subscription's frame.
570 Event {
571 /// Its place in the stream.
572 cursor: EventCursor,
573 /// The event.
574 event: Box<Event>,
575 },
576}
577
578impl Reply {
579 /// The request it answers; `None` for a subscription's frame.
580 #[must_use]
581 pub fn id(&self) -> Option<u64> {
582 match self {
583 Reply::Hello { id, .. }
584 | Reply::Accepted { id, .. }
585 | Reply::Status { id, .. }
586 | Reply::Runs { id, .. }
587 | Reply::Run { id, .. }
588 | Reply::Shell { id, .. }
589 | Reply::Console { id, .. }
590 | Reply::ConsoleClosed { id, .. }
591 | Reply::Native { id, .. }
592 | Reply::Endpoints { id, .. }
593 | Reply::Usage { id, .. }
594 | Reply::PublicKey { id, .. }
595 | Reply::Variables { id, .. }
596 | Reply::Operations { id, .. }
597 | Reply::Downloads { id, .. }
598 | Reply::DownloadsRemoved { id, .. }
599 | Reply::DownloadsAdopted { id, .. }
600 | Reply::AddressBlocks { id, .. }
601 | Reply::Ok { id }
602 | Reply::Busy { id, .. }
603 | Reply::Error { id, .. } => Some(*id),
604 Reply::Event { .. } => None,
605 }
606 }
607}
608
609#[cfg(test)]
610mod tests {
611 use super::*;
612
613 use std::fmt;
614 use std::net::SocketAddr;
615
616 use isothrum_runner::{ConsoleProtocol, Format};
617 use serde_json::json;
618
619 /// `value` written as one line, read back as itself: the line, as JSON.
620 fn round_trip<T: Serialize + serde::de::DeserializeOwned + PartialEq + fmt::Debug>(value: &T) -> serde_json::Value {
621 let line = serde_json::to_string(value).unwrap();
622 assert!(!line.contains('\n'), "one line: {line}");
623 assert_eq!(&serde_json::from_str::<T>(&line).unwrap(), value, "{line}");
624 serde_json::from_str(&line).unwrap()
625 }
626
627 #[test]
628 fn a_request_is_one_flat_json_object() {
629 let up = Request {
630 id: 7,
631 command: Command::Up {
632 target: Target::new("/stacks/web", Some(RunName::new("web").unwrap())).with_format(Format::Compose),
633 options: OpOptions::default(),
634 lifetime_s: Some(3600),
635 },
636 };
637 assert_eq!(
638 round_trip(&up),
639 json!({"id": 7, "cmd": "up", "target": {"path": "/stacks/web", "name": "web", "format": "compose"}, "options": {}, "lifetime_s": 3600})
640 );
641 let park = round_trip(&Request {
642 id: 8,
643 command: Command::Park {
644 target: Target::new("/stacks/web", None),
645 options: OpOptions::default(),
646 mode: Park::Pause,
647 },
648 });
649 assert_eq!((&park["cmd"], &park["mode"]), (&json!("park"), &json!("pause")), "{park}");
650 round_trip(&Request { id: 9, command: Command::List });
651 assert_eq!(
652 round_trip(&Request {
653 id: 10,
654 command: Command::Subscribe {
655 run: None,
656 after: Some(EventCursor(41)),
657 },
658 }),
659 json!({"id": 10, "cmd": "subscribe", "after": 41})
660 );
661 }
662
663 #[test]
664 fn a_secret_is_never_in_the_debug_form() {
665 let options = OpOptions {
666 secrets: [("TOKEN".to_owned(), "hunter2".to_owned())].into(),
667 ..OpOptions::default()
668 };
669 let shown = format!("{options:?}");
670 assert!(shown.contains("TOKEN") && !shown.contains("hunter2"), "{shown}");
671 }
672
673 #[test]
674 fn reveal_is_off_unless_asked_and_travels_only_when_on() {
675 assert_eq!(serde_json::to_string(&OpOptions::default()).unwrap(), "{}");
676 let on = OpOptions {
677 reveal: true,
678 ..OpOptions::default()
679 };
680 let json = serde_json::to_string(&on).unwrap();
681 assert_eq!(json, r#"{"reveal":true}"#);
682 assert!(serde_json::from_str::<OpOptions>(&json).unwrap().reveal);
683 assert!(!serde_json::from_str::<OpOptions>("{}").unwrap().reveal, "off when not said");
684 }
685
686 #[test]
687 fn replies_round_trip() {
688 let accepted = round_trip(&Reply::Accepted {
689 id: 1,
690 operation: OperationId(4),
691 run: RunName::new("web").unwrap(),
692 position: 1,
693 });
694 assert_eq!(accepted, json!({"reply": "accepted", "id": 1, "operation": 4, "run": "web", "position": 1}));
695 let refused = round_trip(&Reply::Error {
696 id: 2,
697 report: isothrum_runner::ErrorReport::new(isothrum_runner::ErrorCode::Usage, "no").unchanged(),
698 });
699 assert_eq!(refused, json!({"reply": "error", "id": 2, "code": "usage", "message": "no", "changed": false}));
700 let run = RunName::new("web").unwrap();
701 let event = crate::v1::phase_event(&run, (Op::Down, OperationId(4)), crate::v1::OperationPhase::Started, None, None);
702 let frame = round_trip(&Reply::Event {
703 cursor: EventCursor(12),
704 event: Box::new(event),
705 });
706 assert_eq!(
707 (&frame["reply"], &frame["cursor"], &frame["event"]["v"]),
708 (&json!("event"), &json!(12), &json!(1)),
709 "{frame}"
710 );
711 }
712
713 #[test]
714 fn the_home_s_other_questions_are_flat_objects_too() {
715 let run = RunName::new("web").unwrap();
716 assert_eq!(
717 round_trip(&Request {
718 id: 4,
719 command: Command::Forget { run: run.clone() },
720 }),
721 json!({"id": 4, "cmd": "forget", "run": "web"})
722 );
723 assert_eq!(
724 round_trip(&Request {
725 id: 5,
726 command: Command::Expired
727 }),
728 json!({"id": 5, "cmd": "expired"})
729 );
730 assert_eq!(
731 round_trip(&Request {
732 id: 6,
733 command: Command::PublicKey
734 }),
735 json!({"id": 6, "cmd": "public_key"})
736 );
737 let console = round_trip(&Request {
738 id: 7,
739 command: Command::GraphicalConsole {
740 run: run.clone(),
741 target: None,
742 options: OpOptions::default(),
743 machine: "desktop".into(),
744 },
745 });
746 assert_eq!(console, json!({"id": 7, "cmd": "graphical_console", "run": "web", "machine": "desktop"}));
747 round_trip(&Request {
748 id: 8,
749 command: Command::ConsoleCommand {
750 run,
751 target: Some(Target::new("/stacks/web", None)),
752 machine: "web".into(),
753 user: Some("root".into()),
754 },
755 });
756 for command in [
757 Command::Record {
758 run: RunName::new("web").unwrap(),
759 },
760 Command::Expired,
761 Command::PublicKey,
762 ] {
763 assert_eq!(command.op(), None, "{command:?} queues nothing");
764 assert!(command.is_question(), "{command:?} is a question");
765 }
766 }
767
768 #[test]
769 fn the_downloads_and_their_removal_are_flat_objects_too() {
770 assert_eq!(
771 round_trip(&Request {
772 id: 3,
773 command: Command::Downloads
774 }),
775 json!({"id": 3, "cmd": "downloads"})
776 );
777 let remove = |which| Request {
778 id: 4,
779 command: Command::RemoveDownloads { which },
780 };
781 assert_eq!(
782 round_trip(&remove(DownloadsToRemove::All)),
783 json!({"id": 4, "cmd": "remove_downloads", "which": "all"})
784 );
785 assert_eq!(
786 round_trip(&remove(DownloadsToRemove::Only(vec![isothrum_runner::DownloadId(7)]))),
787 json!({"id": 4, "cmd": "remove_downloads", "which": {"only": [7]}})
788 );
789 assert!(Command::Downloads.is_question() && Command::Downloads.op().is_none());
790 assert!(remove(DownloadsToRemove::All).command.is_question());
791
792 let image = json!({"id": 7, "kind": "image", "reference": "nginx:1.27", "image_id": "sha256:a", "docker_context": "orbstack",
793 "run": "web", "fetched_at": "2026-11-17T10:00:00Z", "size_bytes": 187_654_321});
794 let listed = json!({"reply": "downloads", "id": 5, "downloads": [image.clone()]});
795 let downloads: Reply = serde_json::from_value(listed.clone()).unwrap();
796 assert_eq!(round_trip(&downloads), listed);
797 assert_eq!(downloads.id(), Some(5));
798 let removed = json!({"reply": "downloads_removed", "id": 6, "removed": [
799 {"id": 7, "outcome": "failed", "reason": "in use", "download": image},
800 {"id": 8, "outcome": "not_recorded"}
801 ]});
802 let outcomes: Reply = serde_json::from_value(removed.clone()).unwrap();
803 assert_eq!(round_trip(&outcomes), removed);
804 }
805
806 #[test]
807 fn a_reached_console_s_secrets_travel_but_never_show() {
808 let reached = ReachedConsole {
809 machine: "pve".into(),
810 protocol: ConsoleProtocol::Vnc,
811 endpoint: ConsoleEndpoint::ProxmoxVnc {
812 websocket: "wss://server/vnc?ticket=t0p".into(),
813 port: 5900,
814 ticket: "t0p".into(),
815 header: "Authorization".into(),
816 authorization: "PVEAPIToken=hunter2".into(),
817 insecure: false,
818 },
819 user: None,
820 password: Some("t0p".into()),
821 note: None,
822 tunnelled: false,
823 };
824 let frame = round_trip(&Reply::Console {
825 id: 9,
826 console: Box::new(reached.clone()),
827 });
828 assert_eq!(
829 (&frame["console"]["endpoint"]["at"], &frame["console"]["password"]),
830 (&json!("proxmox_vnc"), &json!("t0p"))
831 );
832 let shown = format!("{reached:?}");
833 assert!(!shown.contains("t0p") && !shown.contains("hunter2"), "{shown}");
834 let loopback = ConsoleEndpoint::Loopback {
835 address: SocketAddr::from(([127, 0, 0, 1], 5901)),
836 };
837 assert_eq!(serde_json::to_value(&loopback).unwrap(), json!({"at": "loopback", "address": "127.0.0.1:5901"}));
838 }
839
840 #[test]
841 fn the_frames_every_protocol_keeps_read_as_written() {
842 let hello = r#"{"id":0,"cmd":"hello","protocol":7}"#;
843 assert_eq!(serde_json::from_str::<Request>(hello).unwrap().command, Command::Hello { protocol: 7 });
844 assert_eq!(
845 round_trip(&Request {
846 id: 3,
847 command: Command::ShutdownIfIdle,
848 }),
849 json!({"id": 3, "cmd": "shutdown_if_idle"})
850 );
851 let hello_reply = round_trip(&Reply::Hello {
852 id: 0,
853 protocol: 7,
854 version: "9.0.0".into(),
855 });
856 assert_eq!(hello_reply, json!({"reply": "hello", "id": 0, "protocol": 7, "version": "9.0.0"}));
857 let busy = round_trip(&Reply::Busy {
858 id: 3,
859 operations: vec![OperationId(4), OperationId(9)],
860 });
861 assert_eq!(busy, json!({"reply": "busy", "id": 3, "operations": [4, 9]}));
862 assert_eq!(round_trip(&Reply::Ok { id: 3 }), json!({"reply": "ok", "id": 3}));
863 }
864}