zc2 0.0.50

P2P compute broker with yen-denominated billing, WAL, and broker mesh support
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
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
//! The agent's hub client (spec ยง6.7): credentials re-read on change, the
//! provider summary, price writes, poll backoff and new-worker price seeding.

use crate::agent::hubwire::{HubSummary, HubWorker};
use crate::agent::summary::NetworkCapacity;
use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime};

#[derive(Debug, Clone, PartialEq)]
pub struct Credentials {
    pub api_key: String,
    pub api_url: Option<String>,
}

/// `~/.zakuro/credentials` (`api_key=โ€ฆ`, `api_url=โ€ฆ`), as `zc login` writes it.
pub fn read_credentials(path: &Path) -> Option<Credentials> {
    let m = crate::credentials::parse(&std::fs::read_to_string(path).ok()?);
    let api_key = m.get("api_key")?.trim().to_string();
    if api_key.is_empty() {
        return None;
    }
    Some(Credentials {
        api_key,
        api_url: m.get("api_url").cloned().filter(|u| !u.trim().is_empty()),
    })
}

/// Credentials re-read only when the file's modification time changes, so a
/// fresh `zc login` takes effect without restarting the agent.
pub struct CredWatch {
    path: PathBuf,
    mtime: Option<SystemTime>,
    cached: Option<Credentials>,
    loaded: bool,
}

impl CredWatch {
    pub fn new(path: PathBuf) -> Self {
        Self {
            path,
            mtime: None,
            cached: None,
            loaded: false,
        }
    }

    pub fn current(&mut self) -> Option<Credentials> {
        let mtime = std::fs::metadata(&self.path)
            .and_then(|m| m.modified())
            .ok();
        if !self.loaded || mtime != self.mtime {
            self.loaded = true;
            self.mtime = mtime;
            self.cached = read_credentials(&self.path);
        }
        self.cached.clone()
    }
}

#[derive(Debug, Clone, PartialEq)]
pub enum HubError {
    /// 401: the key is missing, wrong or revoked โ†’ `not_logged_in`.
    Unauthorized,
    /// 404: the hub predates the route โ†’ `hub_too_old`.
    NotFound,
    Status(u16, String),
    /// The request never reached the hub: DNS, a refused connection, a reset,
    /// a timeout. Carries reqwest's message with its `source` chain folded in.
    Transport(String),
    /// The hub answered, but its body is not the document we asked for.
    Decode(String),
}

/// The one next step for a failure that never reached the hub. The host may
/// be published only inside a tunnel, and `zc status`'s "connected to zakuro
/// mesh" is a different tunnel from the one the hub needs.
const VPN_HINT: &str = "this host may answer only over a VPN tunnel: check that the tunnel carrying it is up (the zakuro mesh is a different one)";

impl HubError {
    pub fn message(&self) -> String {
        match self {
            HubError::Unauthorized => "the hub rejected this Mac's key (401)".into(),
            HubError::NotFound => "the hub does not have this route yet (404)".into(),
            HubError::Status(s, body) => format!("hub answered HTTP {s}: {body}"),
            HubError::Transport(e) => format!("could not reach the hub: {e}"),
            HubError::Decode(e) => format!("the hub's answer could not be read: {e}"),
        }
    }

    /// The next step to show beside `message()`, for the failures that have
    /// one. Only a connection-level failure gets it: a hub that answered --
    /// with a status, or with a body we couldn't read -- is not a tunnel
    /// problem, and blaming one would send the owner the wrong way.
    pub fn detail(&self) -> Option<String> {
        match self {
            HubError::Transport(_) => Some(VPN_HINT.to_string()),
            _ => None,
        }
    }
}

/// How much of a hub error body `hub.error` and a 502 message carry.
const HUB_ERROR_MAX_CHARS: usize = 200;

/// Whitespace runs collapsed to one space, cut to `HUB_ERROR_MAX_CHARS`
/// characters on a char boundary and marked `โ€ฆ`, so neither a proxy's HTML
/// error page nor a long error chain ever lands whole in the app.
fn one_short_line(text: &str) -> String {
    let text = text.split_whitespace().collect::<Vec<_>>().join(" ");
    match text.char_indices().nth(HUB_ERROR_MAX_CHARS) {
        Some((cut, _)) => format!("{}โ€ฆ", &text[..cut]),
        None => text,
    }
}

/// The readable part of a non-2xx hub body: FastAPI's `detail` when it is a
/// string, otherwise the body itself, as one short line.
fn readable_error(body: &str) -> String {
    let detail = serde_json::from_str::<serde_json::Value>(body)
        .ok()
        .and_then(|v| v.get("detail")?.as_str().map(str::to_string));
    one_short_line(detail.as_deref().unwrap_or(body))
}

