simpleplatform-sdk 0.4.0

Simple Platform Rust SDK
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
1355
1356
1357
1358
1359
1360
//! Putting a file into the platform's store, and reading one back out.
//!
//! Two ways in — bytes this action already holds, and a file behind a URL — and
//! one thing out of both: a [`DocumentHandle`], which is the value a `:document`
//! field holds. The way out is [`read`], which takes that handle and answers with
//! the file's bytes.
//!
//! ```
//! # use simpleplatform_sdk::prelude::*;
//! # use simpleplatform_sdk::testing;
//! use simpleplatform_sdk::storage::Target;
//!
//! # let _session = testing::install(|_name, _params| {
//! #     Ok(json!({
//! #         "file_hash": "c3ab8ff13720e8ad9047dd39466b3c89",
//! #         "filename": "report.pdf",
//! #         "mime_type": "application/pdf",
//! #         "size": 6,
//! #         "storage_path": "documents/c3/ab/c3ab8ff13720e8ad9047dd39466b3c89",
//! #     }))
//! # });
//! let target = Target::new("dev.simple.system", "documents", "attachment");
//! let handle = simple::storage::upload_buffer(b"foobar", "report.pdf", "application/pdf", target)?;
//!
//! assert_eq!(handle.filename, "report.pdf");
//! assert_eq!(handle.size, 6);
//! # Ok::<(), Error>(())
//! ```
//!
//! # The handle is the point
//!
//! An upload stores the file and answers with a handle to it. Attaching that
//! handle to a record is a separate step, and the one that changes tenant data:
//! write the handle into the `:document` field with [`crate::graphql::mutate`]
//! once you have it. So the two halves stay separable — the file is in the store
//! whether or not the record was written, and the store is the only thing
//! [`upload_buffer`] and [`upload_external`] touch.
//!
//! # The same bytes are the same file
//!
//! The store is addressed by the SHA-256 of the contents, which is the
//! `file_hash` on the handle. Identical bytes land under the identical hash and
//! are kept once, so uploading a file the store already holds costs a hash and
//! answers with the handle that was already there.
//!
//! # Reading a file back
//!
//! ```
//! # use simpleplatform_sdk::prelude::*;
//! # use simpleplatform_sdk::storage::DocumentHandle;
//! # use simpleplatform_sdk::testing;
//! # let file = b"%PDF-1.7 ...".to_vec();
//! # let served = file.clone();
//! # let _session = testing::install(|_name, _params| Ok(json!({ "size": 12 })))
//! #     .with_bytes(move |_name, params| {
//! #         let offset = params["offset"].as_u64().unwrap() as usize;
//! #         let length = params["length"].as_u64().unwrap() as usize;
//! #         Ok(served[offset..offset + length].to_vec())
//! #     });
//! # let handle = DocumentHandle {
//! #     file_hash: "9f86d081884c".into(),
//! #     filename: "statement.pdf".into(),
//! #     mime_type: "application/pdf".into(),
//! #     size: 12,
//! #     storage_path: "_staged/9f86d081884c".into(),
//! # };
//! let bytes = simple::storage::read(&handle)?;
//!
//! assert_eq!(bytes, file);
//! # Ok::<(), Error>(())
//! ```
//!
//! The bytes cross from the host as they are, with no JSON and no base64. The
//! size is asked for first, the buffer is allocated once at exactly that size,
//! and the file arrives in ranges of at most [`MAX_RANGE_BYTES`], each written by
//! the host straight into its place in that buffer. [`read_range`] reads part of
//! a file the same way, from the size first, and [`size`] answers how large it
//! is without reading any of it.
//!
//! Reading is for server actions. A browser action is refused.
//!
//! # Why the bytes are encoded here
//!
//! The call travels as JSON, and JSON carries text. So a buffer is base64 on the
//! wire — encoded once, at this boundary, in the same standard alphabet with the
//! same padding every SDK uses, and decoded by the platform before the file is
//! stored. An action passes `&[u8]` and never sees the encoding.

use std::fmt;

use serde::{Deserialize, Serialize};
use serde_json::{json, Value};

use crate::codes::Code;
use crate::error::{Error, Fault};
use crate::host;

/// The host action that stores a file and answers with its handle.
const UPLOAD_EXTERNAL: &str = "action:storage/upload-external";

/// The host action that answers a stored file's size.
const STAT: &str = "action:storage/stat";

/// The host action that answers one range of a stored file as its bytes.
const READ: &str = "action:storage/read";

/// The longest range the host answers one read with.
///
/// [`read`] and [`read_range`] cover anything longer in ranges of this size,
/// into one buffer, so it bounds what the host holds for one call rather than
/// what an action can read.
pub const MAX_RANGE_BYTES: u64 = 16 * 1024 * 1024;

/// Where a size stops being one every SDK counts exactly.
///
/// The TypeScript and Go SDKs read the size as a floating-point number, which
/// holds every whole number below 2^53 exactly and rounds past it. A size at or
/// past this is refused here too, so the same answer from the store reads the
/// same in all three.
const MAX_EXACT_SIZE: u64 = 1 << 53;

/// A stored file, as a `:document` field holds it.
///
/// This is a pointer to the contents rather than the contents: it is what an
/// upload answers with, what a record stores, and what identifies the file
/// afterwards.
#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq, Eq)]
pub struct DocumentHandle {
    /// The SHA-256 of the contents, which is the file's identity in the store.
    pub file_hash: String,
    /// The name the file is stored under.
    pub filename: String,
    /// The media type of the contents, such as `application/pdf`.
    pub mime_type: String,
    /// The size of the contents in bytes.
    pub size: u64,
    /// Where the store keeps the file.
    pub storage_path: String,
}

