graphforge-cli 0.6.0

GraphForge command-line interface
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
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
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
//! Shared HTTPS plumbing for Hub clone and publish.
//!
//! HTTPS only, public addresses only, no proxies, manually bounded redirects
//! for public reads, no redirects for writes, and bounded response bodies.

use graphforge_discovery::RepositoryIdentity;
use graphforge_hub_publish::{HubMethod, HubRequest, HubResponse};
use sha2::{Digest as _, Sha256};
use std::fmt::Write as _;
use std::io::{self, Read};
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use std::time::Duration;
use ureq::unversioned::resolver::{DefaultResolver, ResolvedSocketAddrs, Resolver};
use ureq::unversioned::transport::{
    Buffers, ConnectionDetails, Connector, DefaultConnector, NextTimeout,
};
use url::Url;

mod discovery_auth;
#[cfg(test)]
#[path = "hub_http_range_tests.rs"]
mod hub_http_range_tests;
mod repository_moves;
pub(crate) use discovery_auth::{DiscoveryCredentials, fetch_discovery_with_attempts};
pub(crate) use repository_moves::RepositoryMoveTransport;

pub(crate) const DEFAULT_HUB: &str = "https://graphforge.sh";
pub(crate) const MAX_METADATA_BYTES: usize = 16 * 1024 * 1024;
pub(crate) const MAX_REDIRECTS: usize = 4;

#[derive(Debug)]
struct PublicResolver(DefaultResolver);

impl Resolver for PublicResolver {
    fn resolve(
        &self,
        uri: &ureq::http::Uri,
        config: &ureq::config::Config,
        timeout: ureq::unversioned::transport::NextTimeout,
    ) -> Result<ResolvedSocketAddrs, ureq::Error> {
        let addresses = self.0.resolve(uri, config, timeout)?;
        let mut approved = self.empty();
        for address in addresses
            .iter()
            .copied()
            .filter(|address| public_ip(address.ip()))
        {
            approved.push(address);
        }
        if approved.is_empty() {
            Err(ureq::Error::HostNotFound)
        } else {
            Ok(approved)
        }
    }
}

pub(crate) fn public_ip(ip: IpAddr) -> bool {
    match ip {
        IpAddr::V4(ip) => public_v4(ip),
        IpAddr::V6(ip) => {
            if let Some(v4) = ip.to_ipv4_mapped() {
                return public_v4(v4);
            }
            !(ip.is_unspecified()
                || ip.is_loopback()
                || ip.is_multicast()
                || in_v6(ip, "fc00::".parse().unwrap(), 7)
                || in_v6(ip, "fe80::".parse().unwrap(), 10)
                || in_v6(ip, "2001:db8::".parse().unwrap(), 32))
        }
    }
}

fn public_v4(ip: Ipv4Addr) -> bool {
    let value = u32::from(ip);
    let blocked = [
        ("0.0.0.0", 8),
        ("10.0.0.0", 8),
        ("100.64.0.0", 10),
        ("127.0.0.0", 8),
        ("169.254.0.0", 16),
        ("172.16.0.0", 12),
        ("192.0.0.0", 24),
        ("192.0.2.0", 24),
        ("192.168.0.0", 16),
        ("198.18.0.0", 15),
        ("198.51.100.0", 24),
        ("203.0.113.0", 24),
        ("224.0.0.0", 4),
        ("240.0.0.0", 4),
    ];
    !blocked.iter().any(|(base, bits)| {
        let base = u32::from(base.parse::<Ipv4Addr>().unwrap());
        let mask = u32::MAX.checked_shl(32 - bits).unwrap_or(0);
        value & mask == base & mask
    })
}

fn in_v6(ip: Ipv6Addr, base: Ipv6Addr, bits: u32) -> bool {
    let mask = u128::MAX.checked_shl(128 - bits).unwrap_or(0);
    u128::from(ip) & mask == u128::from(base) & mask
}

pub(crate) struct HttpResponse {
    pub(crate) status: u16,
    pub(crate) location: Option<String>,
    pub(crate) content_range: Option<String>,
    pub(crate) etag: Option<String>,
    pub(crate) content_length: Option<u64>,
    /// `Retry-After` of an unsuccessful response, in whole seconds.
    pub(crate) retry_after: Option<u64>,
    pub(crate) body: Box<dyn Read + Send>,
}

pub(crate) trait Transport {
    /// Bind retained discovery and object grants only after exact item validation.
    fn item_descriptor_verified(
        &self,
        _url: &Url,
        _descriptor: &graphforge_discovery::ItemDescriptor,
    ) -> Result<(), graphforge_api::GfError> {
        Ok(())
    }

    /// Rebind authentication only after the caller verified both old metadata
    /// move markers. This never authorizes an object or forwards a header.
    fn repository_moved(
        &self,
        _moved: &graphforge_discovery::RepositoryMoved,
        _current: &Url,
    ) -> Result<(), graphforge_api::GfError> {
        Ok(())
    }
    fn validate(&self, url: &Url) -> Result<(), graphforge_api::GfError> {
        validate_url(url)
    }

    fn get(
        &self,
        url: &Url,
        range: Option<u64>,
        if_range: Option<&str>,
        limit: u64,
    ) -> Result<HttpResponse, graphforge_api::GfError>;

    /// Send a repository-authorized read while preserving resume validators.
    fn get_authorized(
        &self,
        _url: &Url,
        _range: Option<u64>,
        _if_range: Option<&str>,
        _limit: u64,
        _headers: &[(&str, ureq::http::HeaderValue)],
    ) -> Result<HttpResponse, graphforge_api::GfError> {
        Err(network("transport does not support authorized downloads"))
    }

