subc-client-rs 0.30.8

Shared serve + consume client for Rust subc modules.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
//! Typed channel-0 calls for the supervisor's read and lifecycle operations:
//! cached health, a fresh health probe, provenance, routes, retained stderr
//! and exits, the server description, and restart, stop and start.
//!
//! Each attempt sends one `ClientControlRequest` and decodes the matching
//! `ClientControlResponse` variant. A daemon refusal comes back as
//! [`CallError::Module`], so its code is readable through [`CallError::code`].
//!
//! Reads are retried on transport failures until the consumer's call deadline,
//! like [`SubcConsumer::supervisor_list`]: sending a read twice changes
//! nothing. Restart and enable/disable are sent once and never retried, because
//! a request whose outcome is unknown may already have restarted or stopped the
//! module, and repeating it would do so a second time.

use subc_control::{
    CapabilityRequirementStatus, ClientControlRequest, ClientControlResponse,
    SupervisorDaemonProvenance, SupervisorHealthEntry, SupervisorModuleProvenance,
    SupervisorRouteModule,
};
use tokio::time::Instant;

use super::{is_retryable_catalog_transport_error, CallError, SubcConsumer, TerminalFrame};

/// The stored health records `supervisor.health` answers with.
#[derive(Debug, Clone, PartialEq)]
pub struct SupervisorHealthResponse {
    pub generation: u64,
    pub modules: Vec<SupervisorHealthEntry>,
}

/// Daemon and module provenance from `supervisor.provenance`.
#[derive(Debug, Clone, PartialEq)]
pub struct SupervisorProvenanceResponse {
    pub daemon: SupervisorDaemonProvenance,
    pub modules: Vec<SupervisorModuleProvenance>,
}

/// The daemon's description of itself from `server.describe`.
#[derive(Debug, Clone, PartialEq)]
pub struct ServerDescription {
    pub protocol_ver: u8,
    pub subc_ops: Vec<String>,
    pub capabilities: Vec<String>,
    pub connected_clients: u64,
    pub counters: Option<serde_json::Value>,
    pub build_git_sha: Option<String>,
    pub build_lock_digest: Option<String>,
    pub capability_requirements: Vec<CapabilityRequirementStatus>,
    /// Absent from daemons that predate the field.
    pub machine_id: Option<String>,
    /// The configuration file the daemon reads, as the daemon names it (never
    /// canonicalized). Absent when the daemon predates the field, was started
    /// without a reloadable config file, or reads a relative path.
    pub config_path: Option<std::path::PathBuf>,
}

/// A module's retained stderr from `supervisor.stderr_tail`.
#[derive(Debug, Clone, PartialEq)]
pub struct StderrTailResponse {
    pub module_id: String,
    pub tail: subc_control::StderrTail,
}

/// One module's fresh health probe from `supervisor.health_probe`: the
/// module's whole metrics object, which the cached `supervisor.health` view
/// may have replaced with a size marker.
#[derive(Debug, Clone, PartialEq)]
pub struct HealthProbeResponse {
    pub module_id: String,
    pub status: subc_protocol::session::HealthStatus,
    pub detail: Option<String>,
    pub metrics: Option<serde_json::Value>,
}

/// The daemon's acknowledgement of a lifecycle request: whether it changed
/// anything. `applied: false` means the module was already in the requested
/// state, not that the request failed (a failure is an error).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SupervisorAck {
    pub module_id: String,
    pub applied: bool,
}

impl SubcConsumer {
    /// Send one control request and return the daemon's decoded reply.
    /// `retry` repeats transport failures until the call deadline; only reads
    /// pass it.
    async fn control_request(
        &self,
        request: &ClientControlRequest,
        op: &str,
        retry: bool,
    ) -> Result<ClientControlResponse, CallError> {
        let deadline = Instant::now() + self.shared.opts.call_timeout;
        let body = serde_json::to_vec(request)
            .map_err(|err| CallError::not_sent(format!("failed to encode {op}: {err}")))?;
        let mut attempt = 0usize;
        loop {
            attempt = attempt.saturating_add(1);
            match self
                .shared
                .control_call(body.clone(), deadline, false, None)
                .await
            {
                Ok(TerminalFrame::Response { body, .. }) => {
                    return serde_json::from_slice::<ClientControlResponse>(&body).map_err(|err| {
                        CallError::not_sent(format!("failed to decode {op} response: {err}"))
                    });
                }
                Ok(TerminalFrame::Error { body, .. }) => return Err(CallError::Module(body)),
                Ok(TerminalFrame::StreamEnd) => {
                    return Err(CallError::not_sent(format!("{op} returned StreamEnd")));
                }
                Err(err)
                    if retry
                        && is_retryable_catalog_transport_error(&err)
                        && Instant::now() < deadline =>
                {
                    let delay = self.shared.jittered(
                        self.shared
                            .opts
                            .reconnect_backoff
                            .delay_after_attempt(attempt),
                    );
                    self.shared.sleep_until_retry(deadline, delay).await?;
                }
                Err(err) => return Err(err),
            }
        }
    }