/// The record field a stored file is destined for.
#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq, Eq)]
pub struct Target {
    /// The app that owns the table.
    pub app_id: String,
    /// The table the record lives in.
    pub table_name: String,
    /// The `:document` field the handle is stored in.
    pub field_name: String,
}

impl Target {
    /// A target named by its app, its table and its field.
    ///
    /// ```
    /// use simpleplatform_sdk::storage::Target;
    ///
    /// let target = Target::new("dev.simple.system", "documents", "attachment");
    ///
    /// assert_eq!(target.field_name, "attachment");
    /// ```
    pub fn new(
        app_id: impl Into<String>,
        table_name: impl Into<String>,
        field_name: impl Into<String>,
    ) -> Target {
        Target {
            app_id: app_id.into(),
            table_name: table_name.into(),
            field_name: field_name.into(),
        }
    }
}

/// The credential a URL is read with.
///
/// It is `#[non_exhaustive]`: a `match` on it needs a `_` arm, so a scheme added
/// later does not break an action that was already written.
#[non_exhaustive]
#[derive(Clone, Serialize)]
#[serde(tag = "type", rename_all = "lowercase")]
pub enum Auth {
    /// A username and a password.
    Basic {
        /// The username.
        username: String,
        /// The password.
        password: String,
    },
    /// A bearer token.
    Bearer {
        /// The token.
        bearer_token: String,
    },
}

impl Auth {
    /// Read the URL with a bearer token.
    ///
    /// ```
    /// use simpleplatform_sdk::storage::Auth;
    ///
    /// let auth = Auth::bearer("t-1234");
    ///
    /// assert!(matches!(auth, Auth::Bearer { .. }));
    /// ```
    pub fn bearer(bearer_token: impl Into<String>) -> Auth {
        Auth::Bearer {
            bearer_token: bearer_token.into(),
        }
    }

    /// Read the URL with a username and a password.
    pub fn basic(username: impl Into<String>, password: impl Into<String>) -> Auth {
        Auth::Basic {
            username: username.into(),
            password: password.into(),
        }
    }
}

impl fmt::Debug for Auth {
    /// The scheme, and never the secret.
    ///
    /// A credential is written by hand and read by a host, and the one place it
    /// has no business appearing is a log line. So this renders the scheme, and
    /// the username that names the account, and stops there.
    ///
    /// ```
    /// use simpleplatform_sdk::storage::Auth;
    ///
    /// assert_eq!(format!("{:?}", Auth::bearer("t-1234")), "Bearer { .. }");
    /// ```
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Auth::Basic { username, .. } => formatter
                .debug_struct("Basic")
                .field("username", username)
                .finish_non_exhaustive(),
            Auth::Bearer { .. } => formatter.debug_struct("Bearer").finish_non_exhaustive(),
        }
    }
}

/// The file an external upload reads.
#[derive(Clone, Debug, Serialize)]
pub struct Source {
    /// The URL the file is read from.
    pub url: String,
    /// The credential the URL is read with, for a URL that needs one.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub auth: Option<Auth>,
}

impl Source {
    /// A file at this URL, read without a credential.
    pub fn url(url: impl Into<String>) -> Source {
        Source {
            url: url.into(),
            auth: None,
        }
    }

    /// The same file, read with this credential.
    ///
    /// ```
    /// use simpleplatform_sdk::storage::{Auth, Source};
    ///
    /// let source = Source::url("https://example.com/report.pdf").with_auth(Auth::bearer("t-1234"));
    ///
    /// assert!(source.auth.is_some());
    /// ```
    pub fn with_auth(mut self, auth: Auth) -> Source {
        self.auth = Some(auth);
        self
    }
}

/// Store bytes this action already holds.
///
/// The buffer, the name and the media type are all required, and each is checked
/// before anything is sent: an empty buffer, a blank name, a blank media type or
/// an incomplete [`Target`] is refused where it costs nothing.
///
/// ```
/// # use simpleplatform_sdk::prelude::*;
/// # use simpleplatform_sdk::testing;
/// use simpleplatform_sdk::storage::Target;
///
/// # let _session = testing::install(|_name, params| {
/// #     assert_eq!(params["source"]["bytes"], json!("Zm9vYmFy"));
/// #     Ok(json!({
/// #         "file_hash": "c3ab8ff137",
/// #         "filename": "notes.txt",
/// #         "mime_type": "text/plain",
/// #         "size": 6,
/// #         "storage_path": "documents/c3/ab/c3ab8ff137",
/// #     }))
/// # });
/// let handle = simple::storage::upload_buffer(
///     b"foobar",
///     "notes.txt",
///     "text/plain",
///     Target::new("dev.simple.system", "documents", "attachment"),
/// )?;
///
/// assert_eq!(handle.file_hash, "c3ab8ff137");
/// # Ok::<(), Error>(())
/// ```
pub fn upload_buffer(
    bytes: &[u8],
    filename: &str,
    mime_type: &str,
    target: Target,
) -> Result<DocumentHandle, Error> {
    if bytes.is_empty() {
        return Err(
            Error::invalid("An upload needs at least one byte, and this buffer is empty.")
                .hint("Pass the file's contents."),
        );
    }

    if filename.trim().is_empty() {
        return Err(Error::invalid("An upload needs a filename.")
            .hint("Pass the name the file is stored under, such as report.pdf."));
    }

    if mime_type.trim().is_empty() {
        return Err(Error::invalid("An upload needs a media type.")
            .hint("Pass the type of the contents, such as application/pdf."));
    }

    check_target(&target)?;

    let source = json!({
        "bytes": encode(bytes),
        "filename": filename,
        "mime_type": mime_type,
    });

    send(source, target)
}