    /// Send an initial discovery request with explicit, sensitive headers.
    /// This must never install default headers on the shared agent.
    fn get_discovery(
        &self,
        _url: &Url,
        _headers: &[(&str, ureq::http::HeaderValue)],
        _limit: u64,
    ) -> Result<HttpResponse, graphforge_api::GfError> {
        Err(network(
            "transport does not support authenticated discovery",
        ))
    }

    /// Send one request without following redirects and read at most `limit`
    /// response body bytes. Writes (`POST`, `PUT`) and `HEAD` use this path.
    ///
    /// The caller validates `request.url` first: control-plane URLs with
    /// [`validate_url`], data-plane upload URLs with [`validate_upload_url`].
    fn exchange(
        &self,
        _request: &HubRequest,
        _limit: usize,
    ) -> Result<HubResponse, graphforge_api::GfError> {
        Err(network("transport does not send Hub writes"))
    }
}

pub(crate) struct HttpTransport {
    pub(crate) agent: ureq::Agent,
}

impl HttpTransport {
    pub(crate) fn new() -> Self {
        Self {
            agent: read_agent(
                true,
                &READ_TIMEOUTS,
                PublicResolver(DefaultResolver::default()),
            ),
        }
    }
}

/// Bounds for Hub reads (`GET`): discovery documents and package objects.
///
/// A whole-request deadline cut every object larger than it could transfer,
/// and resume could only restart the same cut. Reads therefore bound each
/// phase instead, and the body by inactivity: every wait for response bytes
/// may last at most `idle`, however long the whole transfer takes.
pub(crate) struct ReadTimeouts {
    /// Opening the connection.
    pub(crate) connect: Duration,
    /// Sending the request head and receiving the response head.
    pub(crate) response: Duration,
    /// Longest wait for the next response bytes.
    pub(crate) idle: Duration,
}

/// Production read bounds.
pub(crate) const READ_TIMEOUTS: ReadTimeouts = ReadTimeouts {
    connect: Duration::from_secs(10),
    response: Duration::from_mins(1),
    idle: Duration::from_mins(1),
};

/// Agent for Hub reads: per-phase bounds and an idle bound on every socket
/// wait, no global or whole-body deadline.
pub(crate) fn read_agent(
    https_only: bool,
    timeouts: &ReadTimeouts,
    resolver: impl Resolver,
) -> ureq::Agent {
    let config = ureq::Agent::config_builder()
        .https_only(https_only)
        .http_status_as_error(false)
        .max_redirects(0)
        .proxy(None)
        .timeout_global(None)
        .timeout_connect(Some(timeouts.connect))
        .timeout_send_request(Some(timeouts.response))
        .timeout_recv_response(Some(timeouts.response))
        .timeout_recv_body(None)
        .build();
    ureq::Agent::with_parts(
        config,
        IdleConnector {
            inner: DefaultConnector::new(),
            idle: timeouts.idle,
        },
        resolver,
    )
}

/// Connector whose transports never wait longer than `idle` for one socket
/// read or write, so a stalled connection fails while a slow but steadily
/// progressing one never does.
#[derive(Debug)]
struct IdleConnector {
    inner: DefaultConnector,
    idle: Duration,
}

impl Connector<()> for IdleConnector {
    type Out = IdleTransport;

    fn connect(
        &self,
        details: &ConnectionDetails,
        chained: Option<()>,
    ) -> Result<Option<Self::Out>, ureq::Error> {
        Ok(self
            .inner
            .connect(details, chained)?
            .map(|inner| IdleTransport {
                inner,
                idle: self.idle.into(),
            }))
    }
}

#[derive(Debug)]
struct IdleTransport {
    inner: Box<dyn ureq::unversioned::transport::Transport>,
    idle: ureq::unversioned::transport::time::Duration,
}

impl IdleTransport {
    fn bound(&self, timeout: NextTimeout) -> NextTimeout {
        NextTimeout {
            after: timeout.after.min(self.idle),
            reason: timeout.reason,
        }
    }
}

impl ureq::unversioned::transport::Transport for IdleTransport {
    fn buffers(&mut self) -> &mut dyn Buffers {
        self.inner.buffers()
    }

    fn transmit_output(&mut self, amount: usize, timeout: NextTimeout) -> Result<(), ureq::Error> {
        let timeout = self.bound(timeout);
        self.inner.transmit_output(amount, timeout)
    }

    fn await_input(&mut self, timeout: NextTimeout) -> Result<bool, ureq::Error> {
        let timeout = self.bound(timeout);
        self.inner.await_input(timeout)
    }

    fn is_open(&mut self) -> bool {
        self.inner.is_open()
    }

    fn is_tls(&self) -> bool {
        self.inner.is_tls()
    }
}

