Skip to main content

lean_ctx_cloud/
computers.rs

1// SPDX-License-Identifier: Apache-2.0
2//! LeanCTX Cloud computers (`/v1/computers`, cloud design `cloud-computer.md`
3//! §4.3): list, create, start and stop the computers of the person and of
4//! their teams, for `lean-ctx cloud computer …` and LeanCTX Code.
5//!
6//! The cloud enforces who may create or start a computer, its role, the free
7//! hours, the balance and the trial; this module only passes the request on
8//! and hands back what the cloud answered:
9//! - `200`/`201`/`202` with a row (or `{computers: […]}`) → [`Answer::Done`];
10//! - an error with a code (`402 balance_empty`, `402 plan_required`,
11//!   `403 forbidden`, `404 no_computer`, `409 computer_exists`,
12//!   `409 computer_busy`, `400`/`422 invalid_request`, `429`,
13//!   `428 confirmation_required`, `503 computer_provider_unavailable`,
14//!   `503 computer_not_available`) → [`Answer::Refused`], with the cloud's
15//!   own message and `error.details`;
16//! - `404` without a code, or `503 not_configured`, from a cloud that does
17//!   not offer computers, and a list `200 {available: false}` (no provider
18//!   yet) → [`Answer::NotOffered`].
19//!
20//! A create or a start costs money, so the CLI sends one only after the
21//! person confirmed the terms (`--yes`), and always with `confirm: true`.
22//! A cloud that still wants a confirmation answers
23//! `428 confirmation_required` with the terms in `error.details`
24//! (`{billing: free|billed, usd_per_hour, free_hours_left, topup_usd}`,
25//! read with [`terms`]) and does nothing: a second guard.
26//!
27//! Every exchange goes through an [`Exchange`]: [`connected`] for the connected
28//! instance (the session refreshes a refused token), [`on_client`] for one
29//! [`CloudClient`].
30//!
31//! No code and no file content is ever sent: the bodies carry only the
32//! request id, the name, the role, the team and the confirmation.
33
34use serde::Serialize;
35use serde_json::{Map, Value, json};
36
37use crate::CloudError;
38use crate::config::CloudConfig;
39use crate::state::CloudStore;
40use crate::transport::CloudClient;
41
42/// The cloud route (under `/v1`).
43const PATH: &str = "/computers";
44/// Largest answer read.
45pub(crate) const MAX_ANSWER_BYTES: usize = 256 * 1024;
46/// Most rows kept from a list.
47pub const MAX_ROWS: usize = 64;
48/// Longest cloud message passed on.
49const MAX_MESSAGE_LEN: usize = 500;
50/// Longest wait passed on (a day).
51const RETRY_AFTER_CAP_S: u64 = 86_400;
52
53/// The role the free Team hours apply to (owner, 18.11.).
54pub const ROLE_WEAVE_HOST: &str = "weave_host";
55/// The role of any other computer; the only one for a personal account.
56pub const ROLE_GENERAL: &str = "general";
57/// The roles a computer is created with; fixed at create.
58pub const ROLES: [&str; 2] = [ROLE_GENERAL, ROLE_WEAVE_HOST];
59
60/// The cloud refused the request; passed on as it said it.
61#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
62pub struct Refusal {
63    /// HTTP status.
64    pub status: u16,
65    /// `error.code`, or `http_<status>` when the cloud sent none.
66    pub code: String,
67    /// `error.message`, when the cloud sent one (bounded).
68    pub message: Option<String>,
69    /// `error.next_step` (`top_up`), when sent.
70    pub next_step: Option<String>,
71    /// Seconds after which asking again may help (`429`).
72    pub retry_after_s: Option<u64>,
73    /// `error.details`, when it is an object (the terms of a `428`).
74    pub details: Option<Map<String, Value>>,
75    /// The specific reason: `error.reason`, else `error.details.reason`
76    /// (a `409 invalid_state` with reason `computer_exists`).
77    pub reason: Option<String>,
78}
79
80/// The terms of a billable write, from a `428 confirmation_required`
81/// (`error.details`): one shape for the cloud, the CLI and LeanCTX Code.
82#[derive(Debug, Clone, Copy, PartialEq, Serialize)]
83pub struct Terms {
84    /// `free` (the team's free `weave_host` hours) or `billed` (paid from
85    /// the top-up, the only source of computer minutes); `None` when the
86    /// cloud named neither.
87    pub billing: Option<&'static str>,
88    pub usd_per_hour: Option<f64>,
89    pub free_hours_left: Option<f64>,
90    /// What is left of the top-up, in USD.
91    pub topup_usd: Option<f64>,
92}
93
94/// The terms in `details`; anything malformed is `None`, never a guess.
95#[must_use]
96pub fn terms(details: Option<&Map<String, Value>>) -> Terms {
97    let num = |k: &str| {
98        details
99            .and_then(|d| d.get(k))
100            .and_then(Value::as_f64)
101            .filter(|n| n.is_finite() && *n >= 0.0)
102    };
103    Terms {
104        billing: match details
105            .and_then(|d| d.get("billing"))
106            .and_then(Value::as_str)
107        {
108            Some("free") => Some("free"),
109            Some("billed") => Some("billed"),
110            _ => None,
111        },
112        usd_per_hour: num("usd_per_hour"),
113        free_hours_left: num("free_hours_left"),
114        // p37 names it `balance_usd` (top-up only, owner 19.11.).
115        topup_usd: num("topup_usd").or_else(|| num("balance_usd")),
116    }
117}
118
119/// What the cloud said.
120#[derive(Debug, Clone, PartialEq)]
121pub enum Answer<T> {
122    Done(T),
123    Refused(Refusal),
124    /// This cloud does not offer computers (older, or switched off).
125    NotOffered,
126}
127
128/// `GET /v1/computers`, checked.
129#[derive(Debug, Clone, PartialEq, Default)]
130pub struct ComputerList {
131    /// The rows, as the cloud sent them (malformed rows left out); each
132    /// carries its scope's `balance` (§4.3 sends no top-level balance).
133    pub computers: Vec<Map<String, Value>>,
134}
135
136/// `POST /v1/computers` body (`{ request_id, name, team?, role, confirm }`).
137/// The cloud picks size and region and does not stop an idle computer, so
138/// the CLI offers no size, region or idle stop: a computer runs, and is
139/// billed, until it is stopped.
140#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
141pub struct CreateRequest {
142    pub request_id: String,
143    pub name: String,
144    /// The team's org id; absent for a personal computer.
145    #[serde(skip_serializing_if = "Option::is_none")]
146    pub team: Option<String>,
147    pub role: String,
148    /// The person confirmed the terms (`--yes`). The CLI sends a create
149    /// only when this is `true`; a cloud that sees `false` answers
150    /// `428 confirmation_required` and creates nothing.
151    pub confirm: bool,
152}
153
154/// A fresh request id: a retry of the same command passes it again with
155/// `--request-id`, and the cloud answers the first answer.
156#[must_use]
157pub fn new_request_id() -> String {
158    format!("req_{}", uuid::Uuid::new_v4().simple())
159}
160
161/// A request id the cloud accepts: 8-64 of `A-Z a-z 0-9 _ -`.
162#[must_use]
163pub fn valid_request_id(id: &str) -> bool {
164    (8..=64).contains(&id.len())
165        && id
166            .bytes()
167            .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
168}
169
170/// A computer id as the cloud sends it (`cmp_…`), safe in a path.
171#[must_use]
172pub fn valid_id(id: &str) -> bool {
173    id.starts_with("cmp_")
174        && (5..=64).contains(&id.len())
175        && id
176            .bytes()
177            .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
178}
179
180/// One exchange with the cloud: method, path (under `/v1`) and body → the
181/// HTTP status and the JSON answer.
182pub type Exchange<'a> = &'a dyn Fn(&str, &str, Option<&Value>) -> Result<(u16, Value), CloudError>;
183
184/// The exchanges of the connected instance: each one through its session,
185/// which refreshes a refused token.
186pub fn connected<'a>(
187    store: &'a CloudStore,
188    config: &'a CloudConfig,
189) -> impl Fn(&str, &str, Option<&Value>) -> Result<(u16, Value), CloudError> + 'a {
190    move |method, path, body| {
191        let session = crate::scheduler::connected_session(store, config)?;
192        session.with_client(|client| on_client(client)(method, path, body))
193    }
194}
195
196/// The exchanges on `client`.
197pub fn on_client(
198    client: &CloudClient,
199) -> impl Fn(&str, &str, Option<&Value>) -> Result<(u16, Value), CloudError> + '_ {
200    move |method, path, body| {
201        let (status, answer) = client.send_answer(method, path, body, MAX_ANSWER_BYTES)?;
202        // A refused token goes through the session's refresh.
203        if status == 401 {
204            return Err(CloudError::from_response(status, &answer));
205        }
206        Ok((status, answer))
207    }
208}
209
210/// `GET /v1/computers`.
211pub fn list(send: Exchange<'_>) -> Result<Answer<ComputerList>, CloudError> {
212    let (status, body) = send("GET", PATH, None)?;
213    list_of(status, &body)
214}
215
216/// The list of `status` and `body`. `200 {available: false}` (no provider
217/// yet, so no computers and no prices) is [`Answer::NotOffered`] like a
218/// cloud without the route; a missing `available` means available.
219fn list_of(status: u16, body: &Value) -> Result<Answer<ComputerList>, CloudError> {
220    if (200..300).contains(&status) && body.get("available") == Some(&Value::Bool(false)) {
221        return Ok(Answer::NotOffered);
222    }
223    classify(status, body, |body| {
224        let rows = body
225            .get("computers")
226            .and_then(Value::as_array)
227            .ok_or_else(|| CloudError::Protocol("computers: no `computers` list".into()))?;
228        Ok(ComputerList {
229            computers: rows.iter().filter_map(checked_row).take(MAX_ROWS).collect(),
230        })
231    })
232}
233
234/// `POST /v1/computers`: the new row (`provisioning`).
235pub fn create(
236    send: Exchange<'_>,
237    request: &CreateRequest,
238) -> Result<Answer<Map<String, Value>>, CloudError> {
239    let body = serde_json::to_value(request)
240        .map_err(|e| CloudError::Protocol(format!("encode request: {e}")))?;
241    let (status, answer) = send("POST", PATH, Some(&body))?;
242    classify(status, &answer, row_of)
243}
244
245/// `POST /v1/computers/{id}/start` or `/stop`: the row (`starting` or
246/// `stopping`). `confirm` (start only) as in [`CreateRequest::confirm`].
247pub fn transition(
248    send: Exchange<'_>,
249    id: &str,
250    action: Transition,
251    request_id: &str,
252    confirm: bool,
253) -> Result<Answer<Map<String, Value>>, CloudError> {
254    if !valid_id(id) {
255        return Err(CloudError::Protocol(format!("computers: bad id '{id}'")));
256    }
257    let path = format!("{PATH}/{id}/{}", action.as_str());
258    let body = match action {
259        Transition::Start => json!({ "request_id": request_id, "confirm": confirm }),
260        Transition::Stop => json!({ "request_id": request_id }),
261    };
262    let (status, answer) = send("POST", &path, Some(&body))?;
263    classify(status, &answer, row_of)
264}
265
266/// A start or a stop.
267#[derive(Debug, Clone, Copy, PartialEq, Eq)]
268pub enum Transition {
269    Start,
270    Stop,
271}
272
273impl Transition {
274    #[must_use]
275    pub fn as_str(self) -> &'static str {
276        match self {
277            Self::Start => "start",
278            Self::Stop => "stop",
279        }
280    }
281}
282
283/// The answer of `status` and `body`; `done` reads a success body.
284pub(crate) fn classify<T>(
285    status: u16,
286    body: &Value,
287    done: impl FnOnce(&Value) -> Result<T, CloudError>,
288) -> Result<Answer<T>, CloudError> {
289    if (200..300).contains(&status) {
290        return done(body).map(Answer::Done);
291    }
292    let code = body["error"]["code"].as_str().unwrap_or_default();
293    if (status == 404 && (code.is_empty() || code == "not_found"))
294        || (status == 503 && code == "not_configured")
295    {
296        return Ok(Answer::NotOffered);
297    }
298    if code.is_empty() && !matches!(status, 400 | 402 | 403 | 409 | 422 | 428 | 429 | 503) {
299        return Err(CloudError::from_response(status, body));
300    }
301    let text = |key: &str| {
302        body["error"][key]
303            .as_str()
304            .map(str::trim)
305            .filter(|s| !s.is_empty())
306            .map(|s| bounded(s, MAX_MESSAGE_LEN))
307    };
308    let details = body["error"]["details"].as_object().cloned();
309    let reason = body["error"]["reason"]
310        .as_str()
311        .or_else(|| details.as_ref()?.get("reason")?.as_str())
312        .map(|r| bounded(r, 64));
313    Ok(Answer::Refused(Refusal {
314        status,
315        code: if code.is_empty() {
316            format!("http_{status}")
317        } else {
318            bounded(code, 64)
319        },
320        message: text("message"),
321        next_step: text("next_step"),
322        retry_after_s: body["error"]["retry_after_s"]
323            .as_u64()
324            .map(|s| s.min(RETRY_AFTER_CAP_S)),
325        details,
326        reason,
327    }))
328}
329
330/// `POST /v1/computers/{id}/start` body for `lean-ctx run --cloud`
331/// (contract §35). A run is billed from the first minute (free hours are
332/// only for `weave_host`), so this body exists only after the person
333/// confirmed the terms (`--yes`, or yes at the prompt): `confirm` is
334/// always `true`. Carries no code, no task text, no file content.
335#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
336pub struct RunStartRequest {
337    pub request_id: String,
338    /// Always `run`: the cloud bills it from the first minute.
339    pub purpose: &'static str,
340    /// Always `true`: an unconfirmed paid start is never sent.
341    pub confirm: bool,
342}
343
344impl RunStartRequest {
345    /// The body of a start the person confirmed.
346    #[must_use]
347    pub fn confirmed(request_id: String) -> Self {
348        Self {
349            request_id,
350            purpose: "run",
351            confirm: true,
352        }
353    }
354}
355
356/// The terms of a run on computer `row`, from the list row alone (no
357/// request to the cloud): billed from the first minute, at the row's price
358/// (else its balance's), with what is left of the top-up as listed
359/// (`topup_usd`). `purpose: "run"` is always `billed`: the free hours are a
360/// team's `weave_host`'s, never a run's. A malformed value is `None`, never
361/// a guess.
362#[must_use]
363pub fn run_terms(row: &Map<String, Value>) -> Terms {
364    let price = row
365        .get("price")
366        .and_then(|p| p.get("usd_per_hour"))
367        .or_else(|| row.get("balance").and_then(|b| b.get("usd_per_hour")));
368    let mut details = Map::new();
369    details.insert("billing".into(), "billed".into());
370    if let Some(price) = price {
371        details.insert("usd_per_hour".into(), price.clone());
372    }
373    if let Some(usd) = row.get("balance").and_then(|b| b.get("usd")) {
374        details.insert("topup_usd".into(), usd.clone());
375    }
376    terms(Some(&details))
377}
378
379/// `POST /v1/computers/{id}/start` for a confirmed run (see
380/// [`RunStartRequest`]): the row (`starting`, or `running` when it already
381/// ran), or the cloud's refusal.
382pub fn start_for_run(
383    send: Exchange<'_>,
384    id: &str,
385    request: &RunStartRequest,
386) -> Result<Answer<Map<String, Value>>, CloudError> {
387    if !valid_id(id) {
388        return Err(CloudError::Protocol(format!("computers: bad id '{id}'")));
389    }
390    if !request.confirm {
391        return Err(CloudError::Protocol(
392            "computers: a run start is sent only when confirmed".into(),
393        ));
394    }
395    let path = format!("{PATH}/{id}/start");
396    let body = serde_json::to_value(request)
397        .map_err(|e| CloudError::Protocol(format!("encode request: {e}")))?;
398    let (status, answer) = send("POST", &path, Some(&body))?;
399    classify(status, &answer, row_of)
400}
401
402fn bounded(text: &str, max: usize) -> String {
403    text.chars().filter(|c| !c.is_control()).take(max).collect()
404}
405
406/// A row with a string `id`, `name` and `state`; anything else is left out.
407pub(crate) fn checked_row(row: &Value) -> Option<Map<String, Value>> {
408    let object = row.as_object()?;
409    let text = |k: &str| object.get(k).and_then(Value::as_str);
410    let id = text("id")?;
411    if !valid_id(id) || text("name")?.is_empty() || text("state")?.is_empty() {
412        return None;
413    }
414    Some(object.clone())
415}
416
417/// A write's answer: the row itself, or `{computer: row}`.
418fn row_of(body: &Value) -> Result<Map<String, Value>, CloudError> {
419    checked_row(body.get("computer").unwrap_or(body))
420        .ok_or_else(|| CloudError::Protocol("computers: the answer is not a computer row".into()))
421}
422
423/// Who pays a start, from the row the cloud answered (§3.3), in the words
424/// of [`Terms::billing`]: a team's `weave_host` computer with free hours
425/// left starts on them (`free`); a personal computer never does (the free
426/// hours are the team's) and a `general` one never does: they are `billed`
427/// (paid from the top-up). A team's `weave_host` whose row carries no
428/// readable `balance.free_hours_left` is `None`: unknown, never guessed.
429/// The cloud decides; this only names it.
430#[must_use]
431pub fn start_basis(row: &Map<String, Value>) -> Option<&'static str> {
432    let team = row
433        .get("scope")
434        .and_then(|s| s.get("kind"))
435        .and_then(Value::as_str)
436        == Some("team");
437    if !team || row.get("role").and_then(Value::as_str) != Some(ROLE_WEAVE_HOST) {
438        return Some("billed");
439    }
440    let free = row
441        .get("balance")
442        .and_then(|b| b.get("free_hours_left"))
443        .and_then(Value::as_f64)
444        .filter(|n| n.is_finite() && *n >= 0.0)?;
445    Some(if free > 0.0 { "free" } else { "billed" })
446}
447
448#[cfg(test)]
449mod tests {
450    use super::*;
451
452    fn row(id: &str, name: &str, state: &str) -> Value {
453        json!({ "id": id, "name": name, "state": state, "role": "weave_host",
454                "balance": { "usd": 12.4, "state": "ok", "free_hours_left": 494.8, "usd_per_hour": 0.09 } })
455    }
456
457    #[test]
458    fn a_list_keeps_well_formed_rows() {
459        let body = json!({
460            "computers": [row("cmp_1", "weave-host", "running"), { "name": "x" }, row("bad id", "y", "running")]
461        });
462        let Answer::Done(list) = classify(200, &body, |b| {
463            Ok(ComputerList {
464                computers: b["computers"]
465                    .as_array()
466                    .unwrap()
467                    .iter()
468                    .filter_map(checked_row)
469                    .collect(),
470            })
471        })
472        .expect("ok") else {
473            panic!("not done");
474        };
475        assert_eq!(list.computers.len(), 1);
476        assert_eq!(list.computers[0]["name"], "weave-host");
477        assert_eq!(list.computers[0]["balance"]["state"], "ok");
478    }
479
480    #[test]
481    fn refusals_pass_the_cloud_code_and_message() {
482        let body = json!({ "error": { "code": "balance_empty", "message": "Top up to start.", "next_step": "top_up" } });
483        let Answer::Refused(refusal) = classify(402, &body, row_of).expect("refusal") else {
484            panic!("not refused");
485        };
486        assert_eq!(refusal.code, "balance_empty");
487        assert_eq!(refusal.status, 402);
488        assert_eq!(refusal.message.as_deref(), Some("Top up to start."));
489        assert_eq!(refusal.next_step.as_deref(), Some("top_up"));
490        let busy = json!({ "error": { "code": "computer_busy" } });
491        let Answer::Refused(refusal) = classify(409, &busy, row_of).expect("refusal") else {
492            panic!("not refused");
493        };
494        assert_eq!(refusal.code, "computer_busy");
495        assert!(refusal.message.is_none());
496        let limited = json!({ "error": { "code": "rate_limited", "retry_after_s": 999_999 } });
497        let Answer::Refused(refusal) = classify(429, &limited, row_of).expect("refusal") else {
498            panic!("not refused");
499        };
500        assert_eq!(refusal.retry_after_s, Some(RETRY_AFTER_CAP_S));
501        let bare = classify(422, &Value::Null, row_of).expect("refusal");
502        assert!(matches!(bare, Answer::Refused(r) if r.code == "http_422"));
503        let exists = json!({ "error": { "code": "invalid_state", "details": { "reason": "computer_exists" } } });
504        let Answer::Refused(refusal) = classify(409, &exists, row_of).expect("refusal") else {
505            panic!("not refused");
506        };
507        assert_eq!(refusal.reason.as_deref(), Some("computer_exists"));
508    }
509
510    #[test]
511    fn a_confirmation_carries_the_terms() {
512        let body = json!({ "error": { "code": "confirmation_required", "message": "Confirm.",
513            "details": { "billing": "free", "usd_per_hour": 0.09, "free_hours_left": 494.8, "topup_usd": 12.4 } } });
514        let Answer::Refused(refusal) = classify(428, &body, row_of).expect("refusal") else {
515            panic!("not refused");
516        };
517        assert_eq!(refusal.code, "confirmation_required");
518        let t = terms(refusal.details.as_ref());
519        assert_eq!(t.billing, Some("free"));
520        assert_eq!(t.usd_per_hour, Some(0.09));
521        assert_eq!(t.free_hours_left, Some(494.8));
522        assert_eq!(t.topup_usd, Some(12.4));
523        let odd = json!({ "billing": "maybe", "usd_per_hour": -1.0, "topup_usd": "12" });
524        let t = terms(odd.as_object());
525        assert_eq!(
526            t,
527            Terms {
528                billing: None,
529                usd_per_hour: None,
530                free_hours_left: None,
531                topup_usd: None
532            }
533        );
534        let p37 = json!({ "billing": "billed", "balance_usd": 3.5 });
535        assert_eq!(terms(p37.as_object()).topup_usd, Some(3.5));
536        assert_eq!(terms(None).billing, None);
537    }
538
539    #[test]
540    fn a_run_start_body_carries_no_code_and_no_task() {
541        let body =
542            serde_json::to_value(RunStartRequest::confirmed("req_12345678".into())).expect("json");
543        let mut keys: Vec<&str> = body
544            .as_object()
545            .expect("object")
546            .keys()
547            .map(String::as_str)
548            .collect();
549        keys.sort_unstable();
550        assert_eq!(keys, ["confirm", "purpose", "request_id"]);
551        assert_eq!(body["purpose"], "run");
552        assert_eq!(body["confirm"], true);
553    }
554
555    #[test]
556    fn run_terms_come_from_the_list_row() {
557        let row = json!({ "id": "cmp_1", "name": "dev", "state": "stopped",
558            "price": { "usd_per_hour": 0.09 },
559            "balance": { "usd": 12.4, "free_hours_left": 494.8, "usd_per_hour": 0.08 } });
560        let t = run_terms(row.as_object().expect("row"));
561        assert_eq!(
562            t.billing,
563            Some("billed"),
564            "a run is billed from the first minute"
565        );
566        assert_eq!(t.usd_per_hour, Some(0.09));
567        assert_eq!(t.topup_usd, Some(12.4));
568        assert_eq!(
569            t.free_hours_left, None,
570            "free hours are a weave_host's, never a run's"
571        );
572        let bare = json!({ "id": "cmp_1", "name": "dev", "state": "stopped",
573            "balance": { "usd_per_hour": 0.09, "usd": "x" } });
574        let t = run_terms(bare.as_object().expect("row"));
575        assert_eq!(t.usd_per_hour, Some(0.09));
576        assert_eq!(t.topup_usd, None);
577    }
578
579    #[test]
580    fn an_unconfirmed_run_start_is_never_sent() {
581        let client = crate::transport::CloudClient::new("http://127.0.0.1:9").expect("client");
582        let mut request = RunStartRequest::confirmed("req_12345678".into());
583        request.confirm = false;
584        let error = start_for_run(&on_client(&client), "cmp_1", &request).expect_err("refused");
585        assert!(error.to_string().contains("only when confirmed"), "{error}");
586    }
587
588    #[test]
589    fn a_cloud_without_computers_is_not_offered() {
590        assert_eq!(
591            classify(404, &Value::Null, row_of).expect("ok"),
592            Answer::NotOffered
593        );
594        let off = json!({ "error": { "code": "not_configured" } });
595        assert_eq!(classify(503, &off, row_of).expect("ok"), Answer::NotOffered);
596        let gone = json!({ "error": { "code": "no_computer" } });
597        assert!(
598            matches!(classify(404, &gone, row_of).expect("ok"), Answer::Refused(r) if r.code == "no_computer")
599        );
600        assert!(classify(500, &Value::Null, row_of).is_err());
601    }
602
603    #[test]
604    fn a_list_without_a_provider_is_not_offered() {
605        let off = json!({ "available": false, "computers": [] });
606        assert_eq!(list_of(200, &off).expect("ok"), Answer::NotOffered);
607        let on = json!({ "available": true, "computers": [row("cmp_1", "weave-host", "running")] });
608        assert!(
609            matches!(list_of(200, &on).expect("ok"), Answer::Done(l) if l.computers.len() == 1)
610        );
611        let older = json!({ "computers": [] });
612        assert!(matches!(list_of(200, &older).expect("ok"), Answer::Done(_)));
613        let write = json!({ "error": { "code": "computer_not_available", "message": "x" } });
614        assert!(
615            matches!(classify(503, &write, row_of).expect("ok"), Answer::Refused(r) if r.code == "computer_not_available")
616        );
617    }
618
619    #[test]
620    fn a_write_answer_is_the_row_or_wrapped_row() {
621        let plain = row_of(&row("cmp_1", "weave-host", "starting")).expect("row");
622        assert_eq!(plain["state"], "starting");
623        let wrapped =
624            row_of(&json!({ "computer": row("cmp_2", "w", "provisioning") })).expect("row");
625        assert_eq!(wrapped["id"], "cmp_2");
626        assert!(row_of(&json!({ "ok": true })).is_err());
627    }
628
629    #[test]
630    fn the_start_basis_follows_scope_role_and_free_hours() {
631        let row = |kind: &str, role: &str, free: Option<f64>| {
632            let mut row = json!({ "id": "cmp_1", "name": "w", "state": "stopped",
633                "scope": { "kind": kind }, "role": role });
634            if let Some(free) = free {
635                row["balance"] = json!({ "usd": 0.0, "free_hours_left": free });
636            }
637            row.as_object().cloned().expect("object")
638        };
639        let basis = |kind, role, free| start_basis(&row(kind, role, free));
640        assert_eq!(basis("team", "weave_host", Some(1.5)), Some("free"));
641        assert_eq!(basis("team", "weave_host", Some(0.0)), Some("billed"));
642        assert_eq!(basis("team", "general", Some(400.0)), Some("billed"));
643        assert_eq!(
644            basis("team", "weave_host", None),
645            None,
646            "no balance: the free hours are unknown, never guessed"
647        );
648        assert_eq!(basis("team", "weave_host", Some(f64::NAN)), None);
649        assert_eq!(basis("team", "weave_host", Some(-1.0)), None);
650        assert_eq!(
651            basis("personal", "weave_host", Some(400.0)),
652            Some("billed"),
653            "personal computers never run on the team's free hours"
654        );
655    }
656
657    #[test]
658    fn ids_and_request_ids_are_checked() {
659        assert!(valid_id("cmp_01HZX"));
660        assert!(!valid_id("cmp_../x"));
661        assert!(!valid_id("dev"));
662        assert!(valid_request_id(&new_request_id()));
663        assert!(!valid_request_id("short"));
664        assert!(!valid_request_id("req_with space_xx"));
665        let body = serde_json::to_value(CreateRequest {
666            request_id: "req_12345678".into(),
667            name: "weave-host".into(),
668            team: None,
669            role: ROLE_WEAVE_HOST.into(),
670            confirm: true,
671        })
672        .expect("json");
673        assert_eq!(body["confirm"], true);
674        assert!(
675            body.get("team").is_none(),
676            "a personal create sends no team"
677        );
678        let keys: Vec<&str> = body
679            .as_object()
680            .expect("object")
681            .keys()
682            .map(String::as_str)
683            .collect();
684        assert_eq!(
685            keys.len(),
686            4,
687            "only request_id, name, role and confirm: {keys:?}"
688        );
689        let body = serde_json::to_value(CreateRequest {
690            request_id: "req_12345678".into(),
691            name: "dev".into(),
692            team: Some("org_acme".into()),
693            role: "general".into(),
694            confirm: true,
695        })
696        .expect("json");
697        assert_eq!(
698            body,
699            json!({"request_id": "req_12345678", "name": "dev",
700                "team": "org_acme",
701                "role": "general", "confirm": true})
702        );
703    }
704}