/// Store a file the platform reads from a URL.
///
/// The URL and any credential on it are checked before anything is sent, as is
/// the [`Target`].
///
/// ```
/// # use simpleplatform_sdk::prelude::*;
/// # use simpleplatform_sdk::testing;
/// use simpleplatform_sdk::storage::{Auth, Source, Target};
///
/// # let _session = testing::install(|_name, params| {
/// #     assert_eq!(params["source"]["auth"]["type"], json!("bearer"));
/// #     Ok(json!({
/// #         "file_hash": "9f86d081884c",
/// #         "filename": "statement.pdf",
/// #         "mime_type": "application/pdf",
/// #         "size": 81_920,
/// #         "storage_path": "documents/9f/86/9f86d081884c",
/// #     }))
/// # });
/// let handle = simple::storage::upload_external(
///     Source::url("https://example.com/statement.pdf").with_auth(Auth::bearer("t-1234")),
///     Target::new("dev.simple.system", "documents", "attachment"),
/// )?;
///
/// assert_eq!(handle.size, 81_920);
/// # Ok::<(), Error>(())
/// ```
pub fn upload_external(source: Source, target: Target) -> Result<DocumentHandle, Error> {
    if source.url.trim().is_empty() {
        return Err(
            Error::invalid("An external upload needs a URL to read from.")
                .hint("Pass the address of the file, or use upload_buffer for bytes you hold."),
        );
    }

    if let Some(auth) = &source.auth {
        check_auth(auth)?;
    }

    check_target(&target)?;

    send(serde_json::to_value(&source)?, target)
}

/// One upload, one round trip, one handle.
fn send(source: Value, target: Target) -> Result<DocumentHandle, Error> {
    let params = json!({ "source": source, "target": serde_json::to_value(&target)? });

    let stored = host::transport()?
        .call(UPLOAD_EXTERNAL.to_string(), params)
        .map_err(|cause| {
            Error::Host(Fault::new(Code::unspecified(), cause.message())).hint(
                "Nothing was attached to the record. The store is addressed by content, \
                 so the same bytes uploaded again answer with the same handle.",
            )
        })?;

    serde_json::from_value(stored).map_err(|cause| {
        Error::Json(Fault::new(
            Code::unspecified(),
            format!("The upload finished and its handle could not be read: {cause}"),
        ))
        .hint(
            "Report this. The file is stored under the hash of its contents, \
             so uploading the same bytes again answers with the handle.",
        )
    })
}

/// How many bytes a stored file holds, from the store's own record of it.
///
/// ```
/// # use simpleplatform_sdk::prelude::*;
/// # use simpleplatform_sdk::storage::DocumentHandle;
/// # use simpleplatform_sdk::testing;
/// # let _session = testing::install(|name, _params| {
/// #     assert_eq!(name, "action:storage/stat");
/// #     Ok(json!({ "size": 81_920 }))
/// # });
/// # let handle = DocumentHandle {
/// #     file_hash: "9f86d081884c".into(),
/// #     filename: "statement.pdf".into(),
/// #     mime_type: "application/pdf".into(),
/// #     size: 81_920,
/// #     storage_path: "_staged/9f86d081884c".into(),
/// # };
/// assert_eq!(simple::storage::size(&handle)?, 81_920);
/// # Ok::<(), Error>(())
/// ```
pub fn size(handle: &DocumentHandle) -> Result<u64, Error> {
    check_handle(handle)?;

    let answer = host::transport()?.call(STAT.to_string(), json!({ "handle": handle }))?;

    answer
        .get("size")
        .and_then(Value::as_u64)
        .filter(|size| *size < MAX_EXACT_SIZE)
        .ok_or_else(|| {
            Error::Host(Fault::new(
                Code::unspecified(),
                format!("{STAT} answered without a size: {answer}"),
            ))
        })
}

/// The whole of a stored file.
///
/// The size is asked for first, the buffer is allocated once at exactly that
/// size, and every range is written by the host straight into its place in it.
/// A file this action has no memory for is refused before anything is read,
/// and a range answered short — a file that changed while it was read — is
/// refused rather than handed over incomplete.
pub fn read(handle: &DocumentHandle) -> Result<Vec<u8>, Error> {
    let total = size(handle)?;

    read_span(handle, 0, total)
}

/// Up to `length` bytes of a stored file, starting `offset` bytes in.
///
/// The size is asked for first, so the range is held at what the file has past
/// `offset`: one that runs past the end answers with exactly the bytes up to
/// the end, and one that starts at or past the end is refused before any range
/// is read. What is left is read as [`read`] reads a whole file — in ranges of
/// at most [`MAX_RANGE_BYTES`], into one buffer allocated once at that length,
/// each range answered in full or refused.
///
/// Asking for the size first is also what makes a host that cannot read
/// stored files refuse in its own words, before any range is asked of it.
pub fn read_range(handle: &DocumentHandle, offset: u64, length: u64) -> Result<Vec<u8>, Error> {
    check_handle(handle)?;

    if length == 0 {
        return Err(Error::invalid("A range needs at least one byte.")
            .hint("Pass a length of one or more, or ask size() how large the file is."));
    }

    let total = size(handle)?;

    if offset >= total {
        return Err(past_end(offset, total));
    }

    read_span(handle, offset, length.min(total - offset))
}