impl HttpTransport {
    pub(crate) fn get_with_headers(
        &self,
        url: &Url,
        range: Option<u64>,
        if_range: Option<&str>,
        limit: u64,
        headers: &[(&str, ureq::http::HeaderValue)],
    ) -> Result<HttpResponse, graphforge_api::GfError> {
        #[cfg(feature = "hub-test-support")]
        if let Some(response) =
            crate::hub_test_support::launcher::read(url, range, if_range, limit, headers)
        {
            return response;
        }

        let mut request = self.agent.get(url.as_str());
        if let Some(offset) = range {
            request = request.header("Range", format!("bytes={offset}-"));
        }
        if let Some(validator) = if_range {
            request = request.header("If-Range", validator);
        }
        for (name, value) in headers {
            request = request.header(*name, value.clone());
        }
        let response = request.call().map_err(|_| network("request failed"))?;
        let status = response.status().as_u16();
        let location = response
            .headers()
            .get("location")
            .and_then(|v| v.to_str().ok())
            .map(str::to_owned);
        let content_range = response
            .headers()
            .get("content-range")
            .and_then(|v| v.to_str().ok())
            .map(str::to_owned);
        let etag = response
            .headers()
            .get("etag")
            .and_then(|v| v.to_str().ok())
            .map(str::to_owned);
        let content_length = response
            .headers()
            .get("content-length")
            .and_then(|v| v.to_str().ok())
            .and_then(|v| v.parse().ok());
        let retry_after = response
            .headers()
            .get("retry-after")
            .and_then(|v| v.to_str().ok())
            .and_then(|v| {
                let now = std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .map_or(0, |elapsed| elapsed.as_secs());
                retry_after_seconds(v, now)
            });
        let (_, body) = response.into_parts();
        Ok(HttpResponse {
            status,
            location,
            content_range,
            etag,
            content_length,
            retry_after,
            body: Box::new(body.into_reader().take(limit.saturating_add(1))),
        })
    }
}

/// Resumable reader for one immutable object URL. A resumed response is
/// accepted only when both HTTP range metadata and the entity validator agree.
pub(crate) struct RangedObjectReader<'a> {
    transport: &'a dyn Transport,
    url: Url,
    body: Box<dyn Read + Send>,
    etag: Option<String>,
    total: Option<u64>,
    consumed: u64,
    response_remaining: u64,
    resumes: u8,
    done: bool,
    changed: bool,
}

impl<'a> RangedObjectReader<'a> {
    pub(crate) fn changed(&self) -> bool {
        self.changed
    }

    pub(crate) fn open(
        transport: &'a dyn Transport,
        url: Url,
    ) -> Result<Self, graphforge_api::GfError> {
        validate_object_url(&url)?;
        let response = transport.get(&url, None, None, u64::MAX)?;
        if response.status != 200 {
            return Err(network("object request did not return 200"));
        }
        let Some(content_length) = response.content_length else {
            return Err(network(
                "object response has no Content-Length; cannot verify resumably",
            ));
        };
        let response_remaining = content_length;
        Ok(Self {
            transport,
            url,
            body: Box::new(response.body.take(content_length)),
            etag: response.etag,
            total: Some(content_length),
            consumed: 0,
            response_remaining,
            resumes: 0,
            done: false,
            changed: false,
        })
    }

    fn resume(&mut self) -> io::Result<()> {
        if self.resumes == 8 {
            return Err(io::Error::other("maximum ranged resumes exceeded"));
        }
        let Some(etag) = self.etag.as_deref().filter(|etag| !etag.starts_with("W/")) else {
            return Err(io::Error::other(
                "object has no strong validator; cannot safely resume",
            ));
        };
        let response =
            match self
                .transport
                .get(&self.url, Some(self.consumed), Some(etag), u64::MAX)
            {
                Ok(response) => response,
                Err(error) => return Err(io::Error::other(error)),
            };
        let conflict =
            || io::Error::other("ConcurrentMutation: remote object changed during verification");
        if response.status != 206 || response.etag.as_deref() != Some(etag) {
            self.changed = true;
            return Err(conflict());
        }
        let expected = format!("bytes {}-", self.consumed);
        let Some(range) = response.content_range.as_deref() else {
            self.changed = true;
            return Err(conflict());
        };
        let parsed = range.strip_prefix(&expected).and_then(|suffix| {
            suffix.split_once('/').and_then(|(end, total)| {
                Some((end.parse::<u64>().ok()?, total.parse::<u64>().ok()?))
            })
        });
        let Some((end, total)) = parsed else {
            self.changed = true;
            return Err(conflict());
        };
        let length = end.saturating_sub(self.consumed).saturating_add(1);
        if end < self.consumed
            || end >= total
            || self.total.is_some_and(|known| known != total)
            || response.content_length.is_some_and(|known| known != length)
        {
            self.changed = true;
            return Err(conflict());
        }
        self.total = Some(total);
        self.resumes += 1;
        self.response_remaining = length;
        self.body = Box::new(response.body.take(length));
        Ok(())
    }
}

/// Presigned object URLs carry their authorization in the query string;
/// validate the same HTTPS, host, credential, and public-address rules while
/// allowing that capability query.
fn validate_object_url(url: &Url) -> Result<(), graphforge_api::GfError> {
    let mut checked = url.clone();
    checked.set_query(None);
    validate_url(&checked)
}

impl Read for RangedObjectReader<'_> {
    fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
        if buffer.is_empty() || self.done {
            return Ok(0);
        }
        loop {
            match self.body.read(buffer) {
                Ok(0) if self.total.is_some_and(|total| self.consumed == total) => {
                    self.done = true;
                    return Ok(0);
                }
                Ok(0) if self.response_remaining == 0 => self.resume()?,
                Err(error) if error.kind() == io::ErrorKind::Interrupted => {}
                Ok(0) | Err(_) => self.resume()?,
                Ok(count) => {
                    self.consumed += count as u64;
                    self.response_remaining = self.response_remaining.saturating_sub(count as u64);
                    return Ok(count);
                }
            }
        }
    }
}

impl Transport for HttpTransport {
    fn get_authorized(
        &self,
        url: &Url,
        range: Option<u64>,
        if_range: Option<&str>,
        limit: u64,
        headers: &[(&str, ureq::http::HeaderValue)],
    ) -> Result<HttpResponse, graphforge_api::GfError> {
        self.get_with_headers(url, range, if_range, limit, headers)
    }