    /// The supervisor's stored health record for every module
    /// (`supervisor.health`). Answered from the daemon's cache; nothing is
    /// probed.
    pub async fn supervisor_health(&self) -> Result<SupervisorHealthResponse, CallError> {
        const OP: &str = "supervisor.health";
        match self
            .control_request(&ClientControlRequest::SupervisorHealth {}, OP, true)
            .await?
        {
            ClientControlResponse::SupervisorHealth {
                generation,
                modules,
            } => Ok(SupervisorHealthResponse {
                generation,
                modules,
            }),
            _ => Err(unexpected(OP)),
        }
    }

    /// Daemon and module provenance (`supervisor.provenance`), for every
    /// module or only `module_id`.
    pub async fn supervisor_provenance(
        &self,
        module_id: Option<String>,
    ) -> Result<SupervisorProvenanceResponse, CallError> {
        const OP: &str = "supervisor.provenance";
        match self
            .control_request(
                &ClientControlRequest::SupervisorProvenance { module_id },
                OP,
                true,
            )
            .await?
        {
            ClientControlResponse::SupervisorProvenance { daemon, modules } => {
                Ok(SupervisorProvenanceResponse { daemon, modules })
            }
            _ => Err(unexpected(OP)),
        }
    }

    /// The live routes each module serves (`supervisor.routes`): every
    /// module's when `module_id` is `None`, otherwise only that module's.
    pub async fn supervisor_routes(
        &self,
        module_id: Option<String>,
    ) -> Result<Vec<SupervisorRouteModule>, CallError> {
        const OP: &str = "supervisor.routes";
        match self
            .control_request(
                &ClientControlRequest::SupervisorRoutes { module_id },
                OP,
                true,
            )
            .await?
        {
            ClientControlResponse::SupervisorRoutes { modules } => Ok(modules),
            _ => Err(unexpected(OP)),
        }
    }

    /// The module's retained stderr (`supervisor.stderr_tail`), oldest entry
    /// first, capped by `max_lines` and `max_bytes` when given.
    pub async fn supervisor_stderr_tail(
        &self,
        module_id: impl Into<String>,
        max_lines: Option<u32>,
        max_bytes: Option<u32>,
    ) -> Result<StderrTailResponse, CallError> {
        const OP: &str = "supervisor.stderr_tail";
        match self
            .control_request(
                &ClientControlRequest::SupervisorStderrTail {
                    module_id: module_id.into(),
                    max_lines,
                    max_bytes,
                },
                OP,
                true,
            )
            .await?
        {
            ClientControlResponse::SupervisorStderrTail { module_id, tail } => {
                Ok(StderrTailResponse { module_id, tail })
            }
            _ => Err(unexpected(OP)),
        }
    }

    /// Asks one module for its health now (`supervisor.health_probe`), the
    /// probe `ck health <id>` sends. Unlike the cached view, the metrics are
    /// complete.
    pub async fn supervisor_health_probe(
        &self,
        module_id: impl Into<String>,
    ) -> Result<HealthProbeResponse, CallError> {
        const OP: &str = "supervisor.health_probe";
        match self
            .control_request(
                &ClientControlRequest::SupervisorHealthProbe {
                    module_id: module_id.into(),
                },
                OP,
                true,
            )
            .await?
        {
            ClientControlResponse::SupervisorHealthProbe {
                module_id,
                status,
                detail,
                metrics,
            } => Ok(HealthProbeResponse {
                module_id,
                status,
                detail,
                metrics,
            }),
            _ => Err(unexpected(OP)),
        }
    }