/// Exactly `length` bytes from `offset`, which the file's size says are there.
///
/// The buffer is allocated once at `length` before any range is asked for, and
/// every range must arrive whole.
fn read_span(handle: &DocumentHandle, offset: u64, length: u64) -> Result<Vec<u8>, Error> {
    let mut bytes = Vec::new();
    let capacity = usize::try_from(length).map_err(|_too_large| too_large(length))?;
    bytes
        .try_reserve_exact(capacity)
        .map_err(|_no_memory| too_large(length))?;

    let transport = host::transport()?;
    let mut done = 0;

    while done < length {
        let wanted = MAX_RANGE_BYTES.min(length - done);
        let appended = transport.call_bytes(
            READ.to_string(),
            range(handle, offset + done, wanted),
            &mut bytes,
        )?;

        if appended as u64 != wanted {
            return Err(short(offset + done, wanted, appended));
        }

        done += wanted;
    }

    Ok(bytes)
}

/// The parameters of one range read.
fn range(handle: &DocumentHandle, offset: u64, length: u64) -> Value {
    json!({ "handle": handle, "offset": offset, "length": length })
}

/// A read this action cannot hold.
fn too_large(length: u64) -> Error {
    Error::failed(format!(
        "Reading {length} bytes needs more memory than this action has."
    ))
    .hint("Raise the action's mem_limit, or read the file in parts with read_range.")
}

/// A range that starts where the file has nothing left to read.
fn past_end(offset: u64, total: u64) -> Error {
    Error::invalid(format!(
        "The range starts at byte {offset}, at or past the end of the file, which is {total} bytes."
    ))
    .hint("Ask size() how large the file is, and start the range before its end.")
}

/// A range the host answered with fewer bytes than the file's size promised.
fn short(offset: u64, length: u64, appended: usize) -> Error {
    Error::Host(Fault::new(
        Code::unspecified(),
        format!(
            "The file answered {appended} bytes for the {length} at offset {offset}, \
             so it is not the size it was when the read began."
        ),
    ))
    .hint("Read it again.")
}

/// Whether a handle names a stored file.
fn check_handle(handle: &DocumentHandle) -> Result<(), Error> {
    let named = [
        ("storage_path", &handle.storage_path),
        ("filename", &handle.filename),
        ("file_hash", &handle.file_hash),
    ];

    for (member, value) in named {
        if value.trim().is_empty() {
            return Err(Error::invalid(format!("A document handle needs {member}."))
                .hint("Pass the handle exactly as the :document field holds it."));
        }
    }

    Ok(())
}

/// Whether a target names a field to attach to.
fn check_target(target: &Target) -> Result<(), Error> {
    let named = [
        ("app_id", &target.app_id),
        ("table_name", &target.table_name),
        ("field_name", &target.field_name),
    ];

    for (member, value) in named {
        if value.trim().is_empty() {
            return Err(Error::invalid(format!("A storage target needs {member}."))
                .hint("Name the app, the table, and the :document field the handle goes in."));
        }
    }

    Ok(())
}

/// Whether a credential carries what its scheme needs.
///
/// The scheme itself is settled by [`Auth`] — there are two, and each holds its
/// own members — so what is left to check is that the members say something.
fn check_auth(auth: &Auth) -> Result<(), Error> {
    match auth {
        Auth::Basic { username, password } => {
            if username.trim().is_empty() {
                return Err(Error::invalid("Basic authentication needs a username.")
                    .hint("Pass the username, or read the URL without a credential."));
            }

            if password.trim().is_empty() {
                return Err(Error::invalid("Basic authentication needs a password.")
                    .hint("Pass the password, or read the URL without a credential."));
            }
        }
        Auth::Bearer { bearer_token } => {
            if bearer_token.trim().is_empty() {
                return Err(Error::invalid("Bearer authentication needs a token.")
                    .hint("Pass the token, or read the URL without a credential."));
            }
        }
    }

    Ok(())
}

/// The symbols base64 spends, in their standard order.
const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

/// What fills a group that ran out of bytes.
const PAD: char = '=';

/// The bytes as base64: three bytes to four symbols, padded to a multiple of
/// four, in the standard alphabet.
fn encode(bytes: &[u8]) -> String {
    let mut encoded = String::with_capacity(bytes.len().div_ceil(3) * 4);

    for group in bytes.chunks(3) {
        let mut packed = 0_u32;

        // Left to right: the first byte takes the top eight of twenty-four bits,
        // and a group of one or two leaves the rest zero.
        for (index, byte) in group.iter().enumerate() {
            packed |= u32::from(*byte) << (16 - 8 * index);
        }

        encoded.push(symbol(packed >> 18));
        encoded.push(symbol(packed >> 12));
        encoded.push(if group.len() > 1 {
            symbol(packed >> 6)
        } else {
            PAD
        });
        encoded.push(if group.len() > 2 { symbol(packed) } else { PAD });
    }

    encoded
}

/// The symbol for the low six bits of `packed`.
fn symbol(packed: u32) -> char {
    // Six bits count to sixty-three and the alphabet holds sixty-four symbols,
    // so there is always one to answer with.
    char::from(ALPHABET[(packed & 0b11_1111) as usize])
}