    fn get(
        &self,
        url: &Url,
        range: Option<u64>,
        if_range: Option<&str>,
        limit: u64,
    ) -> Result<HttpResponse, graphforge_api::GfError> {
        self.get_with_headers(url, range, if_range, limit, &[])
    }

    fn get_discovery(
        &self,
        url: &Url,
        headers: &[(&str, ureq::http::HeaderValue)],
        limit: u64,
    ) -> Result<HttpResponse, graphforge_api::GfError> {
        self.get_with_headers(url, None, None, limit, headers)
    }

    fn exchange(
        &self,
        request: &HubRequest,
        limit: usize,
    ) -> Result<HubResponse, graphforge_api::GfError> {
        #[cfg(feature = "hub-test-support")]
        if let Some(response) = crate::hub_test_support::launcher::exchange(request, limit) {
            return response;
        }

        send_with_agent(&self.agent, request, limit)
    }
}

/// Bounds for Hub writes (`POST`, `PUT`).
///
/// A whole-request deadline would fail every upload chunk on a slow uplink no
/// matter how steadily it progresses, and resume could never help. Writes
/// therefore bound each phase instead: the body of one chunk may take
/// `send_body`, and every other phase (request head, response head, response
/// body) `response`.
pub(crate) struct WriteTimeouts {
    /// Sending one request body (one upload chunk or one commit document).
    pub(crate) send_body: Duration,
    /// Each other request and response phase.
    pub(crate) response: Duration,
}

/// Production write bounds. With 1 MiB upload chunks, five minutes per chunk
/// body admits any uplink of at least about 3.5 KB/s.
pub(crate) const WRITE_TIMEOUTS: WriteTimeouts = WriteTimeouts {
    send_body: Duration::from_mins(5),
    response: Duration::from_mins(1),
};

/// Agent configuration for Hub writes: per-phase bounds, no global deadline.
pub(crate) fn write_agent_config(
    https_only: bool,
    timeouts: &WriteTimeouts,
) -> ureq::config::Config {
    ureq::Agent::config_builder()
        .https_only(https_only)
        .http_status_as_error(false)
        .max_redirects(0)
        .proxy(None)
        .timeout_global(None)
        .timeout_connect(Some(Duration::from_secs(10)))
        .timeout_send_request(Some(timeouts.response))
        .timeout_send_body(Some(timeouts.send_body))
        .timeout_recv_response(Some(timeouts.response))
        .timeout_recv_body(Some(timeouts.response))
        .build()
}

/// Transport for `gf publish`: reads use clone's [`read_agent`], while writes
/// use [`write_agent_config`].
pub(crate) struct HubTransport {
    read: HttpTransport,
    write: ureq::Agent,
}

impl HubTransport {
    pub(crate) fn new() -> Self {
        Self::with_agents(
            HttpTransport::new(),
            ureq::Agent::with_parts(
                write_agent_config(true, &WRITE_TIMEOUTS),
                DefaultConnector::new(),
                PublicResolver(DefaultResolver::default()),
            ),
        )
    }

    pub(crate) fn with_agents(read: HttpTransport, write: ureq::Agent) -> Self {
        Self { read, write }
    }
}

impl Transport for HubTransport {
    fn get(
        &self,
        url: &Url,
        range: Option<u64>,
        if_range: Option<&str>,
        limit: u64,
    ) -> Result<HttpResponse, graphforge_api::GfError> {
        self.read.get(url, range, if_range, limit)
    }

    fn get_discovery(
        &self,
        url: &Url,
        headers: &[(&str, ureq::http::HeaderValue)],
        limit: u64,
    ) -> Result<HttpResponse, graphforge_api::GfError> {
        self.read.get_discovery(url, headers, limit)
    }

    fn exchange(
        &self,
        request: &HubRequest,
        limit: usize,
    ) -> Result<HubResponse, graphforge_api::GfError> {
        #[cfg(feature = "hub-test-support")]
        if let Some(response) = crate::hub_test_support::launcher::exchange(request, limit) {
            return response;
        }

        match request.method {
            HubMethod::Post | HubMethod::Put => send_with_agent(&self.write, request, limit),
            HubMethod::Get | HubMethod::Head => self.read.exchange(request, limit),
        }
    }
}

/// Preserve sensitivity when converting the provider-neutral wire request.
fn request_header(
    name: &str,
    value: &str,
) -> Result<ureq::http::HeaderValue, graphforge_api::GfError> {
    let mut value = ureq::http::HeaderValue::from_str(value)
        .map_err(|_| validation("hub.invalid_input", "request header is invalid"))?;
    if name.eq_ignore_ascii_case("authorization")
        || name.eq_ignore_ascii_case("x-vercel-protection-bypass")
    {
        value.set_sensitive(true);
    }
    Ok(value)
}

/// Preserve the existing per-MiB minimum upload throughput without overflowing.
pub(crate) fn chunk_send_timeout(
    base: Duration,
    bytes: u64,
) -> Result<Duration, graphforge_api::GfError> {
    let units = bytes.div_ceil(1024 * 1024).max(1);
    let units = u32::try_from(units).map_err(|_| network("chunk timeout overflow"))?;
    base.checked_mul(units)
        .ok_or_else(|| network("chunk timeout overflow"))
}