    /// The module's retained process exits (`supervisor.terminals`), with
    /// what the supervisor did after each.
    pub async fn supervisor_terminals(
        &self,
        module_id: impl Into<String>,
    ) -> Result<subc_control::TerminalHistory, CallError> {
        const OP: &str = "supervisor.terminals";
        match self
            .control_request(
                &ClientControlRequest::SupervisorTerminals {
                    module_id: module_id.into(),
                },
                OP,
                true,
            )
            .await?
        {
            ClientControlResponse::SupervisorTerminals { terminals, .. } => Ok(terminals),
            _ => Err(unexpected(OP)),
        }
    }

    /// The daemon's description of itself (`server.describe`).
    pub async fn server_describe(&self) -> Result<ServerDescription, CallError> {
        const OP: &str = "server.describe";
        match self
            .control_request(&ClientControlRequest::ServerDescribe {}, OP, true)
            .await?
        {
            ClientControlResponse::ServerDescribe {
                protocol_ver,
                subc_ops,
                capabilities,
                connected_clients,
                counters,
                build_git_sha,
                build_lock_digest,
                capability_requirements,
                machine_id,
                config_path,
            } => Ok(ServerDescription {
                protocol_ver,
                subc_ops,
                capabilities,
                connected_clients,
                counters,
                build_git_sha,
                build_lock_digest,
                capability_requirements,
                machine_id,
                config_path,
            }),
            _ => Err(unexpected(OP)),
        }
    }

    /// Restart one module (`supervisor.restart`), the request `ck module
    /// restart` sends. `drain_timeout_ms` overrides the module's drain budget
    /// for this restart; `None` keeps the configured one. Sent once, never
    /// retried.
    pub async fn supervisor_restart(
        &self,
        module_id: impl Into<String>,
        drain_timeout_ms: Option<u64>,
    ) -> Result<SupervisorAck, CallError> {
        let request = ClientControlRequest::SupervisorRestart {
            module_id: module_id.into(),
            drain_timeout_ms,
        };
        self.lifecycle(&request, "supervisor.restart").await
    }

    /// Sends `supervisor.set_enabled` for one module: `enabled: true` starts
    /// it and `false` stops it, the same request `ck module start` and
    /// `ck module stop` send. This method sends the request once and never
    /// retries it.
    pub async fn supervisor_set_enabled(
        &self,
        module_id: impl Into<String>,
        enabled: bool,
    ) -> Result<SupervisorAck, CallError> {
        let request = ClientControlRequest::SupervisorSetEnabled {
            module_id: module_id.into(),
            enabled,
        };
        self.lifecycle(&request, "supervisor.set_enabled").await
    }

    async fn lifecycle(
        &self,
        request: &ClientControlRequest,
        op: &str,
    ) -> Result<SupervisorAck, CallError> {
        match self.control_request(request, op, false).await? {
            ClientControlResponse::SupervisorAck { module_id, applied } => {
                Ok(SupervisorAck { module_id, applied })
            }
            _ => Err(unexpected(op)),
        }
    }
}

fn unexpected(op: &str) -> CallError {
    CallError::not_sent(format!("{op} returned an unexpected control response"))
}

#[cfg(test)]
mod tests {
    use std::path::PathBuf;
    use std::sync::Arc;

    use subc_control::{SupervisorHealthStatus, SupervisorRouteModule};
    use subc_protocol::{ErrorBody, Flags, Frame, FrameType, Priority};
    use tokio::sync::mpsc;

    use super::super::{dispatch_frame, ConsumerOptions, Shared};
    use super::*;

    fn consumer() -> (
        SubcConsumer,
        Arc<Shared>,
        mpsc::Receiver<super::super::WriteCommand>,
    ) {
        let shared = Arc::new(Shared::new(
            PathBuf::from("/tmp/does-not-exist"),
            ConsumerOptions::default(),
        ));
        let (writer, rx) = mpsc::channel(1);
        shared.lock_inner().writer = Some(writer);
        (
            SubcConsumer {
                shared: Arc::clone(&shared),
            },
            shared,
            rx,
        )
    }

    fn frame(kind: FrameType, corr: u64, body: Vec<u8>) -> Frame {
        Frame::build(
            kind,
            Flags::new(false, Priority::Interactive, false),
            0,
            0,
            corr,
            body,
        )
        .unwrap()
    }

