bitrouter 1.0.0-alpha.34

BitRouter: an LLM API router. CLI + assembly library.
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
//! Report for the `bro update` self-updater.
//!
//! Every terminal outcome of `update` — a package-manager delegation, a
//! `--check` probe, a declined confirmation, a no-op, or a completed swap —
//! is one [`UpdateReport`]. Interactive prompts and progress are diagnostics
//! and go to stderr; this is the single result value on stdout.

use serde::Serialize;

use crate::output::CliReport;
use crate::output::human::Human;

/// Result of `bro update`. `status` is the discriminant; the remaining
/// fields are populated only for the outcomes they belong to.
#[derive(Debug, Serialize)]
pub struct UpdateReport {
    /// `delegated` | `checked` | `aborted` | `unchanged` | `updated`.
    pub status: &'static str,
    /// The version of the currently-running binary.
    pub current_version: String,
    /// `checked`: whether a newer release exists.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub update_available: Option<bool>,
    /// The version this outcome refers to: the available release (`checked`)
    /// or the freshly-installed one (`updated`). Absent when unknown / N/A.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub target_version: Option<String>,
    /// `delegated`: how the binary was installed (`homebrew` | `cargo` |
    /// `unknown`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub install_method: Option<&'static str>,
    /// `delegated`: the exact command to run to upgrade out-of-band.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub upgrade_command: Option<String>,
    /// `updated`: `restarted`, `compatible`, or `deferred`. Absent when no
    /// daemon runs.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub daemon: Option<&'static str>,
    /// Why an installed binary could not take over the running daemon.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub daemon_reason: Option<String>,
    /// Verified state of the daemon after an update attempt.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub daemon_pid: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub daemon_version: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub daemon_instance_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub daemon_listen: Option<String>,
}

impl UpdateReport {
    /// No cargo-dist receipt: tell the user the package-manager command instead
    /// of clobbering a managed install.
    pub fn delegated(
        current_version: String,
        install_method: &'static str,
        upgrade_command: String,
    ) -> Self {
        Self {
            status: "delegated",
            current_version,
            update_available: None,
            target_version: None,
            install_method: Some(install_method),
            upgrade_command: Some(upgrade_command),
            daemon: None,
            daemon_reason: None,
            daemon_pid: None,
            daemon_version: None,
            daemon_instance_id: None,
            daemon_listen: None,
        }
    }

    /// `--check`: report whether a newer release exists, and which (when known).
    pub fn checked(
        current_version: String,
        available: bool,
        target_version: Option<String>,
    ) -> Self {
        Self {
            status: "checked",
            current_version,
            update_available: Some(available),
            target_version,
            install_method: None,
            upgrade_command: None,
            daemon: None,
            daemon_reason: None,
            daemon_pid: None,
            daemon_version: None,
            daemon_instance_id: None,
            daemon_listen: None,
        }
    }

    /// The user declined the confirmation prompt.
    pub fn aborted(current_version: String) -> Self {
        Self {
            status: "aborted",
            current_version,
            update_available: None,
            target_version: None,
            install_method: None,
            upgrade_command: None,
            daemon: None,
            daemon_reason: None,
            daemon_pid: None,
            daemon_version: None,
            daemon_instance_id: None,
            daemon_listen: None,
        }
    }

    /// The updater ran but the binary was already current.
    pub fn unchanged(current_version: String) -> Self {
        Self {
            status: "unchanged",
            current_version,
            update_available: None,
            target_version: None,
            install_method: None,
            upgrade_command: None,
            daemon: None,
            daemon_reason: None,
            daemon_pid: None,
            daemon_version: None,
            daemon_instance_id: None,
            daemon_listen: None,
        }
    }

    /// The binary was swapped to `new_version`. `daemon` records whether a
    /// running daemon was restarted onto it or still needs a manual restart.
    pub fn updated(
        current_version: String,
        new_version: String,
        daemon: Option<&'static str>,
    ) -> Self {
        Self {
            status: "updated",
            current_version,
            update_available: None,
            target_version: Some(new_version),
            install_method: None,
            upgrade_command: None,
            daemon,
            daemon_reason: None,
            daemon_pid: None,
            daemon_version: None,
            daemon_instance_id: None,
            daemon_listen: None,
        }
    }
}