#[cfg(test)]
mod tests {
    use serde_json::json;

    use super::*;
    use crate::testing;

    /// What the host answers with for an upload that landed.
    fn stored() -> Value {
        json!({
            "file_hash": "c3ab8ff13720e8ad9047dd39466b3c89",
            "filename": "report.pdf",
            "mime_type": "application/pdf",
            "size": 6,
            "storage_path": "documents/c3/ab/c3ab8ff13720e8ad9047dd39466b3c89",
        })
    }

    fn target() -> Target {
        Target::new("dev.simple.system", "documents", "attachment")
    }

    fn handle() -> DocumentHandle {
        DocumentHandle {
            file_hash: "9f86d081884c7d65".to_string(),
            filename: "statement.pdf".to_string(),
            mime_type: "application/pdf".to_string(),
            size: 0,
            storage_path: "_staged/9f86d081884c7d65".to_string(),
        }
    }

    /// Every byte value, so bytes passed through any text decoding on the way
    /// could not compare equal.
    fn every_byte(count: usize) -> Vec<u8> {
        (0..count).map(|i| ((i * 7 + 3) % 256) as u8).collect()
    }

    /// A session serving `file` the way the host does: its size from the store,
    /// and each range as its bytes, up to the end of the file.
    fn serving(file: Vec<u8>) -> testing::Session {
        let size = file.len();

        testing::install(move |name, _params| {
            assert_eq!(name, "action:storage/stat");
            Ok(json!({ "size": size }))
        })
        .with_bytes(move |name, params| {
            assert_eq!(name, "action:storage/read");
            let offset = params["offset"].as_u64().unwrap() as usize;
            let length = params["length"].as_u64().unwrap() as usize;

            if offset >= file.len() {
                return Err(Error::invalid(
                    "'offset' is at or past the end of the file.",
                ));
            }

            Ok(file[offset..file.len().min(offset + length)].to_vec())
        })
    }

    #[test]
    fn a_read_answers_the_file_byte_for_byte() {
        let file = every_byte(5_000);
        let _session = serving(file.clone());

        assert_eq!(read(&handle()).unwrap(), file);
    }

    #[test]
    fn a_read_allocates_once_at_exactly_the_size_the_store_reports() {
        let file = every_byte(40 * 1024 * 1024 + 17);
        let _session = serving(file.clone());

        let bytes = read(&handle()).unwrap();

        assert_eq!(bytes.len(), file.len());
        assert_eq!(bytes.capacity(), file.len());
        assert!(bytes == file);
    }

    #[test]
    fn a_large_read_asks_for_ranges_no_longer_than_the_host_answers() {
        let file = every_byte(40 * 1024 * 1024 + 17);
        let session = serving(file);

        read(&handle()).unwrap();

        let ranges: Vec<(u64, u64)> = session
            .calls()
            .iter()
            .filter(|call| call.name == "action:storage/read")
            .map(|call| {
                (
                    call.params["offset"].as_u64().unwrap(),
                    call.params["length"].as_u64().unwrap(),
                )
            })
            .collect();

        let mib = 1024 * 1024;
        assert_eq!(
            ranges,
            vec![
                (0, 16 * mib),
                (16 * mib, 16 * mib),
                (32 * mib, 8 * mib + 17)
            ]
        );
    }

    #[test]
    fn every_read_carries_the_handle_it_was_given() {
        let session = serving(every_byte(10));

        read(&handle()).unwrap();

        for call in session.calls() {
            assert_eq!(
                call.params["handle"],
                serde_json::to_value(handle()).unwrap()
            );
        }
    }

    #[test]
    fn an_empty_file_is_read_without_asking_for_a_range() {
        let session = serving(Vec::new());

        assert_eq!(read(&handle()).unwrap(), Vec::<u8>::new());
        assert_eq!(session.calls().len(), 1);
    }

    #[test]
    fn a_range_answered_short_is_refused_rather_than_handed_over() {
        let _session = testing::install(|_name, _params| Ok(json!({ "size": 100 })))
            .with_bytes(|_name, _params| Ok(vec![0; 60]));

        let error = read(&handle()).unwrap_err();

        assert!(error.message().contains("60 bytes for the 100 at offset 0"));
    }

    #[test]
    fn a_host_refusal_reaches_the_caller_with_its_own_message() {
        let _session = testing::install(|_name, _params| Ok(json!({ "size": 10 }))).with_bytes(
            |_name, _params| Err(Error::invalid("No stored file matches this handle.")),
        );

        let error = read(&handle()).unwrap_err();

        assert!(error
            .message()
            .contains("action:storage/read failed: No stored file matches this handle."));
    }

    #[test]
    fn a_file_larger_than_this_action_can_hold_is_refused_before_any_range() {
        let largest = MAX_EXACT_SIZE - 1;
        let session = testing::install(move |_name, _params| Ok(json!({ "size": largest })));

        let error = read(&handle()).unwrap_err();

        assert_eq!(
            error.message(),
            format!("Reading {largest} bytes needs more memory than this action has.")
        );
        assert_eq!(session.calls().len(), 1);

        let error = read_range(&handle(), 0, largest).unwrap_err();

        assert!(error
            .message()
            .contains("needs more memory than this action has"));
        assert_eq!(
            session.calls().len(),
            2,
            "one size lookup each, and no range"
        );
    }

    #[test]
    fn size_answers_what_the_store_reports() {
        let _session = testing::install(|_name, _params| Ok(json!({ "size": 81_920 })));

        assert_eq!(size(&handle()).unwrap(), 81_920);
    }