/// Send one request through `agent`; redirects are returned, never followed.
pub(crate) fn send_with_agent(
    agent: &ureq::Agent,
    request: &HubRequest,
    limit: usize,
) -> Result<HubResponse, graphforge_api::GfError> {
    let method = match request.method {
        HubMethod::Get => "GET",
        HubMethod::Head => "HEAD",
        HubMethod::Post => "POST",
        HubMethod::Put => "PUT",
    };
    let mut builder = ureq::http::Request::builder()
        .method(method)
        .uri(request.url.as_str());
    for (name, value) in &request.headers {
        builder = builder.header(name.as_str(), request_header(name, value)?);
    }
    let result = if matches!(request.method, HubMethod::Get | HubMethod::Head) {
        let built = builder
            .body(())
            .map_err(|_| validation("hub.invalid_input", "request is invalid"))?;
        agent.run(built)
    } else {
        let built = builder
            .body(request.body.as_slice())
            .map_err(|_| validation("hub.invalid_input", "request is invalid"))?;
        let built = if request.method == HubMethod::Put {
            let timeout = agent
                .config()
                .timeouts()
                .send_body
                .map(|base| chunk_send_timeout(base, request.body.len() as u64))
                .transpose()?;
            agent
                .configure_request(built)
                .timeout_send_body(timeout)
                .build()
        } else {
            built
        };
        agent.run(built)
    };
    let response = result.map_err(|_| network("request failed"))?;
    let status = response.status().as_u16();
    let headers = response
        .headers()
        .iter()
        .filter_map(|(name, value)| {
            value
                .to_str()
                .ok()
                .map(|value| (name.as_str().to_ascii_lowercase(), value.to_owned()))
        })
        .collect();
    let (_, body) = response.into_parts();
    let mut bytes = Vec::new();
    body.into_reader()
        .take(limit as u64 + 1)
        .read_to_end(&mut bytes)
        .map_err(|_| network("response read failed"))?;
    if bytes.len() > limit {
        return Err(limit_error("response exceeds byte bound"));
    }
    Ok(HubResponse {
        status,
        headers,
        body: bytes,
    })
}

/// Validate a data-plane upload URL a Hub issued.
///
/// Upload URLs are capabilities, so unlike [`validate_url`] a query string is
/// allowed; scheme, credentials, fragment, and host rules are the same.
pub(crate) fn validate_upload_url(url: &Url) -> Result<(), graphforge_api::GfError> {
    if url.scheme() != "https"
        || url.username() != ""
        || url.password().is_some()
        || url.host_str().is_none()
        || url.fragment().is_some()
    {
        return Err(validation(
            "hub.unsafe_location",
            "upload URL must be credential-free HTTPS",
        ));
    }
    if let Some(host) = url.host_str()
        && host.parse::<IpAddr>().is_ok_and(|ip| !public_ip(ip))
    {
        return Err(validation("hub.unsafe_location", "URL host is not public"));
    }
    Ok(())
}

pub(crate) fn validate_url(url: &Url) -> Result<(), graphforge_api::GfError> {
    if url.scheme() != "https"
        || url.username() != ""
        || url.password().is_some()
        || url.host_str().is_none()
        || url.query().is_some()
        || url.fragment().is_some()
    {
        return Err(validation(
            "hub.unsafe_location",
            "URL must be credential-free HTTPS",
        ));
    }
    if let Some(host) = url.host_str()
        && host.parse::<IpAddr>().is_ok_and(|ip| !public_ip(ip))
    {
        return Err(validation("hub.unsafe_location", "URL host is not public"));
    }
    Ok(())
}

/// Bounded in-process retry for transient read failures.
///
/// A retry follows a failed connection, a failed or truncated response body,
/// or a status of the retry class ([`StatusClass::transient`]). Only
/// consecutive failures without progress count toward `attempts`; a body read
/// that advances the durable download offset resets the count, so a long
/// transfer survives any number of separated interruptions while a dead one
/// fails promptly.
#[derive(Clone, Copy, Debug)]
pub(crate) struct RetryPolicy {
    /// Requests allowed for one step without progress.
    pub(crate) attempts: u32,
    /// Wait before the first retry; each later wait doubles.
    pub(crate) initial_backoff: Duration,
    /// Upper bound on one wait, including one a Hub asks for with `Retry-After`.
    pub(crate) max_backoff: Duration,
}

/// Production retry policy: five attempts, waiting 1, 2, 4, then 8 seconds.
pub(crate) const RETRY_POLICY: RetryPolicy = RetryPolicy {
    attempts: 5,
    initial_backoff: Duration::from_secs(1),
    max_backoff: Duration::from_secs(30),
};

impl RetryPolicy {
    /// The wait before retry number `failures` (one-based).
    pub(crate) fn backoff(&self, failures: u32) -> Duration {
        let doublings = failures.saturating_sub(1).min(16);
        self.initial_backoff
            .saturating_mul(1_u32 << doublings)
            .min(self.max_backoff)
    }

    /// The wait before retry number `failures` after a failure whose response
    /// asked for `retry_after` seconds: the longer of that and the backoff.
    /// `None` when the Hub asks for a longer pause than one wait may last, so
    /// the caller reports the failure instead of retrying early.
    pub(crate) fn wait(&self, failures: u32, retry_after: Option<u64>) -> Option<Duration> {
        let backoff = self.backoff(failures);
        match retry_after.map(Duration::from_secs) {
            Some(asked) if asked > self.max_backoff => None,
            Some(asked) => Some(asked.max(backoff)),
            None => Some(backoff),
        }
    }
}

/// `Retry-After` as the number of seconds to wait from `now` (seconds since
/// the Unix epoch): delta-seconds, or one of the three HTTP-date forms of
/// RFC 9110. A delta too large for `u64` saturates, so it exceeds any cap. A
/// date that is not in the future, or a value that is neither form, asks for
/// no particular wait and the ordinary backoff applies.
pub(crate) fn retry_after_seconds(value: &str, now: u64) -> Option<u64> {
    let value = value.trim();
    if !value.is_empty() && value.bytes().all(|byte| byte.is_ascii_digit()) {
        return Some(value.parse().unwrap_or(u64::MAX));
    }
    http_date_unix(value, now)?
        .checked_sub(now)
        .filter(|wait| *wait > 0)
}

