1use 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
42const PATH: &str = "/computers";
44pub(crate) const MAX_ANSWER_BYTES: usize = 256 * 1024;
46pub const MAX_ROWS: usize = 64;
48const MAX_MESSAGE_LEN: usize = 500;
50const RETRY_AFTER_CAP_S: u64 = 86_400;
52
53pub const ROLE_WEAVE_HOST: &str = "weave_host";
55pub const ROLE_GENERAL: &str = "general";
57pub const ROLES: [&str; 2] = [ROLE_GENERAL, ROLE_WEAVE_HOST];
59
60#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
62pub struct Refusal {
63 pub status: u16,
65 pub code: String,
67 pub message: Option<String>,
69 pub next_step: Option<String>,
71 pub retry_after_s: Option<u64>,
73 pub details: Option<Map<String, Value>>,
75 pub reason: Option<String>,
78}
79
80#[derive(Debug, Clone, Copy, PartialEq, Serialize)]
83pub struct Terms {
84 pub billing: Option<&'static str>,
88 pub usd_per_hour: Option<f64>,
89 pub free_hours_left: Option<f64>,
90 pub topup_usd: Option<f64>,
92}
93
94#[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 topup_usd: num("topup_usd").or_else(|| num("balance_usd")),
116 }
117}
118
119#[derive(Debug, Clone, PartialEq)]
121pub enum Answer<T> {
122 Done(T),
123 Refused(Refusal),
124 NotOffered,
126}
127
128#[derive(Debug, Clone, PartialEq, Default)]
130pub struct ComputerList {
131 pub computers: Vec<Map<String, Value>>,
134}
135
136#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
141pub struct CreateRequest {
142 pub request_id: String,
143 pub name: String,
144 #[serde(skip_serializing_if = "Option::is_none")]
146 pub team: Option<String>,
147 pub role: String,
148 pub confirm: bool,
152}
153
154#[must_use]
157pub fn new_request_id() -> String {
158 format!("req_{}", uuid::Uuid::new_v4().simple())
159}
160
161#[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#[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
180pub type Exchange<'a> = &'a dyn Fn(&str, &str, Option<&Value>) -> Result<(u16, Value), CloudError>;
183
184pub 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
196pub 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 if status == 401 {
204 return Err(CloudError::from_response(status, &answer));
205 }
206 Ok((status, answer))
207 }
208}
209
210pub fn list(send: Exchange<'_>) -> Result<Answer<ComputerList>, CloudError> {
212 let (status, body) = send("GET", PATH, None)?;
213 list_of(status, &body)
214}
215
216fn 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
234pub 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
245pub 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#[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
283pub(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#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
336pub struct RunStartRequest {
337 pub request_id: String,
338 pub purpose: &'static str,
340 pub confirm: bool,
342}
343
344impl RunStartRequest {
345 #[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#[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
379pub 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
406pub(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
417fn 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#[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}