    #[test]
    fn a_size_that_is_not_a_count_every_sdk_holds_exactly_is_refused() {
        for answer in [
            json!({}),
            json!({ "size": -1 }),
            json!({ "size": 1.5 }),
            json!({ "size": "10" }),
            json!({ "size": MAX_EXACT_SIZE }),
            json!("10"),
        ] {
            let reply = answer.clone();
            let _session = testing::install(move |_name, _params| Ok(reply.clone()));

            let error = size(&handle()).unwrap_err();

            assert_eq!(
                error.message(),
                format!("action:storage/stat answered without a size: {answer}")
            );
        }
    }

    #[test]
    fn a_size_refusal_keeps_the_hosts_own_message() {
        let _session = testing::install(|_name, _params| {
            Err(Error::invalid("No stored file matches this handle."))
        });

        let error = size(&handle()).unwrap_err();

        assert_eq!(
            error.message(),
            "action:storage/stat failed: No stored file matches this handle."
        );
    }

    #[test]
    fn a_range_answers_exactly_that_range_after_asking_for_the_size() {
        let file = every_byte(10_000);
        let session = serving(file.clone());

        assert_eq!(
            read_range(&handle(), 4_000, 1_500).unwrap(),
            file[4_000..5_500]
        );

        let names: Vec<String> = session.calls().into_iter().map(|call| call.name).collect();

        assert_eq!(names, ["action:storage/stat", "action:storage/read"]);
    }

    #[test]
    fn a_range_running_past_the_end_answers_up_to_the_end() {
        let file = every_byte(10_000);
        let _session = serving(file.clone());

        assert_eq!(read_range(&handle(), 9_990, 100).unwrap(), file[9_990..]);
    }

    #[test]
    fn a_range_starting_at_or_past_the_end_is_refused_before_any_range() {
        for offset in [10, 11, 20] {
            let session = serving(every_byte(10));

            let error = read_range(&handle(), offset, 1).unwrap_err();

            assert_eq!(error.code().as_str(), "INVALID_TOOL_INPUT");
            assert_eq!(
                error.message(),
                format!(
                    "The range starts at byte {offset}, at or past the end of the file, which is 10 bytes."
                )
            );
            assert_eq!(
                error.fault().hint(),
                "Ask size() how large the file is, and start the range before its end."
            );
            assert!(ranges(&session).is_empty());
        }
    }

    /// The offset and length of every range the host was asked for, in order.
    fn ranges(session: &testing::Session) -> Vec<(u64, u64)> {
        session
            .calls()
            .iter()
            .filter(|call| call.name == "action:storage/read")
            .map(|call| {
                (
                    call.params["offset"].as_u64().unwrap(),
                    call.params["length"].as_u64().unwrap(),
                )
            })
            .collect()
    }

    /// A file's size, the offset and the length a range asks for, and the
    /// offset and length of every range the host is asked for in turn.
    type Case = (u64, u64, u64, Vec<(u64, u64)>);

    // The same cases pin the Go and TypeScript SDKs. A range is held at what
    // the file has past its offset, so the file ending exactly where a range
    // of 16 MiB does never leads to asking for a range at the end.
    #[test]
    fn a_range_is_held_at_what_the_file_has_at_every_boundary() {
        let mib: u64 = 1024 * 1024;
        let largest = every_byte(32 * 1024 * 1024 + 5);

        let cases: Vec<Case> = vec![
            (16 * mib, 0, 16 * mib, vec![(0, 16 * mib)]),
            (16 * mib, 0, 16 * mib + 1, vec![(0, 16 * mib)]),
            (
                16 * mib + 1,
                0,
                16 * mib + 1,
                vec![(0, 16 * mib), (16 * mib, 1)],
            ),
            (
                32 * mib + 5,
                0,
                32 * mib + 5,
                vec![(0, 16 * mib), (16 * mib, 16 * mib), (32 * mib, 5)],
            ),
            (
                32 * mib + 5,
                0,
                48 * mib,
                vec![(0, 16 * mib), (16 * mib, 16 * mib), (32 * mib, 5)],
            ),
            (
                32 * mib + 5,
                16 * mib,
                16 * mib + 1,
                vec![(16 * mib, 16 * mib), (32 * mib, 1)],
            ),
            (32 * mib, 16 * mib, 16 * mib + 1, vec![(16 * mib, 16 * mib)]),
            (10, 9, 5, vec![(9, 1)]),
        ];

        for (size, offset, length, asked) in cases {
            let file = largest[..size as usize].to_vec();
            let session = serving(file.clone());

            let bytes = read_range(&handle(), offset, length).unwrap();
            let end = size.min(offset + length) as usize;

            assert_eq!(
                bytes.len(),
                end - offset as usize,
                "{size} {offset} {length}"
            );
            assert_eq!(bytes.capacity(), bytes.len(), "{size} {offset} {length}");
            assert!(
                bytes == file[offset as usize..end],
                "{size} {offset} {length}"
            );
            assert_eq!(ranges(&session), asked, "{size} {offset} {length}");
            assert_eq!(session.calls()[0].name, "action:storage/stat");
        }

        for (size, offset, length) in [
            (0, 0, 1),
            (10, 10, 1),
            (10, 11, 1),
            (10, 20, 32 * mib),
            (16 * mib, 16 * mib, 16 * mib + 1),
        ] {
            let session = serving(largest[..size as usize].to_vec());

            let error = read_range(&handle(), offset, length).unwrap_err();

            assert!(
                error.message().contains(&format!(
                    "at or past the end of the file, which is {size} bytes"
                )),
                "{size} {offset} {length}: {}",
                error.message()
            );
            assert!(ranges(&session).is_empty(), "{size} {offset} {length}");
        }

        for size in [0, 16 * mib, 16 * mib + 1, 32 * mib + 5] {
            let file = largest[..size as usize].to_vec();
            let _session = serving(file.clone());

            assert!(read(&handle()).unwrap() == file, "{size}");
        }
    }