/// An error plus every distinct message under it, joined with `: `. reqwest
/// says only "error sending request for url (โ€ฆ)"; whether that was a reset, a
/// refused connection, a DNS failure or a timeout is in its `source` chain,
/// and that is the part an owner can act on.
fn error_chain(e: &(dyn std::error::Error + 'static)) -> String {
    let mut parts: Vec<String> = Vec::new();
    let mut next: Option<&(dyn std::error::Error + 'static)> = Some(e);
    while let Some(err) = next {
        let msg = err.to_string();
        // A layer that only repeats what is already there adds nothing.
        if !msg.is_empty() && !parts.iter().any(|p| p.contains(&msg)) {
            parts.push(msg);
        }
        next = err.source();
    }
    one_short_line(&parts.join(": "))
}

fn classify(status: u16, body: String) -> HubError {
    match status {
        401 => HubError::Unauthorized,
        404 => HubError::NotFound,
        s => HubError::Status(s, readable_error(&body)),
    }
}

/// How a hub offers call failed, kept apart from `HubError` because the
/// offers routes pass a hub rejection through (status, `code`, `detail`)
/// instead of folding it into `hub.error`.
#[derive(Debug, Clone, PartialEq)]
pub enum OfferError {
    /// The request never reached the hub (or its answer was unreadable).
    Unreachable(String),
    /// The hub answered 4xx/5xx: its status, a machine `code` when the body
    /// carried one, and a readable message (FastAPI's `detail`).
    Rejected {
        status: u16,
        code: Option<String>,
        message: String,
    },
}

/// `code` and `message` out of a hub error body. FastAPI sends
/// `{"detail": "text"}`; a hub may also send `{"code", "detail"}` or
/// `{"detail": {"code", "message"}}`, and the hub's own envelope
/// `{"errors": [..]}` or `{"detail": {"errors": [..]}}`.
fn offer_rejection(status: u16, body: &str) -> OfferError {
    let v = serde_json::from_str::<serde_json::Value>(body).unwrap_or_default();
    let detail = v.get("detail");
    let code = v
        .get("code")
        .or_else(|| detail.and_then(|d| d.get("code")))
        .or_else(|| v.get("error").and_then(|e| e.get("code")))
        .and_then(|c| c.as_str())
        .map(str::to_string);
    let first_error = |x: &serde_json::Value| x.get("errors")?.get(0)?.as_str().map(str::to_string);
    let message = detail
        .and_then(|d| {
            d.as_str()
                .or_else(|| d.get("message").and_then(|m| m.as_str()))
                .map(str::to_string)
                .or_else(|| first_error(d))
        })
        .or_else(|| first_error(&v))
        .map(|m| one_short_line(&m))
        .unwrap_or_else(|| readable_error(body));
    OfferError::Rejected {
        status,
        code,
        message,
    }
}

#[derive(Clone)]
pub struct HubClient {
    http: reqwest::Client,
    base: String,
    key: String,
}

impl HubClient {
    pub fn new(base: &str, key: &str, timeout: Duration) -> Self {
        Self {
            http: reqwest::Client::builder()
                .timeout(timeout)
                .build()
                .expect("reqwest client builds with rustls"),
            base: base.trim_end_matches('/').to_string(),
            key: key.to_string(),
        }
    }

    async fn send(&self, req: reqwest::RequestBuilder) -> Result<String, HubError> {
        let resp = req
            .bearer_auth(&self.key)
            .send()
            .await
            .map_err(|e| HubError::Transport(error_chain(&e)))?;
        let status = resp.status().as_u16();
        let body = resp.text().await.unwrap_or_default();
        if (200..300).contains(&status) {
            Ok(body)
        } else {
            Err(classify(status, body))
        }
    }

    async fn send_offer(
        &self,
        req: reqwest::RequestBuilder,
    ) -> Result<serde_json::Value, OfferError> {
        let resp = req
            .bearer_auth(&self.key)
            .send()
            .await
            .map_err(|e| OfferError::Unreachable(error_chain(&e)))?;
        let status = resp.status().as_u16();
        let body = resp.text().await.unwrap_or_default();
        if !(200..300).contains(&status) {
            return Err(offer_rejection(status, &body));
        }
        serde_json::from_str(&body).map_err(|e| {
            OfferError::Unreachable(format!("the hub's answer could not be read: {e}"))
        })
    }

    /// `GET /api/provide/offers?node=`: the environment catalogue with this
    /// node's subscriptions. The body is returned as the hub sent it.
    pub async fn offers(&self, node: &str) -> Result<serde_json::Value, OfferError> {
        self.send_offer(
            self.http
                .get(format!("{}/api/provide/offers", self.base))
                .query(&[("node", node)]),
        )
        .await
    }

    /// `PUT /api/provide/offers/{template_id}`: subscribe, reprice or
    /// unsubscribe this node. Returns the hub's single offer object.
    pub async fn put_offer(
        &self,
        template_id: &str,
        body: &serde_json::Value,
    ) -> Result<serde_json::Value, OfferError> {
        let mut url = reqwest::Url::parse(&format!("{}/api/provide/offers/", self.base))
            .map_err(|e| OfferError::Unreachable(format!("bad hub url: {e}")))?;
        url.path_segments_mut()
            .map_err(|_| OfferError::Unreachable("bad hub url".into()))?
            .pop_if_empty()
            .push(template_id);
        self.send_offer(self.http.put(url).json(body)).await
    }

    /// `GET /api/provide/summary?tz=` (spec ยง5.3).
    pub async fn summary(&self, tz: &str) -> Result<HubSummary, HubError> {
        let body = self
            .send(
                self.http
                    .get(format!("{}/api/provide/summary", self.base))
                    .query(&[("tz", tz)]),
            )
            .await?;
        serde_json::from_str(&body).map_err(|e| HubError::Decode(format!("bad summary JSON: {e}")))
    }

    /// `GET /api/provide/earnings?tz=`: the account's ledger totals (today
    /// earned, this month earned and spent), for summary v2's `ledger`.
    pub async fn earnings(
        &self,
        tz: &str,
    ) -> Result<crate::agent::hubwire::HubEarningsSummary, HubError> {
        let body = self
            .send(
                self.http
                    .get(format!("{}/api/provide/earnings", self.base))
                    .query(&[("tz", tz)]),
            )
            .await?;
        serde_json::from_str(&body).map_err(|e| HubError::Decode(format!("bad earnings JSON: {e}")))
    }

    /// `GET /api/provide/ledger?from=&to=&tz=`: the provider ledger, rows of
    /// `{day, node, product, earned, spent, fake_earned}` with `by_day`,
    /// `by_node`, `by_product` and `totals`, in yen. Returned as the hub sent
    /// it (`/v2/ledger` reshapes it).
    pub async fn provide_ledger(
        &self,
        from: Option<&str>,
        to: Option<&str>,
        tz: &str,
    ) -> Result<serde_json::Value, HubError> {
        let mut q: Vec<(&str, &str)> = vec![("tz", tz)];
        if let Some(f) = from {
            q.push(("from", f));
        }
        if let Some(t) = to {
            q.push(("to", t));
        }
        let body = self
            .send(
                self.http
                    .get(format!("{}/api/provide/ledger", self.base))
                    .query(&q),
            )
            .await?;
        serde_json::from_str(&body).map_err(|e| HubError::Decode(format!("bad ledger JSON: {e}")))
    }

    /// `PUT /api/workers/{id}/price`: `null` means "use the account default".
    pub async fn put_worker_price(&self, id: i64, price: Option<f64>) -> Result<(), HubError> {
        self.send(
            self.http
                .put(format!("{}/api/workers/{id}/price", self.base))
                .json(&serde_json::json!({ "price_per_hour": price })),
        )
        .await
        .map(|_| ())
    }

    /// `PUT /api/workers/global-price`: `null` means "use the mesh price".
    pub async fn put_default_price(&self, price: Option<f64>) -> Result<(), HubError> {
        self.send(
            self.http
                .put(format!("{}/api/workers/global-price", self.base))
                .json(&serde_json::json!({ "default_price_per_hour": price })),
        )
        .await
        .map(|_| ())
    }

    /// `GET /api/status/network` (network contract ยง3-4). Authenticated with
    /// this Mac's own `zk_` provider key, in `X-Broker-Api-Key` -- the only
    /// credential the widget has -- never the `Authorization: Bearer` header
    /// the rest of this client uses, since that endpoint doesn't accept a
    /// provider key there. Any failure at all (unreachable, a non-2xx status
    /// -- including a 401 from a hub that hasn't deployed this auth path yet
    /// -- or a body that doesn't parse) is `None`: the caller treats missing
    /// network data as "nothing to report", never as an error.
    pub async fn network(&self) -> Option<NetworkCapacity> {
        let resp = self
            .http
            .get(format!("{}/api/status/network", self.base))
            .header("X-Broker-Api-Key", &self.key)
            .send()
            .await
            .ok()?;
        if !resp.status().is_success() {
            return None;
        }
        let body = resp.text().await.ok()?;
        parse_network_capacity(&body)
    }
}

/// Pull the four totals and four `_busy` figures (network contract ยง3) out
/// of a `GET /api/status/network` body. A missing `_busy` field (an older
/// hub deployed before this contract) reads as 0, the same "absent means
/// zero" convention the sync-workers side of this contract uses. Anything
/// that isn't valid JSON, or isn't an object, is `None` -- there is nothing
/// safe to default the totals to.
pub fn parse_network_capacity(body: &str) -> Option<NetworkCapacity> {
    serde_json::from_str(body).ok()
}

/// Every `base` normally; after failures 60 s โ†’ 2 min โ†’ 5 min (base 60 s).
pub fn poll_delay(base: Duration, consecutive_failures: u32) -> Duration {
    match consecutive_failures {
        0 | 1 => base,
        2 => base * 2,
        _ => base * 5,
    }
}

/// Spec ยง6.7: PUT the price on every one of this Mac's worker rows, all at
/// once, then retry each failure once (again all at once). The error lists
/// the rows that still failed. However many workers this Mac has, a device
/// price takes about two hub timeouts at worst.
pub async fn set_device_price(
    client: &HubClient,
    ids: &[i64],
    price: Option<f64>,
) -> Result<(), Vec<(i64, String)>> {
    let failed: Vec<i64> = put_prices(client, ids, price)
        .await
        .into_iter()
        .map(|(id, _)| id)
        .collect();
    let still = put_prices(client, &failed, price).await;
    if still.is_empty() {
        Ok(())
    } else {
        Err(still)
    }
}

/// PUT `price` on every row in `ids` concurrently. Returns the rows that
/// failed, with their errors, in `ids` order.
async fn put_prices(client: &HubClient, ids: &[i64], price: Option<f64>) -> Vec<(i64, String)> {
    let mut writes = tokio::task::JoinSet::new();
    for &id in ids {
        let c = client.clone();
        writes.spawn(async move { (id, c.put_worker_price(id, price).await) });
    }
    // Every row counts as failed until its write reports back, so a write
    // task that panicked is still reported instead of silently dropped.
    let mut errors: std::collections::HashMap<i64, String> = ids
        .iter()
        .map(|&id| (id, "the price write did not finish".to_string()))
        .collect();
    while let Some(joined) = writes.join_next().await {
        match joined {
            Ok((id, Ok(()))) => {
                errors.remove(&id);
            }
            Ok((id, Err(e))) => {
                errors.insert(id, e.message());
            }
            Err(_) => {}
        }
    }
    ids.iter()
        .filter_map(|id| errors.remove(id).map(|e| (*id, e)))
        .collect()
}

/// Spec ยง6.7 seeding: a worker row the agent has not seen before gets the
/// price every known sibling agrees on (an explicit value), as long as that
/// price is at least the account's minimum. A price below the minimum means
/// the owner disabled those siblings, and that is never copied onto a new
/// worker. Otherwise nothing: the hub stays the only price owner.
pub fn seed_targets(this_mac: &[&HubWorker], known: &[i64], min: f64) -> Vec<(i64, f64)> {
    let known_prices: Vec<Option<f64>> = this_mac
        .iter()
        .filter(|w| known.contains(&w.id))
        .map(|w| w.price_per_hour)
        .collect();
    let agreed = match known_prices.first() {
        Some(Some(p)) if known_prices.iter().all(|q| *q == Some(*p)) => *p,
        _ => return vec![],
    };
    if agreed < min {
        return vec![];
    }
    this_mac
        .iter()
        .filter(|w| !known.contains(&w.id) && w.price_per_hour != Some(agreed))
        .map(|w| (w.id, agreed))
        .collect()
}

/// IANA zone for the summary's `?tz=`: `$TZ`, else the `/etc/localtime` link.
pub fn system_tz() -> String {
    tz_from(
        std::env::var("TZ").ok(),
        std::fs::read_link("/etc/localtime").ok(),
    )
}

pub fn tz_from(tz_env: Option<String>, localtime_link: Option<PathBuf>) -> String {
    if let Some(tz) = tz_env.filter(|t| !t.is_empty() && !t.starts_with(':')) {
        return tz;
    }
    localtime_link
        .and_then(|p| {
            let s = p.to_string_lossy().to_string();
            s.split_once("zoneinfo/").map(|(_, z)| z.to_string())
        })
        .filter(|z| !z.is_empty())
        .unwrap_or_else(|| "UTC".to_string())
}

#[cfg(test)]
pub(crate) mod tests {
    use super::*;
    use crate::agent::files::tests::tmp;
    use crate::agent::hubwire::tests::HUB_JSON;
    use std::sync::{Arc, Mutex};

    /// (method, url, body, authorization header) of every request.
    pub(crate) type Seen = Arc<Mutex<Vec<(String, String, String, Option<String>)>>>;

    /// A hub on a free loopback port. `handler(method, url, nth_time_this_url)`
    /// returns (status, JSON body).
    pub(crate) fn mock_hub<F>(handler: F) -> (String, Seen)
    where
        F: Fn(&str, &str, usize) -> (u16, String) + Send + 'static,
    {
        let server = tiny_http::Server::http("127.0.0.1:0").unwrap();
        let port = server.server_addr().to_ip().unwrap().port();
        let seen: Seen = Default::default();
        let log = seen.clone();
        std::thread::spawn(move || {
            for mut req in server.incoming_requests() {
                let mut body = String::new();
                let _ = std::io::Read::read_to_string(req.as_reader(), &mut body);
                let method = req.method().as_str().to_string();
                let url = req.url().to_string();
                let auth = req
                    .headers()
                    .iter()
                    .find(|h| h.field.equiv("Authorization"))
                    .map(|h| h.value.as_str().to_string());
                let nth = {
                    let mut l = log.lock().unwrap();
                    l.push((method.clone(), url.clone(), body, auth));
                    l.iter().filter(|e| e.1 == url).count()
                };
                let (status, reply) = handler(&method, &url, nth);
                let _ = req.respond(
                    tiny_http::Response::from_string(reply)
                        .with_status_code(status)
                        .with_header(
                            tiny_http::Header::from_bytes("Content-Type", "application/json")
                                .unwrap(),
                        ),
                );
            }
        });
        (format!("http://127.0.0.1:{port}"), seen)
    }

    fn block_on<F: std::future::Future>(f: F) -> F::Output {
        tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .unwrap()
            .block_on(f)
    }

    #[test]
    fn credentials_are_reread_only_when_the_file_changes() {
        let dir = tmp("creds");
        std::fs::create_dir_all(&dir).unwrap();
        let p = dir.join("credentials");
        std::fs::write(
            &p,
            "api_key=zk_1_aaa\napi_url=https://stg.api.zakuro-ai.com\n",
        )
        .unwrap();
        let mut w = CredWatch::new(p.clone());
        let first = w.current().unwrap();
        assert_eq!(first.api_key, "zk_1_aaa");
        assert_eq!(
            first.api_url.as_deref(),
            Some("https://stg.api.zakuro-ai.com")
        );

        std::fs::write(&p, "api_key=zk_1_bbb\n").unwrap();
        std::fs::File::options()
            .write(true)
            .open(&p)
            .unwrap()
            .set_modified(std::time::SystemTime::now() + Duration::from_secs(5))
            .unwrap();
        assert_eq!(
            w.current().unwrap().api_key,
            "zk_1_bbb",
            "zc login applies without a restart"
        );

        std::fs::write(&p, "api_url=x\n").unwrap();
        assert_eq!(read_credentials(&p), None, "no key, no credentials");
    }

    #[test]
    fn summary_sends_the_key_and_tz_and_classifies_errors() {
        let (hub, seen) = mock_hub(|_, url, _| match url {
            u if u.starts_with("/api/provide/summary") => (200, HUB_JSON.to_string()),
            "/unauthorized" => (401, "{}".into()),
            _ => (404, "{}".into()),
        });
        let c = HubClient::new(&hub, "zk_1_x", Duration::from_secs(5));
        let s = block_on(c.summary("Asia/Tokyo")).unwrap();
        assert_eq!(s.account.username, "jean");
        let (method, url, _, auth) = seen.lock().unwrap()[0].clone();
        assert_eq!(method, "GET");
        assert_eq!(url, "/api/provide/summary?tz=Asia%2FTokyo");
        assert_eq!(auth.as_deref(), Some("Bearer zk_1_x"));

        assert_eq!(classify(401, "{}".into()), HubError::Unauthorized);
        assert_eq!(classify(404, "{}".into()), HubError::NotFound);
        assert_eq!(
            classify(500, "boom".into()),
            HubError::Status(500, "boom".into())
        );

        let dead = HubClient::new("http://127.0.0.1:1", "k", Duration::from_secs(2));
        assert!(matches!(
            block_on(dead.summary("UTC")),
            Err(HubError::Transport(_))
        ));
    }

    #[test]
    fn offers_get_and_put_carry_the_node_the_key_and_the_hub_error() {
        let (hub, seen) = mock_hub(|m, url, _| match (m, url) {
            ("GET", "/api/provide/offers?node=pk%2B1%3D") => (200, r#"{"offers":[]}"#.into()),
            ("PUT", "/api/provide/offers/py%20x") => (200, r#"{"subscribed":true}"#.into()),
            ("PUT", "/api/provide/offers/bad") => (
                422,
                r#"{"detail":{"code":"bad_price","message":"price must be > 0"}}"#.into(),
            ),
            ("PUT", "/api/provide/offers/gone") => (404, r#"{"detail":"unknown template"}"#.into()),
            ("PUT", "/api/provide/offers/nokey") => (401, "{}".into()),
            ("PUT", "/api/provide/offers/nonode") => {
                (404, r#"{"detail":{"errors":["No such node"]}}"#.into())
            }
            ("PUT", "/api/provide/offers/notmine") => {
                (403, r#"{"errors":["not your node"]}"#.into())
            }
            _ => (500, "boom".into()),
        });
        let c = HubClient::new(&hub, "zk_1_x", Duration::from_secs(5));
        assert_eq!(
            block_on(c.offers("pk+1=")).unwrap(),
            serde_json::json!({"offers": []})
        );
        assert_eq!(seen.lock().unwrap()[0].3.as_deref(), Some("Bearer zk_1_x"));
        let body = serde_json::json!({"node":"n","subscribed":true});
        assert!(block_on(c.put_offer("py x", &body)).is_ok());
        assert_eq!(seen.lock().unwrap()[1].2, body.to_string());
        assert_eq!(
            block_on(c.put_offer("bad", &body)).unwrap_err(),
            OfferError::Rejected {
                status: 422,
                code: Some("bad_price".into()),
                message: "price must be > 0".into()
            }
        );
        assert_eq!(
            block_on(c.put_offer("gone", &body)).unwrap_err(),
            OfferError::Rejected {
                status: 404,
                code: None,
                message: "unknown template".into()
            }
        );
        for (id, status, message) in [
            ("nonode", 404, "No such node"),
            ("notmine", 403, "not your node"),
        ] {
            assert_eq!(
                block_on(c.put_offer(id, &body)).unwrap_err(),
                OfferError::Rejected {
                    status,
                    code: None,
                    message: message.into()
                }
            );
        }
        assert!(matches!(
            block_on(c.put_offer("nokey", &body)),
            Err(OfferError::Rejected { status: 401, .. })
        ));
        let dead = HubClient::new("http://127.0.0.1:1", "k", Duration::from_secs(2));
        assert!(matches!(
            block_on(dead.offers("n")),
            Err(OfferError::Unreachable(_))
        ));
    }

    #[test]
    fn device_price_fans_out_and_retries_each_failure_once() {
        let (hub, seen) = mock_hub(|_, url, nth| match (url, nth) {
            ("/api/workers/12/price", 1) => (500, r#"{"detail":"flaky"}"#.into()),
            ("/api/workers/13/price", _) => (500, r#"{"detail":"down"}"#.into()),
            _ => (200, "{}".into()),
        });
        let c = HubClient::new(&hub, "zk_1_x", Duration::from_secs(5));
        assert_eq!(
            block_on(set_device_price(&c, &[11, 12], Some(18.0))),
            Ok(())
        );
        let bodies: Vec<(String, String, String)> = seen
            .lock()
            .unwrap()
            .iter()
            .map(|(m, u, b, _)| (m.clone(), u.clone(), b.clone()))
            .collect();
        assert_eq!(bodies.len(), 3, "11, 12 (failed), 12 (retry)");
        assert!(bodies
            .iter()
            .all(|(m, _, b)| m == "PUT" && b == r#"{"price_per_hour":18.0}"#));

        let err = block_on(set_device_price(&c, &[13], None)).unwrap_err();
        assert_eq!(err.len(), 1);
        assert_eq!(err[0].0, 13);
        assert!(err[0].1.contains("down"));
    }

    /// A non-2xx hub answer ends up in `hub.error` and in the 502s the app
    /// shows: FastAPI's `detail` string when there is one, otherwise the body
    /// trimmed and cut to about 200 characters, never a proxy's whole HTML page.
    #[test]
    fn hub_error_text_is_the_detail_or_a_short_trimmed_body() {
        let msg = |status: u16, body: &str| classify(status, body.to_string()).message();
        assert_eq!(
            msg(403, r#"{"detail":"Not your worker"}"#),
            "hub answered HTTP 403: Not your worker"
        );
        assert_eq!(msg(500, "  boom \n"), "hub answered HTTP 500: boom");

        let page = format!(
            "<!DOCTYPE html>\n<html><head><title>502 Bad Gateway</title></head>\n<body>{}</body></html>\n",
            "<p>nginx</p>".repeat(100)
        );
        let m = msg(502, &page);
        assert!(
            m.starts_with("hub answered HTTP 502: <!DOCTYPE html> <html>"),
            "{m}"
        );
        assert!(!m.contains("</html>"), "never the whole page: {m}");
        assert!(m.chars().count() < 240, "{} chars: {m}", m.chars().count());

        let m = msg(
            422,
            r#"{"detail":[{"loc":["body","price_per_hour"],"msg":"bad"}]}"#,
        );
        assert!(
            m.contains("price_per_hour"),
            "a non-string detail falls back to the body: {m}"
        );

        let m = msg(500, &"รฉ".repeat(400));
        assert!(m.ends_with('โ€ฆ'), "{m}");
        assert_eq!(
            m.chars().filter(|c| *c == 'รฉ').count(),
            200,
            "cut on a char boundary"
        );
    }

    /// reqwest itself says only "error sending request for url (โ€ฆ)": the
    /// reason lives further down its `source` chain. A refused connection and
    /// a timeout must read differently, and a connection-level failure carries
    /// the one next step an operator can act on: the tunnel that host needs.
    #[test]
    fn a_connection_failure_names_its_cause_and_points_at_the_vpn() {
        let refused = HubClient::new("http://127.0.0.1:1", "zk_1_x", Duration::from_secs(2));
        let err = block_on(refused.summary("UTC")).unwrap_err();
        let msg = err.message();
        assert!(
            msg.to_lowercase().contains("connection refused"),
            "the cause, not just the url: {msg}"
        );
        let detail = err
            .detail()
            .expect("a connection failure carries a next step");
        assert!(
            detail.to_lowercase().contains("vpn"),
            "the next step names the tunnel: {detail}"
        );

        // Same hub, same client, a different cause: the two must not read alike.
        let (hub, _) = mock_hub(|_, _, _| {
            std::thread::sleep(Duration::from_millis(800));
            (200, "{}".into())
        });
        let slow = HubClient::new(&hub, "zk_1_x", Duration::from_millis(200));
        let timed_out = block_on(slow.summary("UTC")).unwrap_err().message();
        assert!(
            timed_out.to_lowercase().contains("timed out"),
            "a timeout says so: {timed_out}"
        );
        assert_ne!(msg, timed_out);
    }

    /// The VPN line is for failures that never reached the hub. A hub that
    /// answered -- with a status, or with a body that isn't a summary -- is
    /// not a tunnel problem, and saying so would send an operator the wrong way.
    #[test]
    fn only_a_connection_failure_blames_the_tunnel() {
        assert_eq!(classify(500, "boom".into()).detail(), None);
        assert_eq!(classify(403, "{}".into()).detail(), None);
        assert_eq!(HubError::Unauthorized.detail(), None);
        assert_eq!(HubError::NotFound.detail(), None);

        let (hub, _) = mock_hub(|_, _, _| (200, "not a summary".into()));
        let c = HubClient::new(&hub, "zk_1_x", Duration::from_secs(5));
        let err = block_on(c.summary("UTC")).unwrap_err();
        assert_eq!(err.detail(), None, "the hub answered: {}", err.message());
        assert!(err.message().contains("summary"), "{}", err.message());
    }

    /// Every row's PUT is in flight at the same time, so a device price takes
    /// about two hub timeouts at worst, however many workers this Mac has.
    #[test]
    fn device_price_puts_are_sent_concurrently() {
        use std::sync::atomic::{AtomicUsize, Ordering};
        let server = tiny_http::Server::http("127.0.0.1:0").unwrap();
        let port = server.server_addr().to_ip().unwrap().port();
        let in_flight = Arc::new(AtomicUsize::new(0));
        let peak = Arc::new(AtomicUsize::new(0));
        let (now, most) = (in_flight.clone(), peak.clone());
        // Each request is held on its own thread, so the hub itself never
        // serializes them.
        std::thread::spawn(move || {
            for req in server.incoming_requests() {
                let (now, most) = (now.clone(), most.clone());
                std::thread::spawn(move || {
                    most.fetch_max(now.fetch_add(1, Ordering::SeqCst) + 1, Ordering::SeqCst);
                    std::thread::sleep(Duration::from_millis(600));
                    now.fetch_sub(1, Ordering::SeqCst);
                    let _ = req.respond(tiny_http::Response::from_string("{}"));
                });
            }
        });
        let c = HubClient::new(
            &format!("http://127.0.0.1:{port}"),
            "zk_1_x",
            Duration::from_secs(5),
        );
        let ids = [11, 12, 13, 14];
        assert_eq!(block_on(set_device_price(&c, &ids, Some(18.0))), Ok(()));
        assert_eq!(
            peak.load(Ordering::SeqCst),
            ids.len(),
            "every worker's PUT was in flight at once"
        );
    }

    #[test]
    fn default_price_writes_the_global_price() {
        let (hub, seen) = mock_hub(|_, _, _| (200, "{}".into()));
        let c = HubClient::new(&hub, "zk_1_x", Duration::from_secs(5));
        block_on(c.put_default_price(None)).unwrap();
        let (m, u, b, _) = seen.lock().unwrap()[0].clone();
        assert_eq!(
            (m.as_str(), u.as_str(), b.as_str()),
            (
                "PUT",
                "/api/workers/global-price",
                r#"{"default_price_per_hour":null}"#
            )
        );
    }

    #[test]
    fn poll_backs_off_60s_2min_5min() {
        let base = Duration::from_secs(60);
        let secs: Vec<u64> = (0..5).map(|n| poll_delay(base, n).as_secs()).collect();
        assert_eq!(secs, vec![60, 60, 120, 300, 300]);
    }

    #[test]
    fn new_workers_get_the_price_their_known_siblings_agree_on() {
        let w = |id: i64, price: Option<f64>| crate::agent::hubwire::HubWorker {
            id,
            worker_id: format!("fp-w{id}"),
            status: "online".into(),
            last_seen: None,
            price_per_hour: price,
            reported_price_per_hour: None,
            effective_price_per_hour: price,
            disabled: false,
        };
        let (a, b, new) = (w(11, Some(18.0)), w(12, Some(18.0)), w(13, None));
        assert_eq!(
            seed_targets(&[&a, &b, &new], &[11, 12], 1.0),
            vec![(13, 18.0)]
        );
        let c = w(12, Some(20.0));
        assert_eq!(
            seed_targets(&[&a, &c, &new], &[11, 12], 1.0),
            vec![],
            "siblings disagree"
        );
        let (d, e) = (w(11, None), w(12, None));
        assert_eq!(
            seed_targets(&[&d, &e, &new], &[11, 12], 1.0),
            vec![],
            "inherited: nothing to copy"
        );
        assert_eq!(
            seed_targets(&[&a, &new], &[], 1.0),
            vec![],
            "no known sibling yet"
        );
    }

    #[test]
    fn seeding_never_copies_a_price_below_the_minimum() {
        let w = |id: i64, price: Option<f64>| crate::agent::hubwire::HubWorker {
            id,
            worker_id: format!("fp-w{id}"),
            status: "online".into(),
            last_seen: None,
            price_per_hour: price,
            reported_price_per_hour: None,
            effective_price_per_hour: price,
            disabled: false,
        };
        let (a, b, new) = (w(11, Some(-1.0)), w(12, Some(-1.0)), w(13, None));
        assert_eq!(
            seed_targets(&[&a, &b, &new], &[11, 12], 1.0),
            vec![],
            "an owner-disabled price is not seeded onto a new worker"
        );
    }

    /// The contract's own example (network contract ยง5) parses into the
    /// eight fields; an older hub that hasn't shipped the `_busy` figures
    /// yet reads them as 0 rather than failing the whole parse.
    #[test]
    fn parses_the_contract_example_and_defaults_missing_busy_figures() {
        let full = parse_network_capacity(
            r#"{"workers": 31, "workers_busy": 4, "cpu_cores": 96, "cpu_cores_busy": 12,
                "ram_gb": 512, "ram_gb_busy": 64, "gpus": 8, "gpus_busy": 2}"#,
        )
        .unwrap();
        assert_eq!(
            full,
            NetworkCapacity {
                workers: 31,
                workers_busy: 4,
                cpu_cores: 96,
                cpu_cores_busy: 12,
                ram_gb: 512,
                ram_gb_busy: 64,
                gpus: 8,
                gpus_busy: 2,
            }
        );

        let old_hub =
            parse_network_capacity(r#"{"workers": 31, "cpu_cores": 96, "ram_gb": 512, "gpus": 8}"#)
                .unwrap();
        assert_eq!(
            old_hub,
            NetworkCapacity {
                workers: 31,
                workers_busy: 0,
                cpu_cores: 96,
                cpu_cores_busy: 0,
                ram_gb: 512,
                ram_gb_busy: 0,
                gpus: 8,
                gpus_busy: 0,
            }
        );

        // The live endpoint returns two fields this struct has no use for.
        // They must be ignored rather than refused: a reader that rejects
        // unknown fields would stop parsing the real hub's answer entirely,
        // and the widget would silently lose the section.
        let with_extras = parse_network_capacity(
            r#"{"workers": 31, "workers_busy": 4, "cpu_cores": 96, "cpu_cores_busy": 12,
                "ram_gb": 512, "ram_gb_busy": 64, "gpus": 8, "gpus_busy": 2,
                "brokers_reporting": 3, "workers_without_broker": 1}"#,
        )
        .expect("the endpoint's own extra fields must not break the parse");
        assert_eq!(with_extras, full);

        // The totals, unlike the `_busy` figures, have no safe default, so a
        // body missing them is no answer at all rather than a zeroed one.
        assert!(parse_network_capacity(r#"{"extra": "field"}"#).is_none());
        assert!(parse_network_capacity("not json").is_none());
        assert!(parse_network_capacity("[]").is_none());
    }

    /// `network()` authenticates with `X-Broker-Api-Key`, never `Authorization`
    /// -- the widget's only credential is a provider key, and this endpoint
    /// doesn't accept it as a bearer token.
    #[test]
    fn network_authenticates_with_the_broker_api_key_header() {
        let (hub, seen) = mock_hub(|_, url, _| match url {
            "/api/status/network" => (
                200,
                r#"{"workers": 2, "workers_busy": 1, "cpu_cores": 8, "cpu_cores_busy": 4,
                    "ram_gb": 32, "ram_gb_busy": 16, "gpus": 1, "gpus_busy": 0}"#
                    .to_string(),
            ),
            _ => (404, "{}".into()),
        });
        let c = HubClient::new(&hub, "zk_1_x", Duration::from_secs(5));
        let n = block_on(c.network()).expect("the mock answered 200");
        assert_eq!((n.workers, n.workers_busy), (2, 1));
        let (method, url, _, auth) = seen.lock().unwrap()[0].clone();
        assert_eq!(
            (method.as_str(), url.as_str()),
            ("GET", "/api/status/network")
        );
        assert_eq!(auth, None, "no Authorization header is sent");
    }

    /// A 401 -- exactly what today's staging hub returns, since its side of
    /// this auth isn't deployed yet -- is "no data", not an error: nothing
    /// here may ever propagate up and break the rest of the summary.
    #[test]
    fn network_treats_any_failure_as_no_data() {
        let (hub, _) = mock_hub(|_, _, _| (401, "{}".into()));
        let c = HubClient::new(&hub, "zk_1_x", Duration::from_secs(5));
        assert_eq!(block_on(c.network()), None);

        let unreachable = HubClient::new("http://127.0.0.1:1", "zk_1_x", Duration::from_secs(2));
        assert_eq!(block_on(unreachable.network()), None);

        let (bad_body, _) = mock_hub(|_, _, _| (200, "not json".into()));
        let c = HubClient::new(&bad_body, "zk_1_x", Duration::from_secs(5));
        assert_eq!(block_on(c.network()), None);
    }

    #[test]
    fn tz_prefers_tz_then_the_localtime_link() {
        assert_eq!(tz_from(Some("Europe/Paris".into()), None), "Europe/Paris");
        assert_eq!(
            tz_from(None, Some("/var/db/timezone/zoneinfo/Asia/Tokyo".into())),
            "Asia/Tokyo"
        );
        assert_eq!(
            tz_from(Some(String::new()), Some("/usr/share/zoneinfo/UTC".into())),
            "UTC"
        );
        assert_eq!(tz_from(None, None), "UTC");
    }
}