    #[tokio::test]
    async fn health_sends_its_op_and_returns_the_entries() {
        let (consumer, shared, mut rx) = consumer();
        let call = tokio::spawn(async move { consumer.supervisor_health().await });
        let command = rx.recv().await.expect("a channel-0 request");
        assert_eq!(command.frame.header.channel, 0);
        let body: serde_json::Value = serde_json::from_slice(&command.frame.body).unwrap();
        assert_eq!(body["op"], "supervisor.health");
        let reply = serde_json::json!({
            "op": "supervisor.health",
            "generation": 7,
            "modules": [{
                "module_id": "broca",
                "status": "degraded",
                "detail": "provider throttled",
                "metrics": {"headline": ["runs"], "runs": 3},
                "consecutive_failures": 0
            }]
        });
        let corr = command.frame.header.corr;
        let reply = serde_json::to_vec(&reply).unwrap();
        assert!(dispatch_frame(&shared, 1, frame(FrameType::Response, corr, reply)).await);
        let health = call.await.unwrap().unwrap();
        assert_eq!(health.generation, 7);
        assert_eq!(health.modules[0].status, SupervisorHealthStatus::Degraded);
        assert_eq!(
            health.modules[0].detail.as_deref(),
            Some("provider throttled")
        );
    }

    #[tokio::test]
    async fn routes_and_describe_decode_their_replies() {
        let (consumer, shared, mut rx) = consumer();
        let consumer = Arc::new(consumer);
        let c = Arc::clone(&consumer);
        let call = tokio::spawn(async move { c.supervisor_routes(Some("broca".into())).await });
        let command = rx.recv().await.unwrap();
        let body: serde_json::Value = serde_json::from_slice(&command.frame.body).unwrap();
        assert_eq!(body["op"], "supervisor.routes");
        assert_eq!(body["module_id"], "broca");
        let reply = serde_json::to_vec(&ClientControlResponse::SupervisorRoutes {
            modules: vec![SupervisorRouteModule {
                module_id: "broca".into(),
                routes: vec![],
            }],
        })
        .unwrap();
        let corr = command.frame.header.corr;
        assert!(dispatch_frame(&shared, 1, frame(FrameType::Response, corr, reply)).await);
        assert_eq!(call.await.unwrap().unwrap()[0].module_id, "broca");

        let c = Arc::clone(&consumer);
        let call = tokio::spawn(async move { c.server_describe().await });
        let command = rx.recv().await.unwrap();
        let reply = serde_json::json!({
            "op": "server.describe",
            "protocol_ver": 1,
            "subc_ops": [],
            "capabilities": [],
            "connected_clients": 12,
            "machine_id": "4f1a9c2e7b3d40c8"
        });
        let corr = command.frame.header.corr;
        let reply = serde_json::to_vec(&reply).unwrap();
        assert!(dispatch_frame(&shared, 1, frame(FrameType::Response, corr, reply)).await);
        let described = call.await.unwrap().unwrap();
        assert_eq!(described.connected_clients, 12);
        assert_eq!(described.machine_id.as_deref(), Some("4f1a9c2e7b3d40c8"));
        assert_eq!(described.config_path, None, "an older daemon sends no path");

        let c = Arc::clone(&consumer);
        let call = tokio::spawn(async move { c.server_describe().await });
        let command = rx.recv().await.unwrap();
        let reply = serde_json::json!({
            "op": "server.describe",
            "protocol_ver": 1,
            "subc_ops": [],
            "capabilities": ["rescan-candidate-preview/v1"],
            "connected_clients": 1,
            "config_path": "/Users/alex/.config/cortexkit/subc.jsonc"
        });
        let corr = command.frame.header.corr;
        let reply = serde_json::to_vec(&reply).unwrap();
        assert!(dispatch_frame(&shared, 1, frame(FrameType::Response, corr, reply)).await);
        let described = call.await.unwrap().unwrap();
        assert_eq!(
            described.config_path.as_deref(),
            Some(std::path::Path::new(
                "/Users/alex/.config/cortexkit/subc.jsonc"
            ))
        );
    }