    // A host from before stored files could be read answers a byte read in
    // its JSON envelope, as though the envelope were the file. The size is
    // asked for first, which such a host refuses as a request it does not
    // know, so the envelope is never asked for and never handed over.
    #[test]
    fn a_host_that_cannot_read_stored_files_refuses_before_any_range() {
        let session = testing::install(|name, _params| {
            Err(Error::invalid(format!("Unknown request: {name}")))
        })
        .with_bytes(|_name, _params| {
            Ok(
                br#"{"ok":false,"error":{"message":"Unknown request: action:storage/read"}}"#
                    .to_vec(),
            )
        });

        for error in [
            read_range(&handle(), 0, 64).unwrap_err(),
            read_range(&handle(), 0, 32 * 1024 * 1024).unwrap_err(),
            read(&handle()).unwrap_err(),
        ] {
            assert_eq!(
                error.message(),
                "action:storage/stat failed: Unknown request: action:storage/stat"
            );
        }

        assert!(ranges(&session).is_empty());
    }

    #[test]
    fn an_empty_range_is_refused_before_anything_is_sent() {
        let session = serving(every_byte(10));

        assert!(read_range(&handle(), 0, 0).is_err());
        assert!(session.calls().is_empty());
    }

    #[test]
    fn a_handle_missing_what_names_the_file_is_refused_before_anything_is_sent() {
        let session = serving(every_byte(10));

        for broken in [
            DocumentHandle {
                storage_path: String::new(),
                ..handle()
            },
            DocumentHandle {
                filename: " ".to_string(),
                ..handle()
            },
            DocumentHandle {
                file_hash: String::new(),
                ..handle()
            },
        ] {
            assert_eq!(
                read(&broken).unwrap_err().code().as_str(),
                "INVALID_TOOL_INPUT"
            );
        }

        assert!(session.calls().is_empty());
    }

    #[test]
    fn a_session_with_no_bytes_reply_says_how_to_give_it_one() {
        let _session = testing::install(|_name, _params| Ok(json!({ "size": 10 })));

        let error = read(&handle()).unwrap_err();

        assert!(error.message().contains("was given no way to"));
    }

    #[test]
    fn a_buffer_travels_base64_encoded_beside_its_name_and_type() {
        let session = testing::install(|_name, _params| Ok(stored()));

        upload_buffer(b"foobar", "report.pdf", "application/pdf", target()).unwrap();

        let calls = session.calls();

        assert_eq!(calls.len(), 1);
        assert_eq!(calls[0].name, "action:storage/upload-external");
        assert_eq!(
            calls[0].params["source"],
            json!({
                "bytes": "Zm9vYmFy",
                "filename": "report.pdf",
                "mime_type": "application/pdf",
            })
        );
        assert_eq!(
            calls[0].params["target"],
            json!({
                "app_id": "dev.simple.system",
                "table_name": "documents",
                "field_name": "attachment",
            })
        );
    }

    #[test]
    fn a_stored_file_answers_with_every_member_of_its_handle() {
        let _session = testing::install(|_name, _params| Ok(stored()));

        let handle = upload_buffer(b"foobar", "report.pdf", "application/pdf", target()).unwrap();

        assert_eq!(
            handle,
            DocumentHandle {
                file_hash: "c3ab8ff13720e8ad9047dd39466b3c89".to_string(),
                filename: "report.pdf".to_string(),
                mime_type: "application/pdf".to_string(),
                size: 6,
                storage_path: "documents/c3/ab/c3ab8ff13720e8ad9047dd39466b3c89".to_string(),
            }
        );
    }

    #[test]
    fn an_empty_buffer_is_refused_before_anything_is_sent() {
        let session = testing::install(|_name, _params| Ok(stored()));

        let error = upload_buffer(&[], "report.pdf", "application/pdf", target()).unwrap_err();

        assert_eq!(error.code().as_str(), "INVALID_TOOL_INPUT");
        assert!(session.calls().is_empty());
    }

    #[test]
    fn a_blank_name_or_type_is_refused_before_anything_is_sent() {
        let session = testing::install(|_name, _params| Ok(stored()));

        for (filename, mime_type) in [("   ", "application/pdf"), ("report.pdf", "")] {
            let error = upload_buffer(b"foobar", filename, mime_type, target()).unwrap_err();

            assert_eq!(error.code().as_str(), "INVALID_TOOL_INPUT");
        }

        assert!(session.calls().is_empty());
    }

    #[test]
    fn a_target_missing_a_member_names_the_one_it_is_missing() {
        let session = testing::install(|_name, _params| Ok(stored()));

        let incomplete = [
            (Target::new("", "documents", "attachment"), "app_id"),
            (
                Target::new("dev.simple.system", " ", "attachment"),
                "table_name",
            ),
            (
                Target::new("dev.simple.system", "documents", ""),
                "field_name",
            ),
        ];

        for (target, member) in incomplete {
            let error = upload_buffer(b"foobar", "report.pdf", "application/pdf", target)
                .expect_err("an incomplete target names nothing to attach to");

            assert_eq!(error.code().as_str(), "INVALID_TOOL_INPUT");
            assert!(error.message().contains(member), "{}", error.message());
        }

        assert!(session.calls().is_empty());
    }