/// Seconds since the Unix epoch of an IMF-fixdate (`Sun, 06 Nov 1994 08:49:37
/// GMT`), an obsolete RFC 850 date (`Sunday, 06-Nov-94 08:49:37 GMT`), or an
/// asctime date (`Sun Nov  6 08:49:37 1994`), read at `now` (seconds since the
/// epoch). The weekday must be a real weekday name but is not checked against
/// the date. Anything that is not a valid calendar instant from 1970 through
/// 9999 is `None`.
fn http_date_unix(value: &str, now: u64) -> Option<u64> {
    const MONTHS: [&str; 12] = [
        "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
    ];
    const WEEKDAYS: [(&str, &str); 7] = [
        ("mon", "monday"),
        ("tue", "tuesday"),
        ("wed", "wednesday"),
        ("thu", "thursday"),
        ("fri", "friday"),
        ("sat", "saturday"),
        ("sun", "sunday"),
    ];
    let tokens: Vec<&str> = value
        .split(|c: char| !c.is_ascii_alphanumeric())
        .filter(|token| !token.is_empty())
        .collect();
    let weekday = tokens.first()?.to_ascii_lowercase();
    if !WEEKDAYS
        .iter()
        .any(|(short, long)| weekday == *short || weekday == *long)
    {
        return None;
    }
    let number = |token: &str| {
        token
            .bytes()
            .all(|byte| byte.is_ascii_digit())
            .then(|| token.parse::<u64>().ok())
            .flatten()
    };
    let month_number = |token: &str| {
        let lower = token.to_ascii_lowercase();
        MONTHS
            .iter()
            .position(|name| *name == lower)
            .map(|m| m as u64 + 1)
    };
    // `Err(yy)` is an RFC 850 two-digit year, resolved against `now` below.
    let (day, month, year, clock) = match tokens[..] {
        // IMF-fixdate and RFC 850 share a shape: day, month, year, clock, zone.
        [_, day, month, year, h, m, s, zone] if zone.eq_ignore_ascii_case("GMT") => {
            let year = match year.len() {
                4 => Ok(number(year)?),
                2 => Err(number(year)?),
                _ => return None,
            };
            (number(day)?, month_number(month)?, year, [h, m, s])
        }
        [_, month, day, h, m, s, year] if year.len() == 4 => (
            number(day)?,
            month_number(month)?,
            Ok(number(year)?),
            [h, m, s],
        ),
        _ => return None,
    };
    let [h, m, s] = clock.map(number);
    let (h, m, s) = (h?, m?, s?);
    if h > 23 || m > 59 || s > 60 {
        return None;
    }
    let instant = |year: u64| {
        if !(1970..=9999).contains(&year) || !(1..=days_in_month(year, month)).contains(&day) {
            return None;
        }
        days_from_civil(year, month, day)?
            .checked_mul(86_400)?
            .checked_add(h * 3600 + m * 60 + s)
    };
    match year {
        Ok(year) => instant(year),
        Err(yy) => {
            // RFC 9110 §5.6.7: an instant more than 50 years after `now` (its
            // civil date plus 50 years, same month, day and time) is read in
            // the previous century.
            let (current, now_month, now_day) = civil_date(now / 86_400)?;
            let limit = days_from_civil(current.checked_add(50)?, now_month, now_day)?
                .checked_mul(86_400)?
                .checked_add(now % 86_400)?;
            let candidate = current / 100 * 100 + yy;
            let this_century = instant(candidate)?;
            if this_century > limit {
                instant(candidate.checked_sub(100)?)
            } else {
                Some(this_century)
            }
        }
    }
}

fn days_in_month(year: u64, month: u64) -> u64 {
    match month {
        2 if year.is_multiple_of(4) && (!year.is_multiple_of(100) || year.is_multiple_of(400)) => {
            29
        }
        2 => 28,
        4 | 6 | 9 | 11 => 30,
        _ => 31,
    }
}

/// Days since 1970-01-01 of a proleptic Gregorian date (after Howard Hinnant).
fn days_from_civil(year: u64, month: u64, day: u64) -> Option<u64> {
    let y = if month <= 2 {
        year.checked_sub(1)?
    } else {
        year
    };
    let era = y / 400;
    let yoe = y - era * 400;
    let mp = (month + 9) % 12;
    let doy = (153 * mp + 2) / 5 + day - 1;
    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
    era.checked_mul(146_097)?
        .checked_add(doe)?
        .checked_sub(719_468)
}

/// The Gregorian (year, month, day) of `days` since 1970-01-01 (after Howard
/// Hinnant).
fn civil_date(days: u64) -> Option<(u64, u64, u64)> {
    let z = days.checked_add(719_468)?;
    let era = z / 146_097;
    let doe = z - era * 146_097;
    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let day = doy - (153 * mp + 2) / 5 + 1;
    let month = if mp < 10 { mp + 3 } else { mp - 9 };
    let year = era.checked_mul(400)?.checked_add(yoe)?;
    Some((if month <= 2 { year + 1 } else { year }, month, day))
}