impl CliReport for UpdateReport {
    fn exit_code(&self) -> i32 {
        i32::from(self.daemon == Some("deferred"))
    }

    fn render(&self, h: &mut Human<'_>) -> std::io::Result<()> {
        match self.status {
            "delegated" => {
                let how = match self.install_method {
                    Some("homebrew") => "Homebrew",
                    Some("cargo") => "Cargo",
                    _ => "your package manager",
                };
                h.line(&format!(
                    "bitrouter looks installed via {how}. Update with:"
                ))?;
                if let Some(cmd) = &self.upgrade_command {
                    h.line(&format!("    {cmd}"))?;
                }
                Ok(())
            }
            "checked" => {
                if self.update_available == Some(true) {
                    match &self.target_version {
                        Some(v) => h.line(&format!(
                            "update available: {} -> {v}",
                            self.current_version
                        )),
                        None => h.line("update available (target version unknown)"),
                    }
                } else {
                    h.line(&format!("up to date ({})", self.current_version))
                }
            }
            "aborted" => h.line("aborted"),
            "unchanged" => h.line(&format!("already up to date ({})", self.current_version)),
            "updated" => {
                let new = self.target_version.as_deref().unwrap_or("(unknown)");
                h.line(&format!("✓ updated {} -> {new}", self.current_version))?;
                match self.daemon {
                    Some("restarted") => h.note(&format!("Restarted the running daemon on {new}.")),
                    Some("compatible") => h.note(&format!("The running daemon is serving {new}.")),
                    Some("restart_needed") => h.note(&format!(
                        "A daemon is running the old binary. Run `{} restart` to serve {new}.",
                        bitrouter_sdk::invocation::name()
                    )),
                    Some("deferred") => h.note(&format!(
                        "Daemon handoff deferred: {}",
                        self.daemon_reason
                            .as_deref()
                            .unwrap_or("reason unavailable")
                    )),
                    _ => Ok(()),
                }?;
                if let Some(pid) = self.daemon_pid {
                    h.field("daemon pid", pid)?;
                }
                if let Some(version) = &self.daemon_version {
                    h.field("daemon version", version)?;
                }
                if let Some(instance) = &self.daemon_instance_id {
                    h.field("daemon instance", instance)?;
                }
                if let Some(listen) = &self.daemon_listen {
                    h.field("daemon listen", listen)?;
                }
                Ok(())
            }
            other => h.line(other),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::output::{Format, Output};

    fn json(r: &dyn CliReport) -> serde_json::Value {
        serde_json::from_slice(&Output::new(Format::Json).render_to_vec(r)).unwrap()
    }

    fn human(r: &dyn CliReport) -> String {
        String::from_utf8(Output::new(Format::Human).render_to_vec(r)).unwrap()
    }

    #[test]
    fn delegated_carries_method_and_command() {
        let r = UpdateReport::delegated(
            "1.0.0-alpha.19".into(),
            "homebrew",
            "brew upgrade bitrouter".into(),
        );
        assert_eq!(
            json(&r),
            serde_json::json!({
                "status": "delegated",
                "current_version": "1.0.0-alpha.19",
                "install_method": "homebrew",
                "upgrade_command": "brew upgrade bitrouter"
            })
        );
        let h = human(&r);
        assert!(h.contains("looks installed via Homebrew"), "{h:?}");
        assert!(h.contains("    brew upgrade bitrouter"), "{h:?}");
    }

    #[test]
    fn checked_available_names_target_version() {
        let r = UpdateReport::checked("1.0.0-alpha.19".into(), true, Some("1.0.0-alpha.20".into()));
        assert_eq!(
            json(&r),
            serde_json::json!({
                "status": "checked",
                "current_version": "1.0.0-alpha.19",
                "update_available": true,
                "target_version": "1.0.0-alpha.20"
            })
        );
        assert_eq!(
            human(&r),
            "update available: 1.0.0-alpha.19 -> 1.0.0-alpha.20\n"
        );
    }

    #[test]
    fn checked_up_to_date_omits_target() {
        let r = UpdateReport::checked("1.0.0-alpha.19".into(), false, None);
        assert_eq!(
            json(&r),
            serde_json::json!({
                "status": "checked",
                "current_version": "1.0.0-alpha.19",
                "update_available": false
            })
        );
        assert_eq!(human(&r), "up to date (1.0.0-alpha.19)\n");
    }

    #[test]
    fn checked_available_but_target_unknown() {
        // `is_update_needed()` is true but `query_new_version()` came back empty.
        let r = UpdateReport::checked("1.0.0-alpha.19".into(), true, None);
        assert_eq!(
            json(&r),
            serde_json::json!({
                "status": "checked",
                "current_version": "1.0.0-alpha.19",
                "update_available": true
            })
        );
        assert_eq!(human(&r), "update available (target version unknown)\n");
    }

    #[test]
    fn updated_without_running_daemon_omits_daemon_key() {
        let r = UpdateReport::updated("1.0.0-alpha.19".into(), "1.0.0-alpha.20".into(), None);
        assert_eq!(
            json(&r),
            serde_json::json!({
                "status": "updated",
                "current_version": "1.0.0-alpha.19",
                "target_version": "1.0.0-alpha.20"
            })
        );
        // No running daemon -> just the result line, no follow-up note.
        assert_eq!(human(&r), "✓ updated 1.0.0-alpha.19 -> 1.0.0-alpha.20\n");
    }

    #[test]
    fn updated_with_restart_hint_renders_note() {
        let r = UpdateReport::updated(
            "1.0.0-alpha.19".into(),
            "1.0.0-alpha.20".into(),
            Some("restart_needed"),
        );
        assert_eq!(
            json(&r),
            serde_json::json!({
                "status": "updated",
                "current_version": "1.0.0-alpha.19",
                "target_version": "1.0.0-alpha.20",
                "daemon": "restart_needed"
            })
        );
        let h = human(&r);
        assert!(
            h.contains("✓ updated 1.0.0-alpha.19 -> 1.0.0-alpha.20"),
            "{h:?}"
        );
        assert!(h.contains("Run `bro restart`"), "{h:?}");
    }

    #[test]
    fn updated_restarted_omits_hint() {
        let r = UpdateReport::updated(
            "1.0.0-alpha.19".into(),
            "1.0.0-alpha.20".into(),
            Some("restarted"),
        );
        let h = human(&r);
        assert!(
            h.contains("Restarted the running daemon on 1.0.0-alpha.20"),
            "{h:?}"
        );
    }

    #[test]
    fn already_compatible_daemon_does_not_claim_restart() {
        let report = UpdateReport::updated(
            "1.0.0-alpha.31".into(),
            "1.0.0-alpha.32".into(),
            Some("compatible"),
        );
        assert_eq!(report.exit_code(), 0);
        assert!(human(&report).contains("The running daemon is serving 1.0.0-alpha.32"));
    }

    #[test]
    fn updated_binary_with_deferred_daemon_is_not_a_success() {
        let mut report = UpdateReport::updated(
            "1.0.0-alpha.31".into(),
            "1.0.0-alpha.32".into(),
            Some("deferred"),
        );
        report.daemon_reason = Some("one supervised run is still active".into());
        assert_eq!(report.exit_code(), 1);
        assert_eq!(json(&report)["daemon"], "deferred");
        assert!(human(&report).contains("one supervised run is still active"));
    }

    #[test]
    fn unchanged_and_aborted_are_one_liners() {
        assert_eq!(
            human(&UpdateReport::unchanged("1.0.0-alpha.19".into())),
            "already up to date (1.0.0-alpha.19)\n"
        );
        assert_eq!(
            human(&UpdateReport::aborted("1.0.0-alpha.19".into())),
            "aborted\n"
        );
        assert_eq!(
            json(&UpdateReport::aborted("1.0.0-alpha.19".into())),
            serde_json::json!({"status": "aborted", "current_version": "1.0.0-alpha.19"})
        );
    }
}