    #[test]
    fn a_url_upload_carries_the_url_alone_when_it_needs_no_credential() {
        let session = testing::install(|_name, _params| Ok(stored()));

        upload_external(Source::url("https://example.com/report.pdf"), target()).unwrap();

        assert_eq!(
            session.calls()[0].params["source"],
            json!({ "url": "https://example.com/report.pdf" }),
            "a source with no credential carries no auth member"
        );
    }

    #[test]
    fn a_credential_travels_under_its_own_scheme() {
        let session = testing::install(|_name, _params| Ok(stored()));

        upload_external(
            Source::url("https://example.com/report.pdf").with_auth(Auth::bearer("t-1234")),
            target(),
        )
        .unwrap();

        upload_external(
            Source::url("https://example.com/report.pdf").with_auth(Auth::basic("ada", "s3cret")),
            target(),
        )
        .unwrap();

        let calls = session.calls();

        assert_eq!(
            calls[0].params["source"]["auth"],
            json!({ "type": "bearer", "bearer_token": "t-1234" })
        );
        assert_eq!(
            calls[1].params["source"]["auth"],
            json!({ "type": "basic", "username": "ada", "password": "s3cret" })
        );
    }

    #[test]
    fn a_blank_url_is_refused_before_anything_is_sent() {
        let session = testing::install(|_name, _params| Ok(stored()));

        let error = upload_external(Source::url("  "), target()).unwrap_err();

        assert_eq!(error.code().as_str(), "INVALID_TOOL_INPUT");
        assert!(session.calls().is_empty());
    }

    #[test]
    fn a_credential_with_nothing_in_it_is_refused_before_anything_is_sent() {
        let session = testing::install(|_name, _params| Ok(stored()));

        let blank = [
            Auth::bearer("  "),
            Auth::basic("", "s3cret"),
            Auth::basic("ada", " "),
        ];

        for auth in blank {
            let error = upload_external(
                Source::url("https://example.com/report.pdf").with_auth(auth),
                target(),
            )
            .expect_err("a credential that says nothing cannot read the URL");

            assert_eq!(error.code().as_str(), "INVALID_TOOL_INPUT");
        }

        assert!(session.calls().is_empty());
    }

    #[test]
    fn a_refused_upload_keeps_the_hosts_own_message() {
        let _session = testing::install(|_name, _params| Err(Error::failed("the store is full")));

        let error =
            upload_buffer(b"foobar", "report.pdf", "application/pdf", target()).unwrap_err();

        assert!(matches!(error, Error::Host(_)));
        assert!(error.message().contains("the store is full"));
        assert!(!error.is_retryable());
    }

    #[test]
    fn a_handle_that_cannot_be_read_is_reported_rather_than_returned() {
        let _session = testing::install(|_name, _params| Ok(json!({ "filename": "report.pdf" })));

        let error =
            upload_buffer(b"foobar", "report.pdf", "application/pdf", target()).unwrap_err();

        assert!(matches!(error, Error::Json(_)));
        assert!(error.message().contains("could not be read"));
    }

    #[test]
    fn an_upload_with_no_host_to_send_it_to_says_so() {
        let error =
            upload_buffer(b"foobar", "report.pdf", "application/pdf", target()).unwrap_err();

        assert!(error.message().contains("No host is installed"));
    }

    // The standard test vectors, which pin the alphabet and the padding.
    #[test]
    fn bytes_encode_to_the_standard_alphabet_with_standard_padding() {
        assert_eq!(encode(b""), "");
        assert_eq!(encode(b"f"), "Zg==");
        assert_eq!(encode(b"fo"), "Zm8=");
        assert_eq!(encode(b"foo"), "Zm9v");
        assert_eq!(encode(b"foob"), "Zm9vYg==");
        assert_eq!(encode(b"fooba"), "Zm9vYmE=");
        assert_eq!(encode(b"foobar"), "Zm9vYmFy");
    }

    #[test]
    fn the_last_two_symbols_of_the_alphabet_are_plus_and_slash() {
        assert_eq!(encode(&[0xfb, 0xff]), "+/8=");
        assert_eq!(encode(&[0xff, 0xff, 0xff]), "////");
        assert_eq!(encode(&[0x00, 0x00, 0x00]), "AAAA");
    }

    #[test]
    fn every_byte_value_survives_the_encoding() {
        let every: Vec<u8> = (0..=255).collect();
        let encoded = encode(&every);

        assert_eq!(encoded.len(), 344, "256 bytes fill 86 groups of four");
        assert!(encoded.ends_with("/w=="));
        assert!(encoded
            .chars()
            .all(|symbol| symbol == PAD || ALPHABET.contains(&(symbol as u8))));
    }

    #[test]
    fn a_credential_is_not_written_out_by_a_debug_rendering() {
        let source =
            Source::url("https://example.com/report.pdf").with_auth(Auth::bearer("t-1234"));

        let rendered = format!("{source:?}");

        assert!(!rendered.contains("t-1234"));
        assert!(rendered.contains("Bearer"));

        let basic = format!("{:?}", Auth::basic("ada", "s3cret"));

        assert!(!basic.contains("s3cret"));
        assert!(basic.contains("ada"));
    }
}