/// What an unsuccessful Hub status means to the caller. The class decides both
/// the in-process retry and the error: retry-class statuses are storage errors
/// (`GF_IO`, exit 3), the rest validation errors (`GF_VALIDATION`, exit 2).
/// Messages carry only the status number, never the Hub's response body.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum StatusClass {
    /// `404`, `410`: no such repository or object. Fix the input.
    NotFound,
    /// `401`, `403`: the Hub refuses this read. Ask a human for access.
    AccessDenied,
    /// `429`: too many requests. Retry later, after `Retry-After`.
    RateLimited,
    /// `408`, `502`, `503`, `504`: the Hub is temporarily unavailable. Retry.
    Unavailable,
    /// Any other status: a protocol or Hub failure. Ask a human.
    Unexpected,
}

impl StatusClass {
    pub(crate) const fn of(status: u16) -> Self {
        match status {
            404 | 410 => Self::NotFound,
            401 | 403 => Self::AccessDenied,
            429 => Self::RateLimited,
            408 | 502..=504 => Self::Unavailable,
            _ => Self::Unexpected,
        }
    }

    /// The stable semantic code.
    pub(crate) const fn code(self) -> &'static str {
        match self {
            Self::NotFound => "hub.not_found",
            Self::AccessDenied => "hub.access_denied",
            Self::RateLimited => "hub.rate_limited",
            Self::Unavailable => "hub.unavailable",
            Self::Unexpected => "hub.unexpected_status",
        }
    }

    /// Whether a retry may cure the failure.
    pub(crate) const fn transient(self) -> bool {
        matches!(self, Self::RateLimited | Self::Unavailable)
    }

    fn error(self, status: u16, retry_after: Option<u64>) -> graphforge_api::GfError {
        let mut message = format!("{}: Hub returned HTTP status {status}", self.code());
        if let Some(seconds) = retry_after {
            let _ = write!(message, "; retry after {seconds} s");
        }
        if self.transient() {
            graphforge_api::GfError::Storage(message)
        } else {
            graphforge_api::GfError::Validation(message)
        }
    }
}

/// One request failure; `transient` marks a failure a retry may cure,
/// `status` is the HTTP status of an unsuccessful response, and `retry_after`
/// its `Retry-After` seconds.
pub(crate) struct FetchFailure {
    pub(crate) error: graphforge_api::GfError,
    pub(crate) transient: bool,
    pub(crate) status: Option<u16>,
    pub(crate) retry_after: Option<u64>,
}

impl From<graphforge_api::GfError> for FetchFailure {
    fn from(error: graphforge_api::GfError) -> Self {
        Self {
            error,
            transient: false,
            status: None,
            retry_after: None,
        }
    }
}

#[cfg(test)]
pub(crate) fn fetch(
    transport: &dyn Transport,
    start: &Url,
    range: Option<u64>,
    if_range: Option<&str>,
    limit: u64,
) -> Result<HttpResponse, graphforge_api::GfError> {
    let mut attempts = 0;
    fetch_once(transport, start, range, if_range, limit, &mut attempts).map_err(|f| f.error)
}

/// Fetch `start`, retrying transient failures under `policy`.
pub(crate) fn fetch_with_attempts(
    transport: &dyn Transport,
    start: &Url,
    range: Option<u64>,
    if_range: Option<&str>,
    limit: u64,
    attempts: &mut u32,
    policy: &RetryPolicy,
) -> Result<HttpResponse, graphforge_api::GfError> {
    retry_read(policy, || {
        fetch_once(transport, start, range, if_range, limit, attempts)
    })
}

fn retry_read(
    policy: &RetryPolicy,
    mut fetch: impl FnMut() -> Result<HttpResponse, FetchFailure>,
) -> Result<HttpResponse, graphforge_api::GfError> {
    let mut failures = 0;
    loop {
        match fetch() {
            Ok(response) => return Ok(response),
            Err(failure) => {
                failures += 1;
                let wait = policy.wait(failures, failure.retry_after);
                match wait {
                    Some(wait) if failure.transient && failures < policy.attempts => {
                        std::thread::sleep(wait);
                    }
                    _ => return Err(failure.error),
                }
            }
        }
    }
}

/// Fetch `start` once, following at most [`MAX_REDIRECTS`] public redirects.
pub(crate) fn fetch_once(
    transport: &dyn Transport,
    start: &Url,
    range: Option<u64>,
    if_range: Option<&str>,
    limit: u64,
    attempts: &mut u32,
) -> Result<HttpResponse, FetchFailure> {
    fetch_once_inner(transport, start, range, if_range, limit, attempts, None)
}

fn fetch_once_inner(
    transport: &dyn Transport,
    start: &Url,
    range: Option<u64>,
    if_range: Option<&str>,
    limit: u64,
    attempts: &mut u32,
    credentials: Option<&DiscoveryCredentials>,
) -> Result<HttpResponse, FetchFailure> {
    let mut url = start.clone();
    for hop in 0..=MAX_REDIRECTS {
        transport.validate(&url)?;
        *attempts = attempts.saturating_add(1);
        // Only the initial discovery request may carry credentials. Even a
        // same-origin redirect uses the ordinary credential-free read path.
        let response = if hop == 0 {
            if let Some(credentials) = credentials {
                transport.get_discovery(&url, credentials.headers_for(&url)?, limit)
            } else {
                transport.get(&url, range, if_range, limit)
            }
        } else {
            transport.get(&url, range, if_range, limit)
        }
        .map_err(|error| FetchFailure {
            transient: is_network(&error),
            error,
            status: None,
            retry_after: None,
        })?;
        if matches!(response.status, 301 | 302 | 303 | 307 | 308) {
            if hop == MAX_REDIRECTS {
                return Err(network("redirect limit exceeded").into());
            }
            let location = response
                .location
                .as_deref()
                .ok_or_else(|| network("redirect is missing Location"))?;
            url = url
                .join(location)
                .map_err(|_| validation("hub.unsafe_location", "invalid redirect URL"))?;
            continue;
        }
        if !(200..300).contains(&response.status) {
            let class = StatusClass::of(response.status);
            return Err(FetchFailure {
                error: class.error(response.status, response.retry_after),
                transient: class.transient(),
                status: Some(response.status),
                retry_after: response.retry_after,
            });
        }
        return Ok(response);
    }
    unreachable!()
}