    #[tokio::test]
    async fn restart_returns_the_ack_and_a_refusal_keeps_its_code() {
        let (consumer, shared, mut rx) = consumer();
        let consumer = Arc::new(consumer);
        let c = Arc::clone(&consumer);
        let call = tokio::spawn(async move { c.supervisor_restart("broca", None).await });
        let command = rx.recv().await.unwrap();
        let body: serde_json::Value = serde_json::from_slice(&command.frame.body).unwrap();
        assert_eq!(body["op"], "supervisor.restart");
        assert_eq!(body["module_id"], "broca");
        assert!(body.get("drain_timeout_ms").is_none());
        let reply = serde_json::to_vec(&ClientControlResponse::SupervisorAck {
            module_id: "broca".into(),
            applied: true,
        })
        .unwrap();
        let corr = command.frame.header.corr;
        assert!(dispatch_frame(&shared, 1, frame(FrameType::Response, corr, reply)).await);
        assert_eq!(
            call.await.unwrap().unwrap(),
            SupervisorAck {
                module_id: "broca".into(),
                applied: true
            }
        );

        let c = Arc::clone(&consumer);
        let call = tokio::spawn(async move { c.supervisor_set_enabled("broca", false).await });
        let command = rx.recv().await.unwrap();
        let body: serde_json::Value = serde_json::from_slice(&command.frame.body).unwrap();
        assert_eq!(body["op"], "supervisor.set_enabled");
        assert_eq!(body["enabled"], false);
        let refusal = serde_json::to_vec(&ErrorBody {
            code: "module_reserved".into(),
            message: "refused by the test".into(),
            detail: None,
        })
        .unwrap();
        let corr = command.frame.header.corr;
        assert!(dispatch_frame(&shared, 1, frame(FrameType::Error, corr, refusal)).await);
        assert_eq!(
            call.await.unwrap().unwrap_err().code(),
            Some("module_reserved")
        );
    }

    #[tokio::test]
    async fn health_probe_and_terminals_decode_their_replies() {
        let (consumer, shared, mut rx) = consumer();
        let consumer = Arc::new(consumer);
        let c = Arc::clone(&consumer);
        let call = tokio::spawn(async move { c.supervisor_health_probe("aft").await });
        let command = rx.recv().await.unwrap();
        let body: serde_json::Value = serde_json::from_slice(&command.frame.body).unwrap();
        assert_eq!(body["op"], "supervisor.health_probe");
        assert_eq!(body["module_id"], "aft");
        let reply = serde_json::json!({
            "op": "supervisor.health_probe", "module_id": "aft", "status": "ok",
            "metrics": {"headline": ["files"], "files": 12}
        });
        let corr = command.frame.header.corr;
        let reply = serde_json::to_vec(&reply).unwrap();
        assert!(dispatch_frame(&shared, 1, frame(FrameType::Response, corr, reply)).await);
        let probe = call.await.unwrap().unwrap();
        assert_eq!(probe.metrics.unwrap()["files"], 12);

        let c = Arc::clone(&consumer);
        let call = tokio::spawn(async move { c.supervisor_terminals("aft").await });
        let command = rx.recv().await.unwrap();
        let body: serde_json::Value = serde_json::from_slice(&command.frame.body).unwrap();
        assert_eq!(body["op"], "supervisor.terminals");
        let reply = serde_json::json!({
            "op": "supervisor.terminals", "module_id": "aft",
            "daemon_started_at_ms": 1000,
            "entries": [{"exit_code": 0, "at_ms": 2000, "disposition": "restarting"}]
        });
        let corr = command.frame.header.corr;
        let reply = serde_json::to_vec(&reply).unwrap();
        assert!(dispatch_frame(&shared, 1, frame(FrameType::Response, corr, reply)).await);
        let history = call.await.unwrap().unwrap();
        assert_eq!(history.entries.len(), 1);
        assert_eq!(history.entries[0].at_ms, 2000);
    }

    #[tokio::test]
    async fn stderr_tail_carries_its_caps_and_decodes_lines() {
        let (consumer, shared, mut rx) = consumer();
        let call = tokio::spawn(async move {
            consumer
                .supervisor_stderr_tail("broca", Some(200), None)
                .await
        });
        let command = rx.recv().await.unwrap();
        let body: serde_json::Value = serde_json::from_slice(&command.frame.body).unwrap();
        assert_eq!(body["op"], "supervisor.stderr_tail");
        assert_eq!(body["max_lines"], 200);
        let reply = serde_json::json!({
            "op": "supervisor.stderr_tail",
            "module_id": "broca",
            "capture": {"state": "captured"},
            "entries": [
                {"kind": "line", "text": "hello", "truncated": false, "at_ms": 1000}
            ]
        });
        let corr = command.frame.header.corr;
        let reply = serde_json::to_vec(&reply).unwrap();
        assert!(dispatch_frame(&shared, 1, frame(FrameType::Response, corr, reply)).await);
        let tail = call.await.unwrap().unwrap();
        assert_eq!(tail.module_id, "broca");
        assert_eq!(tail.tail.entries.len(), 1);
    }
}