Skip to main content

subc_client_rs/consumer/
supervisor_ops.rs

1//! Typed channel-0 calls for the supervisor's read and lifecycle operations:
2//! cached health, a fresh health probe, provenance, routes, retained stderr
3//! and exits, the server description, restart, stop and start, and the
4//! checked rescan that previews or applies a config.
5//!
6//! Each attempt sends one `ClientControlRequest` and decodes the matching
7//! `ClientControlResponse` variant. A daemon refusal comes back as
8//! [`CallError::Module`], so its code is readable through [`CallError::code`].
9//!
10//! Reads are retried on transport failures until the consumer's call deadline,
11//! like [`SubcConsumer::supervisor_list`]: sending a read twice changes
12//! nothing. Restart and enable/disable are sent once and never retried, because
13//! a request whose outcome is unknown may already have restarted or stopped the
14//! module, and repeating it would do so a second time.
15
16use subc_control::{
17    CapabilityRequirementStatus, ClientControlRequest, ClientControlResponse, RescanExpect,
18    SupervisorDaemonProvenance, SupervisorHealthEntry, SupervisorModuleProvenance,
19    SupervisorRescanResult, SupervisorRouteModule,
20};
21use tokio::time::Instant;
22
23use super::{is_retryable_catalog_transport_error, CallError, SubcConsumer, TerminalFrame};
24
25/// The stored health records `supervisor.health` answers with.
26#[derive(Debug, Clone, PartialEq)]
27pub struct SupervisorHealthResponse {
28    pub generation: u64,
29    pub modules: Vec<SupervisorHealthEntry>,
30}
31
32/// Daemon and module provenance from `supervisor.provenance`.
33#[derive(Debug, Clone, PartialEq)]
34pub struct SupervisorProvenanceResponse {
35    pub daemon: SupervisorDaemonProvenance,
36    pub modules: Vec<SupervisorModuleProvenance>,
37}
38
39/// The daemon's description of itself from `server.describe`.
40#[derive(Debug, Clone, PartialEq)]
41pub struct ServerDescription {
42    pub protocol_ver: u8,
43    pub subc_ops: Vec<String>,
44    pub capabilities: Vec<String>,
45    pub connected_clients: u64,
46    pub counters: Option<serde_json::Value>,
47    pub build_git_sha: Option<String>,
48    pub build_lock_digest: Option<String>,
49    pub capability_requirements: Vec<CapabilityRequirementStatus>,
50    /// Absent from daemons that predate the field.
51    pub machine_id: Option<String>,
52    /// The configuration file the daemon reads, as the daemon names it (never
53    /// canonicalized). Absent when the daemon predates the field, was started
54    /// without a reloadable config file, or reads a relative path.
55    pub config_path: Option<std::path::PathBuf>,
56}
57
58/// A module's retained stderr from `supervisor.stderr_tail`.
59#[derive(Debug, Clone, PartialEq)]
60pub struct StderrTailResponse {
61    pub module_id: String,
62    pub tail: subc_control::StderrTail,
63}
64
65/// One module's fresh health probe from `supervisor.health_probe`: the
66/// module's whole metrics object, which the cached `supervisor.health` view
67/// may have replaced with a size marker.
68#[derive(Debug, Clone, PartialEq)]
69pub struct HealthProbeResponse {
70    pub module_id: String,
71    pub status: subc_protocol::session::HealthStatus,
72    pub detail: Option<String>,
73    pub metrics: Option<serde_json::Value>,
74}
75
76/// The daemon's acknowledgement of a lifecycle request: whether it changed
77/// anything. `applied: false` means the module was already in the requested
78/// state, not that the request failed (a failure is an error).
79#[derive(Debug, Clone, PartialEq, Eq)]
80pub struct SupervisorAck {
81    pub module_id: String,
82    pub applied: bool,
83}
84
85impl SubcConsumer {
86    /// Send one control request and return the daemon's decoded reply.
87    /// `retry` repeats transport failures until the call deadline; only reads
88    /// pass it.
89    async fn control_request(
90        &self,
91        request: &ClientControlRequest,
92        op: &str,
93        retry: bool,
94    ) -> Result<ClientControlResponse, CallError> {
95        let deadline = Instant::now() + self.shared.opts.call_timeout;
96        let body = serde_json::to_vec(request)
97            .map_err(|err| CallError::not_sent(format!("failed to encode {op}: {err}")))?;
98        let mut attempt = 0usize;
99        loop {
100            attempt = attempt.saturating_add(1);
101            match self
102                .shared
103                .control_call(body.clone(), deadline, false, None)
104                .await
105            {
106                Ok(TerminalFrame::Response { body, .. }) => {
107                    return serde_json::from_slice::<ClientControlResponse>(&body).map_err(|err| {
108                        CallError::invalid_response(format!(
109                            "failed to decode {op} response: {err}"
110                        ))
111                    });
112                }
113                Ok(TerminalFrame::Error { body, .. }) => return Err(CallError::Module(body)),
114                Ok(TerminalFrame::StreamEnd) => {
115                    return Err(CallError::invalid_response(format!(
116                        "{op} returned StreamEnd"
117                    )));
118                }
119                Err(err)
120                    if retry
121                        && is_retryable_catalog_transport_error(&err)
122                        && Instant::now() < deadline =>
123                {
124                    let delay = self.shared.jittered(
125                        self.shared
126                            .opts
127                            .reconnect_backoff
128                            .delay_after_attempt(attempt),
129                    );
130                    self.shared.sleep_until_retry(deadline, delay).await?;
131                }
132                Err(err) => return Err(err),
133            }
134        }
135    }
136
137    /// The supervisor's stored health record for every module
138    /// (`supervisor.health`). Answered from the daemon's cache; nothing is
139    /// probed.
140    pub async fn supervisor_health(&self) -> Result<SupervisorHealthResponse, CallError> {
141        const OP: &str = "supervisor.health";
142        match self
143            .control_request(&ClientControlRequest::SupervisorHealth {}, OP, true)
144            .await?
145        {
146            ClientControlResponse::SupervisorHealth {
147                generation,
148                modules,
149            } => Ok(SupervisorHealthResponse {
150                generation,
151                modules,
152            }),
153            _ => Err(unexpected(OP)),
154        }
155    }
156
157    /// Daemon and module provenance (`supervisor.provenance`), for every
158    /// module or only `module_id`.
159    pub async fn supervisor_provenance(
160        &self,
161        module_id: Option<String>,
162    ) -> Result<SupervisorProvenanceResponse, CallError> {
163        const OP: &str = "supervisor.provenance";
164        match self
165            .control_request(
166                &ClientControlRequest::SupervisorProvenance { module_id },
167                OP,
168                true,
169            )
170            .await?
171        {
172            ClientControlResponse::SupervisorProvenance { daemon, modules } => {
173                Ok(SupervisorProvenanceResponse { daemon, modules })
174            }
175            _ => Err(unexpected(OP)),
176        }
177    }
178
179    /// The live routes each module serves (`supervisor.routes`): every
180    /// module's when `module_id` is `None`, otherwise only that module's.
181    pub async fn supervisor_routes(
182        &self,
183        module_id: Option<String>,
184    ) -> Result<Vec<SupervisorRouteModule>, CallError> {
185        const OP: &str = "supervisor.routes";
186        match self
187            .control_request(
188                &ClientControlRequest::SupervisorRoutes { module_id },
189                OP,
190                true,
191            )
192            .await?
193        {
194            ClientControlResponse::SupervisorRoutes { modules } => Ok(modules),
195            _ => Err(unexpected(OP)),
196        }
197    }
198
199    /// The module's retained stderr (`supervisor.stderr_tail`), oldest entry
200    /// first, capped by `max_lines` and `max_bytes` when given.
201    pub async fn supervisor_stderr_tail(
202        &self,
203        module_id: impl Into<String>,
204        max_lines: Option<u32>,
205        max_bytes: Option<u32>,
206    ) -> Result<StderrTailResponse, CallError> {
207        const OP: &str = "supervisor.stderr_tail";
208        match self
209            .control_request(
210                &ClientControlRequest::SupervisorStderrTail {
211                    module_id: module_id.into(),
212                    max_lines,
213                    max_bytes,
214                },
215                OP,
216                true,
217            )
218            .await?
219        {
220            ClientControlResponse::SupervisorStderrTail { module_id, tail } => {
221                Ok(StderrTailResponse { module_id, tail })
222            }
223            _ => Err(unexpected(OP)),
224        }
225    }
226
227    /// Asks one module for its health now (`supervisor.health_probe`), the
228    /// probe `ck health <id>` sends. Unlike the cached view, the metrics are
229    /// complete.
230    pub async fn supervisor_health_probe(
231        &self,
232        module_id: impl Into<String>,
233    ) -> Result<HealthProbeResponse, CallError> {
234        const OP: &str = "supervisor.health_probe";
235        match self
236            .control_request(
237                &ClientControlRequest::SupervisorHealthProbe {
238                    module_id: module_id.into(),
239                },
240                OP,
241                true,
242            )
243            .await?
244        {
245            ClientControlResponse::SupervisorHealthProbe {
246                module_id,
247                status,
248                detail,
249                metrics,
250            } => Ok(HealthProbeResponse {
251                module_id,
252                status,
253                detail,
254                metrics,
255            }),
256            _ => Err(unexpected(OP)),
257        }
258    }
259
260    /// The module's retained process exits (`supervisor.terminals`), with
261    /// what the supervisor did after each.
262    pub async fn supervisor_terminals(
263        &self,
264        module_id: impl Into<String>,
265    ) -> Result<subc_control::TerminalHistory, CallError> {
266        const OP: &str = "supervisor.terminals";
267        match self
268            .control_request(
269                &ClientControlRequest::SupervisorTerminals {
270                    module_id: module_id.into(),
271                },
272                OP,
273                true,
274            )
275            .await?
276        {
277            ClientControlResponse::SupervisorTerminals { terminals, .. } => Ok(terminals),
278            _ => Err(unexpected(OP)),
279        }
280    }
281
282    /// The daemon's description of itself (`server.describe`).
283    pub async fn server_describe(&self) -> Result<ServerDescription, CallError> {
284        const OP: &str = "server.describe";
285        match self
286            .control_request(&ClientControlRequest::ServerDescribe {}, OP, true)
287            .await?
288        {
289            ClientControlResponse::ServerDescribe {
290                protocol_ver,
291                subc_ops,
292                capabilities,
293                connected_clients,
294                counters,
295                build_git_sha,
296                build_lock_digest,
297                capability_requirements,
298                machine_id,
299                config_path,
300            } => Ok(ServerDescription {
301                protocol_ver,
302                subc_ops,
303                capabilities,
304                connected_clients,
305                counters,
306                build_git_sha,
307                build_lock_digest,
308                capability_requirements,
309                machine_id,
310                config_path,
311            }),
312            _ => Err(unexpected(OP)),
313        }
314    }
315
316    /// Restart one module (`supervisor.restart`), the request `ck module
317    /// restart` sends. `drain_timeout_ms` overrides the module's drain budget
318    /// for this restart; `None` keeps the configured one. Sent once, never
319    /// retried.
320    pub async fn supervisor_restart(
321        &self,
322        module_id: impl Into<String>,
323        drain_timeout_ms: Option<u64>,
324    ) -> Result<SupervisorAck, CallError> {
325        let request = ClientControlRequest::SupervisorRestart {
326            module_id: module_id.into(),
327            drain_timeout_ms,
328        };
329        self.lifecycle(&request, "supervisor.restart").await
330    }
331
332    /// Sends `supervisor.set_enabled` for one module: `enabled: true` starts
333    /// it and `false` stops it, the same request `ck module start` and
334    /// `ck module stop` send. This method sends the request once and never
335    /// retries it.
336    pub async fn supervisor_set_enabled(
337        &self,
338        module_id: impl Into<String>,
339        enabled: bool,
340    ) -> Result<SupervisorAck, CallError> {
341        let request = ClientControlRequest::SupervisorSetEnabled {
342            module_id: module_id.into(),
343            enabled,
344        };
345        self.lifecycle(&request, "supervisor.set_enabled").await
346    }
347
348    /// Sends `supervisor.rescan_checked` and returns the daemon's rescan
349    /// result. With `preview: true` and the full candidate config text, the
350    /// daemon previews that text and writes nothing; the result carries what
351    /// each module would do and the `expect` value an apply must send. With
352    /// `preview: false` and that `expect`, the daemon applies its config file
353    /// only if the file and its staged state still match the preview. Any
354    /// other combination is refused by the daemon. A refusal, such as
355    /// `invalid_daemon_config` for a candidate the daemon can't load, comes
356    /// back as [`CallError::Module`].
357    ///
358    /// Send this only to a daemon whose `server.describe` lists
359    /// `rescan-candidate-preview/v1`. A preview is retried on transport
360    /// failures like the other reads; an apply is sent once and never retried,
361    /// because one whose outcome is unknown may already have applied.
362    pub async fn supervisor_rescan_checked(
363        &self,
364        preview: bool,
365        candidate: Option<String>,
366        expect: Option<RescanExpect>,
367    ) -> Result<SupervisorRescanResult, CallError> {
368        const OP: &str = "supervisor.rescan_checked";
369        let request = ClientControlRequest::SupervisorRescanChecked {
370            preview,
371            candidate,
372            expect,
373        };
374        match self.control_request(&request, OP, preview).await? {
375            ClientControlResponse::SupervisorRescan { result } => Ok(result),
376            _ => Err(unexpected(OP)),
377        }
378    }
379
380    async fn lifecycle(
381        &self,
382        request: &ClientControlRequest,
383        op: &str,
384    ) -> Result<SupervisorAck, CallError> {
385        match self.control_request(request, op, false).await? {
386            ClientControlResponse::SupervisorAck { module_id, applied } => {
387                Ok(SupervisorAck { module_id, applied })
388            }
389            _ => Err(unexpected(op)),
390        }
391    }
392}
393
394fn unexpected(op: &str) -> CallError {
395    CallError::invalid_response(format!("{op} returned an unexpected control response"))
396}
397
398#[cfg(test)]
399mod tests {
400    use std::path::PathBuf;
401    use std::sync::Arc;
402
403    use subc_control::{SupervisorHealthStatus, SupervisorRouteModule};
404    use subc_protocol::{ErrorBody, Flags, Frame, FrameType, Priority};
405    use tokio::sync::mpsc;
406
407    use super::super::{dispatch_frame, ConsumerOptions, Shared};
408    use super::*;
409
410    fn consumer() -> (
411        SubcConsumer,
412        Arc<Shared>,
413        mpsc::Receiver<super::super::WriteCommand>,
414    ) {
415        let shared = Arc::new(Shared::new(
416            PathBuf::from("/tmp/does-not-exist"),
417            ConsumerOptions::default(),
418        ));
419        let (writer, rx) = mpsc::channel(1);
420        shared.lock_inner().writer = Some(writer);
421        shared.lock_inner().daemon_ver = "0.39.0".into();
422        (
423            SubcConsumer {
424                shared: Arc::clone(&shared),
425            },
426            shared,
427            rx,
428        )
429    }
430
431    fn frame(kind: FrameType, corr: u64, body: Vec<u8>) -> Frame {
432        Frame::build(
433            kind,
434            Flags::new(false, Priority::Interactive, false),
435            0,
436            0,
437            corr,
438            body,
439        )
440        .unwrap()
441    }
442
443    #[tokio::test]
444    async fn health_sends_its_op_and_returns_the_entries() {
445        let (consumer, shared, mut rx) = consumer();
446        let call = tokio::spawn(async move { consumer.supervisor_health().await });
447        let command = rx.recv().await.expect("a channel-0 request");
448        assert_eq!(command.frame.header.channel, 0);
449        let body: serde_json::Value = serde_json::from_slice(&command.frame.body).unwrap();
450        assert_eq!(body["op"], "supervisor.health");
451        let reply = serde_json::json!({
452            "op": "supervisor.health",
453            "generation": 7,
454            "modules": [{
455                "module_id": "broca",
456                "status": "degraded",
457                "detail": "provider throttled",
458                "metrics": {"headline": ["runs"], "runs": 3},
459                "consecutive_failures": 0
460            }]
461        });
462        let corr = command.frame.header.corr;
463        let reply = serde_json::to_vec(&reply).unwrap();
464        assert!(dispatch_frame(&shared, 1, frame(FrameType::Response, corr, reply)).await);
465        let health = call.await.unwrap().unwrap();
466        assert_eq!(health.generation, 7);
467        assert_eq!(health.modules[0].status, SupervisorHealthStatus::Degraded);
468        assert_eq!(
469            health.modules[0].detail.as_deref(),
470            Some("provider throttled")
471        );
472    }
473
474    #[tokio::test]
475    async fn routes_and_describe_decode_their_replies() {
476        let (consumer, shared, mut rx) = consumer();
477        let consumer = Arc::new(consumer);
478        let c = Arc::clone(&consumer);
479        let call = tokio::spawn(async move { c.supervisor_routes(Some("broca".into())).await });
480        let command = rx.recv().await.unwrap();
481        let body: serde_json::Value = serde_json::from_slice(&command.frame.body).unwrap();
482        assert_eq!(body["op"], "supervisor.routes");
483        assert_eq!(body["module_id"], "broca");
484        let reply = serde_json::to_vec(&ClientControlResponse::SupervisorRoutes {
485            modules: vec![SupervisorRouteModule {
486                module_id: "broca".into(),
487                routes: vec![],
488            }],
489        })
490        .unwrap();
491        let corr = command.frame.header.corr;
492        assert!(dispatch_frame(&shared, 1, frame(FrameType::Response, corr, reply)).await);
493        assert_eq!(call.await.unwrap().unwrap()[0].module_id, "broca");
494
495        let c = Arc::clone(&consumer);
496        let call = tokio::spawn(async move { c.server_describe().await });
497        let command = rx.recv().await.unwrap();
498        let reply = serde_json::json!({
499            "op": "server.describe",
500            "protocol_ver": 1,
501            "subc_ops": [],
502            "capabilities": [],
503            "connected_clients": 12,
504            "machine_id": "4f1a9c2e7b3d40c8"
505        });
506        let corr = command.frame.header.corr;
507        let reply = serde_json::to_vec(&reply).unwrap();
508        assert!(dispatch_frame(&shared, 1, frame(FrameType::Response, corr, reply)).await);
509        let described = call.await.unwrap().unwrap();
510        assert_eq!(described.connected_clients, 12);
511        assert_eq!(described.machine_id.as_deref(), Some("4f1a9c2e7b3d40c8"));
512        assert_eq!(described.config_path, None, "an older daemon sends no path");
513
514        let c = Arc::clone(&consumer);
515        let call = tokio::spawn(async move { c.server_describe().await });
516        let command = rx.recv().await.unwrap();
517        let reply = serde_json::json!({
518            "op": "server.describe",
519            "protocol_ver": 1,
520            "subc_ops": [],
521            "capabilities": ["rescan-candidate-preview/v1"],
522            "connected_clients": 1,
523            "config_path": "/Users/alex/.config/cortexkit/subc.jsonc"
524        });
525        let corr = command.frame.header.corr;
526        let reply = serde_json::to_vec(&reply).unwrap();
527        assert!(dispatch_frame(&shared, 1, frame(FrameType::Response, corr, reply)).await);
528        let described = call.await.unwrap().unwrap();
529        assert_eq!(
530            described.config_path.as_deref(),
531            Some(std::path::Path::new(
532                "/Users/alex/.config/cortexkit/subc.jsonc"
533            ))
534        );
535    }
536
537    #[tokio::test]
538    async fn restart_returns_the_ack_and_a_refusal_keeps_its_code() {
539        let (consumer, shared, mut rx) = consumer();
540        let consumer = Arc::new(consumer);
541        let c = Arc::clone(&consumer);
542        let call = tokio::spawn(async move { c.supervisor_restart("broca", None).await });
543        let command = rx.recv().await.unwrap();
544        let body: serde_json::Value = serde_json::from_slice(&command.frame.body).unwrap();
545        assert_eq!(body["op"], "supervisor.restart");
546        assert_eq!(body["module_id"], "broca");
547        assert!(body.get("drain_timeout_ms").is_none());
548        let reply = serde_json::to_vec(&ClientControlResponse::SupervisorAck {
549            module_id: "broca".into(),
550            applied: true,
551        })
552        .unwrap();
553        let corr = command.frame.header.corr;
554        assert!(dispatch_frame(&shared, 1, frame(FrameType::Response, corr, reply)).await);
555        assert_eq!(
556            call.await.unwrap().unwrap(),
557            SupervisorAck {
558                module_id: "broca".into(),
559                applied: true
560            }
561        );
562
563        let c = Arc::clone(&consumer);
564        let call = tokio::spawn(async move { c.supervisor_set_enabled("broca", false).await });
565        let command = rx.recv().await.unwrap();
566        let body: serde_json::Value = serde_json::from_slice(&command.frame.body).unwrap();
567        assert_eq!(body["op"], "supervisor.set_enabled");
568        assert_eq!(body["enabled"], false);
569        let refusal = serde_json::to_vec(&ErrorBody {
570            code: "module_reserved".into(),
571            message: "refused by the test".into(),
572            detail: None,
573        })
574        .unwrap();
575        let corr = command.frame.header.corr;
576        assert!(dispatch_frame(&shared, 1, frame(FrameType::Error, corr, refusal)).await);
577        assert_eq!(
578            call.await.unwrap().unwrap_err().code(),
579            Some("module_reserved")
580        );
581    }
582
583    #[tokio::test]
584    async fn health_probe_and_terminals_decode_their_replies() {
585        let (consumer, shared, mut rx) = consumer();
586        let consumer = Arc::new(consumer);
587        let c = Arc::clone(&consumer);
588        let call = tokio::spawn(async move { c.supervisor_health_probe("aft").await });
589        let command = rx.recv().await.unwrap();
590        let body: serde_json::Value = serde_json::from_slice(&command.frame.body).unwrap();
591        assert_eq!(body["op"], "supervisor.health_probe");
592        assert_eq!(body["module_id"], "aft");
593        let reply = serde_json::json!({
594            "op": "supervisor.health_probe", "module_id": "aft", "status": "ok",
595            "metrics": {"headline": ["files"], "files": 12}
596        });
597        let corr = command.frame.header.corr;
598        let reply = serde_json::to_vec(&reply).unwrap();
599        assert!(dispatch_frame(&shared, 1, frame(FrameType::Response, corr, reply)).await);
600        let probe = call.await.unwrap().unwrap();
601        assert_eq!(probe.metrics.unwrap()["files"], 12);
602
603        let c = Arc::clone(&consumer);
604        let call = tokio::spawn(async move { c.supervisor_terminals("aft").await });
605        let command = rx.recv().await.unwrap();
606        let body: serde_json::Value = serde_json::from_slice(&command.frame.body).unwrap();
607        assert_eq!(body["op"], "supervisor.terminals");
608        let reply = serde_json::json!({
609            "op": "supervisor.terminals", "module_id": "aft",
610            "daemon_started_at_ms": 1000,
611            "entries": [{"exit_code": 0, "at_ms": 2000, "disposition": "restarting"}]
612        });
613        let corr = command.frame.header.corr;
614        let reply = serde_json::to_vec(&reply).unwrap();
615        assert!(dispatch_frame(&shared, 1, frame(FrameType::Response, corr, reply)).await);
616        let history = call.await.unwrap().unwrap();
617        assert_eq!(history.entries.len(), 1);
618        assert_eq!(history.entries[0].at_ms, 2000);
619    }
620
621    #[tokio::test]
622    async fn stderr_tail_carries_its_caps_and_decodes_lines() {
623        let (consumer, shared, mut rx) = consumer();
624        let call = tokio::spawn(async move {
625            consumer
626                .supervisor_stderr_tail("broca", Some(200), None)
627                .await
628        });
629        let command = rx.recv().await.unwrap();
630        let body: serde_json::Value = serde_json::from_slice(&command.frame.body).unwrap();
631        assert_eq!(body["op"], "supervisor.stderr_tail");
632        assert_eq!(body["max_lines"], 200);
633        let reply = serde_json::json!({
634            "op": "supervisor.stderr_tail",
635            "module_id": "broca",
636            "capture": {"state": "captured"},
637            "entries": [
638                {"kind": "line", "text": "hello", "truncated": false, "at_ms": 1000}
639            ]
640        });
641        let corr = command.frame.header.corr;
642        let reply = serde_json::to_vec(&reply).unwrap();
643        assert!(dispatch_frame(&shared, 1, frame(FrameType::Response, corr, reply)).await);
644        let tail = call.await.unwrap().unwrap();
645        assert_eq!(tail.module_id, "broca");
646        assert_eq!(tail.tail.entries.len(), 1);
647    }
648
649    fn expect() -> RescanExpect {
650        RescanExpect {
651            config_sha256: "ab".repeat(32),
652            staged_generation: subc_control::StagedGeneration {
653                incarnation: "incarnation-1".into(),
654                counter: 4,
655            },
656        }
657    }
658
659    /// The request on the wire is exactly subc-control's
660    /// `SupervisorRescanChecked` variant with the arguments given, for both
661    /// the preview and the apply form.
662    #[tokio::test]
663    async fn rescan_checked_sends_the_checked_variant_with_its_arguments() {
664        let (consumer, shared, mut rx) = consumer();
665        let consumer = Arc::new(consumer);
666        for (preview, candidate, expect) in [
667            (true, Some("{\"modules\": {}}".to_string()), None),
668            (false, None, Some(expect())),
669        ] {
670            let c = Arc::clone(&consumer);
671            let (sent_candidate, sent_expect) = (candidate.clone(), expect.clone());
672            let call = tokio::spawn(async move {
673                c.supervisor_rescan_checked(preview, sent_candidate, sent_expect)
674                    .await
675            });
676            let command = rx.recv().await.unwrap();
677            assert_eq!(command.frame.header.channel, 0);
678            let sent: ClientControlRequest = serde_json::from_slice(&command.frame.body).unwrap();
679            assert_eq!(
680                sent,
681                ClientControlRequest::SupervisorRescanChecked {
682                    preview,
683                    candidate,
684                    expect,
685                }
686            );
687            let body: serde_json::Value = serde_json::from_slice(&command.frame.body).unwrap();
688            assert_eq!(body["op"], "supervisor.rescan_checked");
689            let reply = serde_json::to_vec(&serde_json::json!({
690                "op": "supervisor.rescan",
691                "added": [], "removed": [], "changed_pending_reload": [], "unchanged": 0
692            }))
693            .unwrap();
694            let corr = command.frame.header.corr;
695            assert!(dispatch_frame(&shared, 1, frame(FrameType::Response, corr, reply)).await);
696            call.await.unwrap().unwrap();
697        }
698    }
699
700    /// Drops the waiting caller's reply channel for `command`, as a transport
701    /// failure before any reply does. The request may already have been
702    /// written, so the caller sees `OutcomeUnknown`.
703    fn lose_reply(shared: &Shared, command: &super::super::WriteCommand) {
704        let key = command.pending.expect("a request waits for its reply");
705        assert!(shared.lock_inner().pending.remove(&key).is_some());
706    }
707
708    /// A preview changes nothing, so a transport failure is retried with a
709    /// second request. An apply whose outcome is unknown may already have
710    /// applied, so it is sent once and the failure is returned.
711    #[tokio::test]
712    async fn rescan_checked_retries_a_preview_but_sends_an_apply_once() {
713        let (consumer, shared, mut rx) = consumer();
714        let consumer = Arc::new(consumer);
715        let c = Arc::clone(&consumer);
716        let call = tokio::spawn(async move {
717            c.supervisor_rescan_checked(true, Some("{}".into()), None)
718                .await
719        });
720        let first = rx.recv().await.unwrap();
721        lose_reply(&shared, &first);
722        let second = tokio::time::timeout(std::time::Duration::from_secs(5), rx.recv())
723            .await
724            .expect("a preview is sent again after a transport failure")
725            .unwrap();
726        assert_ne!(second.frame.header.corr, first.frame.header.corr);
727        assert_eq!(second.frame.body, first.frame.body);
728        let reply = serde_json::to_vec(&serde_json::json!({
729            "op": "supervisor.rescan",
730            "added": [], "removed": [], "changed_pending_reload": [], "unchanged": 0,
731            "preview": true
732        }))
733        .unwrap();
734        let corr = second.frame.header.corr;
735        assert!(dispatch_frame(&shared, 1, frame(FrameType::Response, corr, reply)).await);
736        assert!(call.await.unwrap().unwrap().preview);
737
738        let c = Arc::clone(&consumer);
739        let call = tokio::spawn(async move {
740            c.supervisor_rescan_checked(false, None, Some(expect()))
741                .await
742        });
743        let only = rx.recv().await.unwrap();
744        lose_reply(&shared, &only);
745        let err = call.await.unwrap().unwrap_err();
746        assert!(
747            !err.is_not_sent() && err.outcome_cause().is_some(),
748            "{err:?}"
749        );
750        assert!(
751            rx.try_recv().is_err(),
752            "an apply is never sent a second time"
753        );
754    }
755
756    /// A preview reply decodes with its module actions, earlier-pending list,
757    /// diagnostics and `expect`; a refusal keeps its code and message.
758    #[tokio::test]
759    async fn rescan_checked_decodes_the_preview_and_keeps_a_refusal_typed() {
760        let (consumer, shared, mut rx) = consumer();
761        let consumer = Arc::new(consumer);
762        let c = Arc::clone(&consumer);
763        let call = tokio::spawn(async move {
764            c.supervisor_rescan_checked(true, Some("{}".into()), None)
765                .await
766        });
767        let command = rx.recv().await.unwrap();
768        let reply = serde_json::json!({
769            "op": "supervisor.rescan",
770            "added": [], "removed": [], "changed_pending_reload": ["broca"],
771            "unchanged": 3, "preview": true,
772            "restart_required": ["storage"],
773            "capability_warnings": ["memory.read has no provider"],
774            "module_actions": [{
775                "module_id": "broca", "action": "restart", "changed": ["environment"],
776                "drain_timeout_ms": 30000,
777                "busy_gauges": [{"gauge": "runs_in_flight", "value": 3}]
778            }],
779            "earlier_pending": ["wernicke"],
780            "expect": serde_json::to_value(expect()).unwrap()
781        });
782        let corr = command.frame.header.corr;
783        let reply = serde_json::to_vec(&reply).unwrap();
784        assert!(dispatch_frame(&shared, 1, frame(FrameType::Response, corr, reply)).await);
785        let result = call.await.unwrap().unwrap();
786        assert!(result.preview);
787        assert_eq!(result.restart_required, vec!["storage"]);
788        assert_eq!(
789            result.capability_warnings,
790            vec!["memory.read has no provider"]
791        );
792        assert_eq!(result.earlier_pending, vec!["wernicke"]);
793        assert_eq!(result.expect, Some(expect()));
794        let action = &result.module_actions[0];
795        assert_eq!(action.module_id, "broca");
796        assert_eq!(action.action, subc_control::RescanModuleActionKind::Restart);
797        assert_eq!(action.changed, vec!["environment"]);
798        assert_eq!(action.drain_timeout_ms, Some(30000));
799        assert_eq!(action.busy_gauges[0].gauge, "runs_in_flight");
800        assert_eq!(action.busy_gauges[0].value, Some(serde_json::json!(3)));
801
802        let c = Arc::clone(&consumer);
803        let call = tokio::spawn(async move {
804            c.supervisor_rescan_checked(true, Some("{".into()), None)
805                .await
806        });
807        let command = rx.recv().await.unwrap();
808        let refusal = serde_json::to_vec(&ErrorBody {
809            code: "invalid_daemon_config".into(),
810            message: "supervisor rescan rejected daemon config: unexpected end".into(),
811            detail: None,
812        })
813        .unwrap();
814        let corr = command.frame.header.corr;
815        assert!(dispatch_frame(&shared, 1, frame(FrameType::Error, corr, refusal)).await);
816        match call.await.unwrap().unwrap_err() {
817            CallError::Module(body) => {
818                assert_eq!(body.code, "invalid_daemon_config");
819                assert_eq!(
820                    body.message,
821                    "supervisor rescan rejected daemon config: unexpected end"
822                );
823            }
824            other => panic!("expected a typed refusal, got {other:?}"),
825        }
826    }
827}