/// Whether `error` is a `hub.network` failure.
pub(crate) fn is_network(error: &graphforge_api::GfError) -> bool {
    matches!(error, graphforge_api::GfError::Storage(detail) if detail.starts_with("hub.network:"))
}

pub(crate) fn read_bounded(
    mut response: HttpResponse,
    limit: usize,
) -> Result<Vec<u8>, graphforge_api::GfError> {
    let mut bytes = Vec::new();
    response
        .body
        .read_to_end(&mut bytes)
        .map_err(|_| network("response read failed"))?;
    if bytes.len() > limit {
        return Err(limit_error("response exceeds byte bound"));
    }
    Ok(bytes)
}

pub(crate) fn parse_input(
    value: &str,
) -> Result<(RepositoryIdentity, Url), graphforge_api::GfError> {
    parse_input_at(value, None)
}

/// Resolve a repository argument against `hub`, which only applies to the
/// `owner/repository` form; an explicit repository URL names its own Hub.
pub(crate) fn parse_input_at(
    value: &str,
    hub: Option<&str>,
) -> Result<(RepositoryIdentity, Url), graphforge_api::GfError> {
    if !value.contains("://") {
        let identity = RepositoryIdentity::parse(value)
            .map_err(|_| validation("hub.invalid_identity", "invalid repository identity"))?;
        let hub = hub_base(hub)?;
        let mut base = hub.clone();
        base.set_path(&format!(
            "{}/{}/{}",
            hub.path().trim_end_matches('/'),
            identity.owner,
            identity.repository
        ));
        return Ok((identity, base));
    }
    if hub.is_some() {
        return Err(validation(
            "hub.invalid_identity",
            "--hub applies only to an owner/repository name",
        ));
    }
    let base = Url::parse(value)
        .map_err(|_| validation("hub.invalid_identity", "invalid repository URL"))?;
    validate_url(&base)?;
    if base.query().is_some() || base.path().ends_with('/') {
        return Err(validation(
            "hub.invalid_identity",
            "repository URL must end in owner/repository",
        ));
    }
    let segments: Vec<_> = base.path_segments().into_iter().flatten().collect();
    if segments.len() != 2 {
        return Err(validation(
            "hub.invalid_identity",
            "repository URL must end in owner/repository",
        ));
    }
    let identity = RepositoryIdentity::parse(&format!("{}/{}", segments[0], segments[1]))
        .map_err(|_| validation("hub.invalid_identity", "invalid repository identity"))?;
    Ok((identity, base))
}

/// Validate the configured Hub origin and optional deployment path prefix.
pub(crate) fn hub_base(hub: Option<&str>) -> Result<Url, graphforge_api::GfError> {
    let hub = Url::parse(hub.unwrap_or(DEFAULT_HUB))
        .map_err(|_| validation("hub.invalid_identity", "invalid Hub URL"))?;
    validate_url(&hub)?;
    Ok(hub)
}

pub(crate) fn endpoint(base: &Url, name: &str) -> Url {
    let mut endpoint = base.clone();
    endpoint.set_path(&format!("{}/.gf/{name}", base.path().trim_end_matches('/')));
    endpoint
}

pub(crate) fn validation(code: &str, message: &str) -> graphforge_api::GfError {
    graphforge_api::GfError::Validation(format!("{code}: {message}"))
}

pub(crate) fn network(message: &str) -> graphforge_api::GfError {
    graphforge_api::GfError::Storage(format!("hub.network: {message}"))
}
pub(crate) fn limit_error(message: &str) -> graphforge_api::GfError {
    validation("hub.limit_exceeded", message)
}
pub(crate) fn storage(error: impl std::fmt::Display) -> graphforge_api::GfError {
    graphforge_api::GfError::Storage(error.to_string())
}
/// An incremental SHA-256 rendered as `sha256:<hex>`, the form every Hub
/// object digest and portable transport digest uses.
pub(crate) struct RunningDigest(Sha256);

impl RunningDigest {
    pub(crate) fn new() -> Self {
        Self(Sha256::new())
    }

    pub(crate) fn update(&mut self, bytes: &[u8]) {
        self.0.update(bytes);
    }

    /// Hash everything `reader` still yields.
    pub(crate) fn absorb(&mut self, reader: &mut impl Read) -> Result<(), graphforge_api::GfError> {
        let mut buffer = vec![0_u8; 64 * 1024].into_boxed_slice();
        loop {
            let read = reader.read(&mut buffer).map_err(storage)?;
            if read == 0 {
                return Ok(());
            }
            self.0.update(&buffer[..read]);
        }
    }

    pub(crate) fn finish(self) -> String {
        let hex = self
            .0
            .finalize()
            .iter()
            .fold(String::with_capacity(64), |mut hex, byte| {
                write!(hex, "{byte:02x}").expect("writing to a string cannot fail");
                hex
            });
        format!("sha256:{hex}")
    }
}

pub(crate) fn hash_reader(reader: &mut impl Read) -> Result<String, graphforge_api::GfError> {
    let mut digest = RunningDigest::new();
    digest.absorb(reader)?;
    Ok(digest.finish())
}