ingraph 0.1.0

A declaration-driven indexing framework: records and nodes are written as Rust types, and the storage rows, the dataflow between them and the GraphQL query surface are emitted from the declaration.
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
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
//! The local-filesystem blob backend: the connection-manager [`LocalFsStore`] holds THE one root
//! and hands out the stateless [`LocalFsBlob`] handle per artifact-family slot.
//!
//! # The address is the KEY
//!
//! A blob stores at `<root>/<slot>/<seg1>/…/<segN>[.<ext>]`: the slot is the artifact family, and
//! the key's fields are path components in the order the key walks them — lineage order, parent ids
//! first — so an entity's directory holds every descendant artifact and a hard-delete by lineage is
//! a directory removal. The extension comes from the record, for browsability. The address is
//! derivable from the key ALONE, so a lookup locates a file without a round-trip. Deliberately NOT
//! content-addressed: identical bytes under two keys store twice, which is what keeps a key's
//! location stable when its bytes are rewritten.
//!
//! # Rendering is TOTAL — no id value is ever refused
//!
//! Every value of every [`Id`](crate::Id) member renders. There is no charset admission test, no
//! refusal and no error path for a segment's CONTENT: text ids in particular carry NO restriction of
//! any kind, and the escape below is precisely what makes that true rather than a rule they must
//! obey. What the split decides is which FILENAME FORM gets written, never whether a value is
//! allowed.
//!
//! ```text
//! verbatim ⇔ the segment matches [a-z0-9._-]+, does not begin with '=',
//!            is neither `.` nor `..`, and is not a reserved device name
//! escaped  ⇔ '=' followed by lowercase RFC 4648 base32 (no padding) of the UTF-8 bytes
//! ```
//!
//! Injective, which is the property the whole scheme rests on:
//!
//! - A verbatim segment never begins with `=` and an escaped one always does, so the two ranges
//!   cannot meet.
//! - Both ranges are SINGLE-CASE. The product's own filesystem is case-insensitive, so a two-case
//!   verbatim range would let `Alice` and `alice` become one path; here the second is verbatim and
//!   the first escapes, and two escaped values differ in a lowercase alphabet where a
//!   case-insensitive comparison is exact.
//! - base32 is injective on bytes and the alphabet is disjoint from nothing it needs to be — the
//!   `=` prefix is the only marker, and RFC 4648's padding character (also `=`) is dropped, so no
//!   encoded body can be confused for a second prefix.
//!
//! Every non-text member lands verbatim by construction: decimal integers (`-` is in range), the
//! canonical lowercase hyphenated uuid, lowercase hex for the fixed-width byte members, and the
//! network family below. The browsable tree survives for all of them and for every lowercase text
//! id.
//!
//! # The network family's segments
//!
//! ```text
//! Ipv4Addr        1.2.3.4
//! Ipv6Addr        20010db8000000000000000000000001
//! IpAddr          either of the two above, untagged
//! SocketAddrV4    1.2.3.4_8080
//! SocketAddrV6    20010db8000000000000000000000001_8080_0_0
//! SocketAddr      either of the two above, untagged
//! ```
//!
//! A v6 address renders as FIXED 32 lowercase hex characters rather than in its textual form: the
//! colon is path-hostile on Windows and inside a URL, and RFC 5952's `::` compression means one
//! address has several textual spellings — so the compressed form never appears on disk, and the
//! rendering is the sixteen octets and nothing else. `IpAddr` and `SocketAddr` need no tag byte to
//! stay injective, because their two arms cannot be confused: a dotted quad contains `.` and a v6
//! rendering is 32 characters of hex with none.
//!
//! `SocketAddrV6` renders its `flowinfo` and `scope_id` ALWAYS, including when both are zero, and
//! that is forced rather than uniform-for-tidiness: both participate in std's `Eq` and `Hash`
//! (measured), so two `SocketAddrV6` values Rust calls unequal would otherwise share one file.
//!
//! # The reserved-device carve, and why it is a carve rather than a refusal
//!
//! Windows resolves `CON`, `NUL`, `AUX`, `PRN`, `COM1`…`COM9` and `LPT1`…`LPT9` as DEVICES, case-
//! insensitively, in any directory. Their lowercase spellings are inside `[a-z0-9_-]+`, so without
//! this carve a text id of `con` would render verbatim and name a device rather than a file. They
//! are therefore moved into the ESCAPED set by rule. `.` and `..` need no carve — the verbatim
//! charset has no `.`, so they cannot form — and the empty string needs none either, since `+`
//! requires one character. The carve exists so that no id is ever REFUSED: the alternative reading,
//! rejecting a reserved name, would make a legal text value undeclarable on one host.
//!
//! # LENGTH is the one axis a total rendering leaves, and it lives at the WALK
//!
//! A VALUE is never refused; an ADDRESS still can be. Two ceilings — [`MAX_SEGMENT_LEN`] on one path
//! component and [`MAX_PATH_LEN`] on the whole address — are checked in `resolve_path`, which is the
//! only place that sees the root, the slot and every rendered segment at once, and a breach is
//! [`LocalFsBlobError::SegmentTooLong`] or [`LocalFsBlobError::PathTooLong`]. Both REFUSE and
//! neither truncates: a truncated component is a silent collision, and two keys sharing one file is
//! the single thing this whole address scheme exists to prevent.
//!
//! Length is where the failure belongs because it is a property of the ADDRESS a walk assembles —
//! the root the caller chose, the slot, the depth of the lineage — rather than of any value that
//! went into it. No id is unrenderable; some trees are too deep to hold one.
//!
//! Both ceilings are ONE number on every host rather than the running one's, for the reason the
//! strategy seam below states: a tree is written on one machine and read on another.
//!
//! # The publish is an atomic keyed replace
//!
//! `put` stages the bytes in a tmp file beside the final path and renames it OVER that path. The
//! rename-over IS the keyed replace — last-write-wins — and it is atomic VISIBILITY: a reader sees
//! the whole old file or the whole new one, never a torn one. That is a property of a correct file
//! write rather than a durability feature, so this backend carries no fsync ceremony: an acked
//! `put` is visible, not power-durable. A blob is a DERIVED artifact, so its corruption detector is
//! the consumer and its recovery is regenerate. A publish that fails part-way reaps the tmp it
//! staged, since nothing else ever comes back to collect one.
//!
//! # No async runtime, no dependency beyond std
//!
//! The fs work is synchronous, so `put`/`get`/`locate` do their IO inline and return a ready
//! future; a caller wanting the work off the async thread wraps the call.

use core::{
  future::{Future, ready},
  sync::atomic::{AtomicU64, Ordering},
};
use std::{
  borrow::Cow,
  fs::{self, File, OpenOptions},
  io::{self, Write},
  path::{Path, PathBuf},
};

use smol_bytes::Utf8Bytes;

use super::{
  AsyncBlobEngine, AsyncBlobStore, AsyncLocate, BlobEngine, BlobLocation, BlobStore, Connected,
  Locate,
};
use crate::{BlobRecord, Id, Identifiable, Transformer, TypedId};

/// A process-global monotonic counter feeding each `put`'s tmp-file suffix. Uniqueness only needs
/// to hold among concurrent in-flight puts to the SAME key, which resolve to the same final path:
/// the key already names the file and the pid scopes it to this process, so this counter is the
/// last disambiguator — no wall clock and no entropy, neither of which correctness needs.
static PUT_NONCE: AtomicU64 = AtomicU64::new(0);

/// The lowercase RFC 4648 base32 alphabet. Single-case, which is what makes an escaped segment
/// unambiguous on a case-insensitive filesystem.
const BASE32: &[u8; 32] = b"abcdefghijklmnopqrstuvwxyz234567";

/// The Windows device names, lowercased. Matched case-insensitively BY the verbatim range being
/// lowercase-only: a segment reaching this check is already all-lowercase, so an exact compare here
/// is the case-insensitive one.
const RESERVED: [&str; 22] = [
  "con", "prn", "aux", "nul", "com1", "com2", "com3", "com4", "com5", "com6", "com7", "com8",
  "com9", "lpt1", "lpt2", "lpt3", "lpt4", "lpt5", "lpt6", "lpt7", "lpt8", "lpt9",
];

/// The most bytes ONE path component of a blob address may occupy —
/// [`LocalFsBlobError::SegmentTooLong`] refuses past it.
///
/// 255 is `NAME_MAX` on every filesystem this backend writes to: ext4, XFS, btrfs, APFS and HFS+ all
/// take 255 BYTES per name, and NTFS takes 255 UTF-16 code units. Those two units coincide here
/// rather than approximately agreeing — every component this backend mints is ASCII, the slot by its
/// identifier rule and a segment by the verbatim charset `[a-z0-9._-]` or the base32 escape — so one
/// byte is one code unit and 255 is the same ceiling under both spellings.
///
/// It measures every component this backend mints: the slot, each rendered segment, and the LEAF
/// WITH the record's extension on it — the extension is part of the name a filesystem actually
/// holds, so a 255-byte leaf plus `.png` is a 259-byte name and does not fit.
///
/// NOT a per-host number, and that is the portability law rather than a simplification — see
/// [`MAX_PATH_LEN`], which carries the argument for both.
pub const MAX_SEGMENT_LEN: usize = 255;

/// The most bytes a WHOLE resolved blob address may occupy, the store's root included —
/// [`LocalFsBlobError::PathTooLong`] refuses past it.
///
/// # The per-OS variance, and why the smallest of it is the number
///
/// | host | ceiling | note |
/// |---|---|---|
/// | Linux | 4096 (`PATH_MAX`) | the roomiest, and the terminating NUL is counted inside it |
/// | macOS, the BSDs | 1024 (`PATH_MAX`) | the smallest MODERN one, and the number this constant is |
/// | Windows | 260 (`MAX_PATH`), or ~32767 | the legacy limit and the extended one. Rust's own
///   `std::fs` rewrites a long ABSOLUTE path into the `\\?\` verbatim form, so 260 binds other tools
///   browsing the tree rather than this backend's IO |
///
/// A store is written once and must open EVERYWHERE afterwards, so the ceiling is a property of the
/// address FORMAT and not of the machine that happens to be holding the disk: taking the running
/// host's limit would let a Linux write produce an address a Mac cannot open, silently, since
/// `locate` is a pure render with nothing to compare against. That is the same law the rendering
/// strategy answers to, applied to the one axis a total rendering leaves.
///
/// Windows' legacy 260 is deliberately NOT the number. It is not a limit this backend's own IO hits,
/// and taking it would refuse addresses every host in the table can open — a ceiling that low costs
/// a real lineage depth for a limit only some readers have.
///
/// 1023 rather than 1024, because POSIX counts the terminating NUL inside `PATH_MAX`: 1023 bytes is
/// the longest address the smallest host in the table can actually open.
pub const MAX_PATH_LEN: usize = 1023;

/// Which rendering STRATEGY a store's tree was written under.
///
/// The seam exists because the rendering is entirely this backend's — [`Id`](crate::Id) is sealed,
/// so no outside type can arrive needing a rendering this backend did not choose — and a later
/// strategy could legitimately widen the verbatim range for a filesystem that can carry it.
///
/// # The portability law, which is what this seam is the shape of
///
/// A blob store written once must WORK ON EVERY OPERATING SYSTEM afterwards. So a rendering never
/// branches on the running host: ONE canonical, single-case, injective form everywhere, with the
/// Windows device names carved out of it on a machine that may never be Windows. Evolution is a NEW
/// VERSIONED STRATEGY — never OS detection, and never a fallible render, which is why
/// [`render`](Self::render) is total under EVERY strategy rather than by v1's own good luck.
///
/// The one axis this law leaves open is aggregate LENGTH, and it does not live here: it lives at the
/// walk, where the root and the whole address are visible — see [`MAX_PATH_LEN`].
///
/// # A strategy belongs to the STORE, never to the running host
///
/// A blob tree is DURABLE STATE, and the disks it lives on move between machines: a media library
/// on an external drive is written on one host and read on another. So a strategy derived from the
/// running OS would re-render the same key differently on the second machine and miss every file —
/// silently, since `locate` is a pure render from the key and has nothing to compare against. The
/// strategy is therefore a property of the tree, decided when it is created and carried with it.
///
/// # A filesystem that cannot honour a store's strategy refuses at OPEN
///
/// Loudly, and never by re-rendering. A quiet fallback is the same miss one step later, and it
/// would corrupt the tree by writing half of it under a second scheme.
///
/// # v1 is the only strategy, and a tree with no marker IS v1
///
/// Neither law can bite yet: there is one strategy, it is the portable one, and it is safe on the
/// worst filesystem the product touches — therefore on all of them. No marker file is written and
/// no probe is made, because a marker is owed only once a second strategy exists to distinguish. The
/// laws are written down now so the author of that second strategy inherits them rather than
/// rediscovering them from a library that stopped resolving.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Strategy {
  /// Lowercase-verbatim or `=`-escaped base32 — portable, single-case, injective everywhere, and
  /// the same bytes on every host because the law above admits no other kind.
  V1,
}

impl Strategy {
  /// The strategy a store uses. A `const` while there is one: the seam's shape is what matters
  /// here, and a knob with a single value would be a knob nobody can set.
  const fn of_store() -> Self {
    Self::V1
  }

  /// Render one segment under this strategy. TOTAL under every strategy — that is the seam's
  /// standing requirement, not v1's own choice.
  fn render(self, segment: &str, out: &mut String) {
    match self {
      Self::V1 => render_segment(segment, out),
    }
  }
}

/// Is `segment` writable verbatim — `[a-z0-9._-]+`, not `=`-leading, not `.` or `..`, and not a
/// reserved device name?
///
/// The `.` is in the charset so a dotted-quad address renders browsably, and it is the reason the
/// two CARVES below exist rather than being tidiness. `.` and `..` are inside `[a-z0-9._-]+` and
/// name the current and parent directories on every host, so they are carved into the escaped set —
/// escaped, never refused, since a text id of `..` is a legal id.
///
/// The `=`-leading test remains REDUNDANT against the charset: `=` was not what got widened, so
/// nothing but a future widening of `=` itself could make it bite. It stays because it is the line
/// the injectivity argument actually names, and the widening that just happened is the evidence that
/// such a line earns its keep — the charset grew and this check did not have to be rediscovered.
fn is_verbatim(segment: &str) -> bool {
  !segment.is_empty()
    && !segment.starts_with('=')
    && segment
      .bytes()
      .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_' || b == b'-' || b == b'.')
    && segment != "."
    && segment != ".."
    && !RESERVED.contains(&segment)
}

/// Append `segment` to `out` in whichever form it takes — verbatim, or `=` plus its lowercase
/// base32. TOTAL: every `&str` renders, including the empty one (which escapes to a bare `=`).
fn render_segment(segment: &str, out: &mut String) {
  if is_verbatim(segment) {
    out.push_str(segment);
    return;
  }
  out.push('=');
  let bytes = segment.as_bytes();
  for chunk in bytes.chunks(5) {
    // Pack up to five bytes big-endian into 40 bits, then take five bits at a time. The output
    // length is ceil(bits / 5) with no padding, which is what makes the encoding injective without
    // RFC 4648's `=` padding — a character this scheme has already spent as its prefix.
    let mut buf = [0u8; 5];
    buf[..chunk.len()].copy_from_slice(chunk);
    let packed = u64::from_be_bytes([0, 0, 0, buf[0], buf[1], buf[2], buf[3], buf[4]]);
    let symbols = chunk.len() * 8 / 5 + usize::from(chunk.len() * 8 % 5 != 0);
    for i in 0..symbols {
      let shift = 35 - i * 5;
      out.push(BASE32[((packed >> shift) & 0x1f) as usize] as char);
    }
  }
}

/// The path segments a key renders to — the sink a [`KeySegments`] walk pushes into.
///
/// Every push is TOTAL, so this accumulates and never fails. It holds rendered text rather than the
/// ids themselves, because the rendering is what both a `put` and a by-key `get` must agree on and
/// doing it once at the push is what keeps them from disagreeing.
#[derive(Debug, Default)]
pub struct Segments {
  rendered: Vec<String>,
}

impl Segments {
  /// An empty sink — the backend mints one per op.
  #[inline]
  pub const fn new() -> Self {
    Self {
      rendered: Vec::new(),
    }
  }

  /// Append one key field as one path segment.
  ///
  /// Generic over the CLOSED [`Id`] vocabulary, so the set of things that can become a segment is
  /// the set of things that can be an id — there is no second admission question here, and no way
  /// for a walk to push something the vocabulary has not admitted.
  #[inline]
  pub fn push<I: Segment>(&mut self, id: &I) {
    let mut out = String::new();
    id.render(&mut out);
    self.rendered.push(out);
  }

  /// Append one DISCRIMINANT as one path segment — the word naming which of several shapes a key
  /// took, where [`push`](Self::push) appends a VALUE.
  ///
  /// # The word, and not a number
  ///
  /// A node drawing from several upstreams addresses each message by the upstream it came from, and
  /// the discriminant is that upstream's own word wherever it is spelled: a directory here, a
  /// column in a row, a field in an engine. One vocabulary across all of them is what lets an
  /// artifact be found from the declaration a reader has in front of them, and it is why nothing
  /// here packs a tag.
  ///
  /// # A separate door, because a discriminant is not an id
  ///
  /// [`push`](Self::push) is generic over the closed [`Id`] vocabulary, and that closure is the
  /// property it exists for: a walk cannot render something the vocabulary has not admitted. A
  /// discriminant is not an id at all — it is a name the FRAMEWORK minted from a declaration, never
  /// a value a row carries — so admitting it through the id door would have meant widening a
  /// closure whose whole content is that it is narrow.
  #[inline]
  pub fn push_word(&mut self, word: &'static str) {
    self.rendered.push(word.to_owned());
  }

  /// The rendered segments, in push order.
  #[inline]
  pub fn as_slice(&self) -> &[String] {
    &self.rendered
  }
}

/// How a key walks its fields into [`Segments`] — the fs backend's own key requirement.
///
/// Fs-LOCAL on purpose: an address is a filesystem's question, so the trait is declared beside the
/// backend that asks it, and a HAND-WRITTEN key that lives in a database and never in a file owes
/// it nothing. A key implements it by pushing its fields in lineage order, parent ids first and the
/// leaf last.
///
/// **A DECLARED key gets that impl from `#[ingraph::record(…)]`** — `impl KeySegments for
/// <Record>Key`, one push per key column in the key's own order. It is emitted for every
/// declaration rather than for the ones that store bytes, because a declaration carries no word
/// saying which stores will hold it and the walk is settled by the key's shape alone; the cost to a
/// record that never becomes a file is one impl. So the sentence above describes a hand-written key,
/// and a derived one is already this.
///
/// The walk is INFALLIBLE, because every push is — see the module note on totality.
pub trait KeySegments {
  /// Push this key's fields, in the order they nest as directories.
  fn segments(&self, out: &mut Segments);
}

/// How one [`Id`] member becomes one path segment.
///
/// Its supertrait is the sealed vocabulary and its own name is unreachable from outside this crate,
/// so the set of renderable ids is exactly the set of ids — closed at both ends, and now CHECKED at
/// both. The seal closes it from OUTSIDE: a downstream type acquires a rendering only by acquiring
/// membership, and the one door to membership is a delegation whose delegate already renders. The
/// audit further down closes it from INSIDE: `audit_segment!` instantiates this bound once per row
/// of `id::for_each_id_member!`, which is the same list `id!` writes the admissions from — so a
/// member admitted with no `Render` impl is a compile error naming that member, where it used to be
/// two hand-synced files and a hope.
pub trait Segment: Id + private::Render {}

impl<I: Id + private::Render> Segment for I {}

mod private {
  #[diagnostic::on_unimplemented(
    message = "`{Self}` has no filesystem rendering, so it cannot become a path segment",
    label = "no rendering",
    note = "the renderable set IS the id vocabulary, so if `{Self}` is a MEASURED member its \
            `Render` impl is missing from `store::fs` — add it beside the row \
            `id::for_each_id_member!` admits it on. If `{Self}` DELEGATES, the delegation row below \
            already renders it and what is missing is the delegate's own rendering. If `{Self}` is \
            neither, it is not a key field type at all: see `ingraph::Id`"
  )]
  pub trait Render {
    fn render(&self, out: &mut String);
  }
}

use private::Render;

macro_rules! render_display {
  ($($ty:ty),* $(,)?) => {
    $(impl Render for $ty {
      #[inline]
      fn render(&self, out: &mut String) {
        // Decimal, and verbatim by construction: the digits and a leading `-` are all inside the
        // verbatim charset, so no integer id ever takes the escape.
        out.push_str(&self.to_string());
      }
    })*
  };
}

render_display!(i8, i16, i32, i64, i128, u8, u16, u32, u64, u128);

macro_rules! render_nonzero {
  ($($ty:ty),* $(,)?) => {
    $(impl Render for $ty {
      #[inline]
      fn render(&self, out: &mut String) {
        // Transparent to the integer member, so a `NonZeroU64` and the `u64` it wraps address the
        // same file — which is what "transparent delegation" has to mean for a stored key.
        out.push_str(&self.get().to_string());
      }
    })*
  };
}

render_nonzero!(
  core::num::NonZeroI8,
  core::num::NonZeroI16,
  core::num::NonZeroI32,
  core::num::NonZeroI64,
  core::num::NonZeroI128,
  core::num::NonZeroU8,
  core::num::NonZeroU16,
  core::num::NonZeroU32,
  core::num::NonZeroU64,
  core::num::NonZeroU128,
);

impl Render for uuid::Uuid {
  #[inline]
  fn render(&self, out: &mut String) {
    // Canonical lowercase hyphenated — verbatim by construction, and the rendering whose byte order
    // matches the uuid's own.
    let mut buf = [0u8; uuid::fmt::Hyphenated::LENGTH];
    out.push_str(self.hyphenated().encode_lower(&mut buf));
  }
}

macro_rules! render_text {
  ($($ty:ty),* $(,)?) => {
    $(impl Render for $ty {
      #[inline]
      fn render(&self, out: &mut String) {
        Strategy::of_store().render(self.as_ref(), out);
      }
    })*
  };
}

render_text!(String, Utf8Bytes);

#[cfg(feature = "smol_str")]
render_text!(smol_str::SmolStr);

// The network family. Each rendering reproduces std's own order — see the matrix on
// [`Id`](crate::Id) for the measurements that decided the byte forms these mirror.
impl Render for core::net::Ipv4Addr {
  #[inline]
  fn render(&self, out: &mut String) {
    // Dotted quad, verbatim through the widened charset — and the octet order IS std's order.
    let [a, b, c, d] = self.octets();
    out.push_str(&format!("{a}.{b}.{c}.{d}"));
  }
}

impl Render for core::net::Ipv6Addr {
  #[inline]
  fn render(&self, out: &mut String) {
    // The sixteen octets as fixed 32 lowercase hex — never the textual form, whose colons are
    // path-hostile and whose `::` compression gives one address several spellings.
    self.octets().render(out);
  }
}

impl Render for core::net::IpAddr {
  #[inline]
  fn render(&self, out: &mut String) {
    // Untagged: a dotted quad carries dots and a v6 rendering is 32 hex characters with none, so the
    // two arms cannot collide and the browsable form survives for both.
    match self {
      Self::V4(ip) => ip.render(out),
      Self::V6(ip) => ip.render(out),
    }
  }
}

impl Render for core::net::SocketAddrV4 {
  #[inline]
  fn render(&self, out: &mut String) {
    self.ip().render(out);
    out.push('_');
    self.port().render(out);
  }
}

impl Render for core::net::SocketAddrV6 {
  #[inline]
  fn render(&self, out: &mut String) {
    // All four fields, in std's own comparison order, and the last two unconditionally: both
    // participate in `Eq` and `Hash`, so omitting them would let two unequal ids share a file.
    self.ip().render(out);
    out.push('_');
    self.port().render(out);
    out.push('_');
    self.flowinfo().render(out);
    out.push('_');
    self.scope_id().render(out);
  }
}

impl Render for core::net::SocketAddr {
  #[inline]
  fn render(&self, out: &mut String) {
    match self {
      Self::V4(addr) => addr.render(out),
      Self::V6(addr) => addr.render(out),
    }
  }
}

// THE DELEGATION ROW — one row for every transparent id there will ever be, this crate's and a
// downstream's alike, and the only `Render` a type outside this crate can acquire.
//
// It replaced four hand rows — `Arc<T>`, `Rc<T>`, `Box<T>` and `TypedId<I, E>`, each of which is now
// a `DelegatesId` — and it is not merely their sum. A delegation's value IS its delegate's, so the
// segment it addresses HAS to be the delegate's segment: a wrapper that rendered anything else would
// name a second file for one key. The pointee's rendering, the typed id's held id and a product
// newtype's inner are one sentence, written once.
//
// It TERMINATES because a MEASURED member is not a delegation: `Arc<TypedId<u64, Scene>>` resolves
// through two delegation steps onto the `u64`'s own row above, and the `u64` bottoms out there. That
// same fact is why this blanket does not overlap the concrete rows — a member's `DelegatesId` is
// knowably absent, and the orphan rule keeps a downstream from adding one for a type it does not
// own.
impl<T> Render for T
where
  T: crate::DelegatesId,
  T::Inner: Render,
{
  #[inline]
  fn render(&self, out: &mut String) {
    <T::Inner as Render>::render(self.delegate(), out);
  }
}

impl<const N: usize> Render for [u8; N] {
  #[inline]
  fn render(&self, out: &mut String) {
    // Lowercase hex, 2N characters — verbatim by construction, and bytewise-monotone, so the path
    // order is the byte order.
    for byte in self {
      out.push(char::from_digit(u32::from(byte >> 4), 16).expect("a nibble is a hex digit"));
      out.push(char::from_digit(u32::from(byte & 0x0f), 16).expect("a nibble is a hex digit"));
    }
  }
}

#[cfg(feature = "mongo")]
impl Render for bson::Uuid {
  #[inline]
  fn render(&self, out: &mut String) {
    uuid::Uuid::from_bytes(self.bytes()).render(out);
  }
}

#[cfg(feature = "mongo")]
impl Render for bson::oid::ObjectId {
  #[inline]
  fn render(&self, out: &mut String) {
    // Lowercase hex of the twelve bytes — the fixed-width byte member's rendering, reached through
    // it rather than restated.
    self.bytes().render(out);
  }
}

/// The probe the audit below instantiates: the same bound [`Segments::push`] asks for, so a type
/// that passes here is one a walk can push.
///
/// `Render` is named a SECOND time, redundantly against `Segment`'s own supertrait, and it earns the
/// redundancy at the only thing this probe produces — its refusal. Reached through the supertrait it
/// is a DERIVED obligation, which rustc renders in the default wording; named here it is the ROOT
/// one, so its `on_unimplemented` note fires and the message says which half is missing and where to
/// write it. Measured both ways.
fn renders_as_a_segment<I: Segment + Render>() {}

/// One `Segment` instantiation per member of the list — the audit's whole body.
macro_rules! audit_segment {
  ($($ty:ty),* $(,)?) => {
    $(
      // Taking the address is enough: a bound is resolved where a generic item is INSTANTIATED, so
      // the call never has to happen for the question to be asked.
      const _: fn() = renders_as_a_segment::<$ty>;
    )*
  };
}

// THE COMPLETENESS AUDIT: every member of the id vocabulary renders, checked by the compiler.
//
// `id::for_each_id_member!` is the one member list, and `id!` there writes the same rows' admissions
// — so the two files can no longer disagree about what a member is. A member admitted with no
// `Render` impl in this file fails HERE, naming itself, where it used to fail at whatever
// declaration first spelled it in a key (or, for a member no shipped key spells, at none).
//
// The gated rows carry their gate in the list, so this audit is complete over the member set of the
// build it is compiled in rather than over `--all-features`'s.
crate::id::for_each_id_member!(audit_segment);

// The GENERIC rows, which no list of types can carry: each is an `impl` over a PARAMETER. A witness
// leaf is the whole audit for them, and not a weaker one — every such impl is bounded on what it
// holds, so the only thing it can fail is EXISTING, and one instantiation settles that.
//
// Four of the five reach their rendering through the ONE delegation row above rather than through
// four hand rows, so what the witnesses now check is that the delegation resolves and TERMINATES.
// The last two do the terminating: a `Box<Arc<u64>>` is two delegation steps onto the `u64`'s own
// concrete row, and an `Arc<TypedId<u64, _>>` is two steps of a different shape onto the same leaf.
// Neither was reachable before — a nested wrapper had no row of its own — so the pair is an audit of
// the new law rather than a restatement of the old one.
const _: () = {
  // An entity naming the wrapper back, which is what the typed id's admission demands of `E`.
  struct Witness;

  impl Identifiable for Witness {
    type Id = TypedId<u64, Witness>;

    fn id_ref(&self) -> &Self::Id {
      unreachable!("the audit takes a function's address and never calls it")
    }
  }

  let _: [fn(); 7] = [
    renders_as_a_segment::<std::sync::Arc<u64>>,
    renders_as_a_segment::<std::rc::Rc<u64>>,
    renders_as_a_segment::<Box<u64>>,
    renders_as_a_segment::<[u8; 16]>,
    renders_as_a_segment::<TypedId<u64, Witness>>,
    renders_as_a_segment::<Box<std::sync::Arc<u64>>>,
    renders_as_a_segment::<std::sync::Arc<TypedId<u64, Witness>>>,
  ];
};

/// The payload of [`LocalFsBlobError::SegmentTooLong`]: which component was too long, what it
/// rendered to, and the ceiling it passed.
///
/// One path component of the address is longer than a name a filesystem can hold, so the address
/// cannot be written. REFUSED rather than truncated: a truncated component is a silent collision,
/// and two keys sharing one file is what the whole address scheme exists to prevent.
///
/// This is about a LENGTH and never about a value's content — every id renders, and one that renders
/// long is a legal id under an address that does not fit.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SegmentTooLong {
  position: usize,
  got: usize,
  limit: usize,
}

impl SegmentTooLong {
  /// Record that the address's `position`th component rendered to `got` bytes against `limit`.
  #[inline]
  pub(crate) const fn new(position: usize, got: usize, limit: usize) -> Self {
    Self {
      position,
      got,
      limit,
    }
  }

  /// WHICH component, counted among the ones this backend mints under the store's root: the slot at
  /// 0, then the key's own segments in walk order — so at a position `n > 0` the offending field is
  /// the key's `n - 1`th. The root is the caller's own existing directory and is not measured; the
  /// whole address is, by [`PathTooLong`].
  #[inline]
  pub const fn position(&self) -> usize {
    self.position
  }

  /// The component's rendered length in bytes — the LEAF's including the record's extension, because
  /// the extension is part of the name a filesystem holds.
  #[inline]
  pub const fn got(&self) -> usize {
    self.got
  }

  /// [`MAX_SEGMENT_LEN`], carried so a caught error holds the whole comparison.
  #[inline]
  pub const fn limit(&self) -> usize {
    self.limit
  }
}

/// The payload of [`LocalFsBlobError::PathTooLong`]: the address that did not fit, its length, and
/// the ceiling it passed.
///
/// The whole address is longer than a portable path may be. Only the walk sees it: the root, the
/// slot and every segment together are what exceed the ceiling, and each of them can be under the
/// per-component one.
///
/// Refused rather than truncated, for the reason [`SegmentTooLong`] is, and against ONE ceiling on
/// every host rather than the running one's — see [`MAX_PATH_LEN`] for the per-OS variance this
/// collapses and why the smallest of it is the number.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PathTooLong {
  path: PathBuf,
  got: usize,
  limit: usize,
}

impl PathTooLong {
  /// Record that `path` assembled to `got` bytes against `limit`.
  #[inline]
  pub(crate) const fn new(path: PathBuf, got: usize, limit: usize) -> Self {
    Self { path, got, limit }
  }

  /// The address that did not fit. Carried whole, because it is what a reader has to look at to see
  /// WHICH of the root, the slot and the lineage is the long part.
  #[inline]
  pub fn path(&self) -> &Path {
    &self.path
  }

  /// The address's length in bytes.
  #[inline]
  pub const fn got(&self) -> usize {
    self.got
  }

  /// [`MAX_PATH_LEN`], carried so a caught error holds the whole comparison.
  #[inline]
  pub const fn limit(&self) -> usize {
    self.limit
  }
}

/// A local-filesystem blob failure.
///
/// No arm names a segment's CONTENT, and that absence is the design: rendering is total, so there is
/// no invalid segment to report — every value of every member renders, and the escape is what makes
/// that true. What can still fail is the slot (a name this backend makes a directory of), a key with
/// no fields at all, the filesystem, and LENGTH.
///
/// Length is the exception that proves the rule rather than a hole in it: the two length arms are
/// about the ADDRESS a walk assembles — how deep the lineage runs, how long the caller's root is —
/// and never about whether a value was allowed to be an id. Both refuse and neither truncates.
#[derive(Debug)]
#[non_exhaustive]
pub enum LocalFsBlobError {
  /// A filesystem call failed — creating the root, staging or renaming the tmp file, or a
  /// non-missing read error.
  Io(io::Error),
  /// `get` was asked for a key whose file is absent. Carries the resolved path, so the miss is
  /// precise.
  Missing(PathBuf),
  /// The slot is not an identifier, so this store will not name an artifact-family directory after
  /// it. A slot NAMES the first path level under the root, and it is also every other backend's
  /// resource name, so it answers to the crate's ONE identifier rule rather than to a per-backend
  /// one. Rendered with `Debug` because it is caller-supplied and may carry control characters that
  /// `Display` would emit raw into a log.
  InvalidSlot(Utf8Bytes),
  /// The key rendered NO segments, so no file can be addressed. This is a key with no FIELDS — not
  /// a field with an unusable value, which cannot occur.
  EmptyKey,
  /// A caller handed a SUFFIX no address could end with — the empty string, `.`, `..`, or one
  /// carrying a separator or a NUL. Each would make the address malformed rather than merely ugly: a
  /// separator invents a directory level the key never declared, and `..` invents one above the
  /// store's own root.
  ///
  /// It is the runtime half of a floor the grammar already holds for a STATIC suffix. It exists
  /// because a PER-ENTRY one is a column's value or a hook's return, which no expansion sees.
  /// Rendered with `Debug` for the reason [`InvalidSlot`](Self::InvalidSlot) is.
  InvalidSuffix(Utf8Bytes),
  /// One path component of the address is longer than a name a filesystem can hold — see
  /// [`SegmentTooLong`].
  SegmentTooLong(SegmentTooLong),
  /// The whole address is longer than a portable path may be — see [`PathTooLong`].
  PathTooLong(PathTooLong),
  /// A resolved path is not valid UTF-8, so it cannot render to a location's ADDRESS —
  /// refused rather than lossily replaced, since an address a client round-trips must be the exact
  /// one. Near-unreachable: every rendered segment is ASCII, so only a non-UTF-8 store ROOT
  /// reaches it.
  NonUtf8Address(PathBuf),
}

impl core::fmt::Display for LocalFsBlobError {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    match self {
      Self::Io(error) => error.fmt(f),
      Self::Missing(path) => write!(f, "no blob stored at {path:?}"),
      Self::InvalidSlot(slot) => write!(
        f,
        "{slot:?} is not a valid slot: it must be an identifier — `[A-Za-z_][A-Za-z0-9_]*`"
      ),
      Self::EmptyKey => {
        f.write_str("the key rendered no path segments — a keyed blob needs at least one key field")
      }
      Self::InvalidSuffix(suffix) => write!(
        f,
        "{suffix:?} cannot end a blob address: a suffix may not be empty, `.` or `..`, and may not \
         carry a separator or a NUL — each would invent a directory level the key never declared"
      ),
      Self::SegmentTooLong(error) => write!(
        f,
        "component {} of the blob address renders to {} bytes, past the {} one path component may \
         take",
        error.position(),
        error.got(),
        error.limit()
      ),
      Self::PathTooLong(error) => write!(
        f,
        "the blob address {:?} is {} bytes, past the {} a portable path may take",
        error.path(),
        error.got(),
        error.limit()
      ),
      Self::NonUtf8Address(path) => write!(
        f,
        "the blob path {path:?} is not valid UTF-8, so it cannot render to a location's address"
      ),
    }
  }
}

impl core::error::Error for LocalFsBlobError {
  fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
    match self {
      Self::Io(error) => Some(error),
      _ => None,
    }
  }
}

impl From<io::Error> for LocalFsBlobError {
  #[inline]
  fn from(error: io::Error) -> Self {
    Self::Io(error)
  }
}

/// The local-filesystem connection-manager and the shared connection its handles thread: THE one
/// root, created once by [`open`](Self::open). It IS the [`AsyncBlobEngine::Connection`] of the handles
/// [`blob`](Self::blob) mints — a handle holds only its slot and reaches the root through
/// `ctx.connection()`.
#[derive(Debug, Clone)]
pub struct LocalFsStore {
  root: PathBuf,
}

impl LocalFsStore {
  /// Open a blob store rooted at `root`, creating the directory and any missing parents.
  ///
  /// # Errors
  ///
  /// [`LocalFsBlobError::Io`] if the root cannot be created.
  pub fn open(root: impl AsRef<Path>) -> Result<Self, LocalFsBlobError> {
    let root = root.as_ref().to_path_buf();
    fs::create_dir_all(&root)?;
    Ok(Self { root })
  }

  /// The root every artifact-family slot resolves under.
  #[inline]
  pub fn root(&self) -> &Path {
    &self.root
  }
}

/// The local-filesystem blob face — a STATELESS keyed handle holding ONLY its artifact-family slot.
/// It threads the [`LocalFsStore`] as its connection, so `put` publishes under, and `get` resolves
/// against, the manager's one root.
#[derive(Debug, Clone)]
pub struct LocalFsBlob {
  slot: Utf8Bytes,
}

impl LocalFsBlob {
  /// A blob handle for artifact-family `slot`.
  #[inline]
  pub fn new(slot: impl Into<Utf8Bytes>) -> Self {
    Self { slot: slot.into() }
  }

  /// The artifact-family slot — the first path level under the store's root.
  #[inline]
  pub fn slot(&self) -> &str {
    &self.slot
  }

  /// The on-disk ADDRESS of `key`'s object under this handle's slot and `root` — the KEY-ONLY door
  /// onto the address funnel.
  ///
  /// # Why it exists beside [`Locate::locate`]
  ///
  /// That verb reaches the same funnel and asks its caller for more than the funnel needs: its
  /// supertrait is the read/write face, so a caller has to name a record with a
  /// [`BlobRecord`](crate::BlobRecord) impl even though rendering an address touches no payload. It
  /// was the honest bound while the tail came off `BlobRecord::extension()`; with the suffix handed
  /// in, the funnel's real requirement is the KEY's own walk and nothing else.
  ///
  /// So this is that requirement, spelled — and it is what an artifact family's own
  /// [`ArtifactStore`](crate::ArtifactStore) impl spends. A blob node's `Transformer::Key` is its
  /// UPSTREAM's, and every declaration's key gets a [`KeySegments`] impl whether or not it will ever
  /// become a file, so a family reaches its addresses with no payload face anywhere in sight.
  ///
  /// # Errors
  ///
  /// Every refusal `resolve_path` raises — the slot, the suffix's floor, an empty key, and the two
  /// length ceilings. All of them land before any I/O.
  pub fn address<K>(
    &self,
    root: &Path,
    key: &K,
    suffix: Option<&str>,
  ) -> Result<PathBuf, LocalFsBlobError>
  where
    K: KeySegments,
  {
    resolve_path(&self.slot, root, key, suffix)
  }

  /// The BYTES of `key`'s object under this handle's slot and `root`, or [`None`] where nothing is
  /// stored there — [`address`](Self::address)'s reading twin, at the same bound.
  ///
  /// Synchronous, because a file read IS a blocking syscall — the dual-mode criterion's own reading,
  /// and the same reason [`BlobEngine`] holds this family's bodies. An async caller wraps the
  /// call in whichever resolved future its own seam returns, which is what the shipped
  /// [`AsyncBlobEngine`] face does one seat over.
  ///
  /// ABSENCE IS A VALUE here, as it is on the seam this door answers for: the `NotFound` this
  /// backend already tells apart from every other I/O failure comes back as `Ok(None)` rather than
  /// through the error channel, and the split costs no syscall — the read looked either way.
  ///
  /// # Errors
  ///
  /// Every refusal [`address`](Self::address) raises, plus a real I/O fault — a permission, a path
  /// component that is not a directory. A MISSING object is neither.
  pub fn fetch<K>(
    &self,
    root: &Path,
    key: &K,
    suffix: Option<&str>,
  ) -> Result<Option<Vec<u8>>, LocalFsBlobError>
  where
    K: KeySegments,
  {
    read_optional_blob(&self.slot, root, key, suffix)
  }
}

/// THE NATIVE FACE of this store's construction: creating a directory is a syscall that returns,
/// and the inherent [`LocalFsStore::open`] above has always been spelled that way.
impl BlobStore for LocalFsStore {
  /// The root directory, created if missing.
  type Options = PathBuf;
  type Error = LocalFsBlobError;
  type Handle = LocalFsBlob;

  #[inline]
  fn open(options: Self::Options) -> Result<Self, Self::Error> {
    LocalFsStore::open(options)
  }

  #[inline]
  fn blob(&self, slot: impl Into<Utf8Bytes>) -> Self::Handle {
    LocalFsBlob::new(slot)
  }
}

/// The async face, BRIDGED — and the bridge is the honest kind, which is the whole point of writing
/// it this way.
///
/// It calls the blocking face and resolves immediately. No thread is borrowed, no pool is spawned,
/// nothing is pretended: the future is already complete when it is handed back, so an executor sees
/// one `Poll::Ready` and the caller's `.await` is a formality the type system asked for. That is
/// what a filesystem store honestly offers an async application, and it is why `open` here is `async
/// fn` in name only.
///
/// What it is NOT is `tokio::fs` — a real `spawn_blocking` behind an async signature. That road
/// moves the blocking act to another thread and is a DEPLOYMENT's decision about its own runtime,
/// not a store's about its API; an application that needs it wraps this call itself, with the
/// executor it actually chose.
impl AsyncBlobStore for LocalFsStore {
  type Options = PathBuf;
  type Error = LocalFsBlobError;
  type Handle = LocalFsBlob;

  fn open(options: Self::Options) -> impl Future<Output = Result<Self, Self::Error>> + Send {
    ready(<Self as BlobStore>::open(options))
  }

  #[inline]
  fn blob(&self, slot: impl Into<Utf8Bytes>) -> Self::Handle {
    <Self as BlobStore>::blob(self, slot)
  }
}

/// A record storable through this backend: its key walks into path segments.
///
/// The address renders FROM THE KEY, never from the record, so a `put` — which reaches the key
/// through `record.key()` — and a by-key `get` walk the same type and reach the identical path.
/// There is no second rendering to disagree.
pub trait LocalFsBlobRecord: BlobRecord + Transformer<Key: KeySegments> {}

impl<T> LocalFsBlobRecord for T where T: BlobRecord + Transformer<Key: KeySegments> {}

/// Resolve a key to its on-disk path: `<root>/<slot>/<seg1>/…/<segN>[.<suffix>]`.
///
/// The single funnel `put`, `get`, `read` and `locate` reach a file through, so every guard runs
/// here, once, on the assembled address. That includes both LENGTH ceilings — this is the only place
/// that holds the root, the slot and every rendered segment at the same time, which is what makes
/// the aggregate one checkable at all.
///
/// The refusals land before any IO, so a caller that only wants the address gets them from `locate`
/// and never from a half-made directory tree.
///
/// # The suffix is a PARAMETER, and its two callers are the two authorities
///
/// `put` and `get` pass `R::extension()` — the TYPE's answer, which a by-key read must use because
/// it holds no row to ask. `locate` and `read` pass what the CALLER decided, because a family whose
/// suffix comes off a column has that value only where the row is. One funnel either way, so the
/// address is assembled in one place however its tail was chosen.
///
/// The bound is the KEY ITSELF rather than [`LocalFsBlobRecord`], and the narrowing is what the
/// parameter bought: with the suffix handed in, nothing here reads [`BlobRecord`](crate::BlobRecord)
/// or even [`Transformer`] — an address is the slot, the root, the key's own walk and a tail, and
/// the funnel now asks for exactly those. [`LocalFsBlob::address`] is the door that spends the
/// narrowing.
///
/// # Errors
///
/// [`LocalFsBlobError::InvalidSlot`] if the slot is not an identifier;
/// [`LocalFsBlobError::InvalidSuffix`] if the suffix could not end an address;
/// [`LocalFsBlobError::EmptyKey`] if the key has no fields;
/// [`LocalFsBlobError::SegmentTooLong`] if one component exceeds [`MAX_SEGMENT_LEN`];
/// [`LocalFsBlobError::PathTooLong`] if the whole address exceeds [`MAX_PATH_LEN`].
fn resolve_path<K>(
  slot: &str,
  root: &Path,
  key: &K,
  suffix: Option<&str>,
) -> Result<PathBuf, LocalFsBlobError>
where
  K: KeySegments,
{
  if !crate::slot::is_identifier(slot.as_bytes()) {
    return Err(LocalFsBlobError::InvalidSlot(Utf8Bytes::from(slot)));
  }
  // THE FLOOR, at the last line that could still hold it. The grammar refuses a malformed STATIC
  // suffix where it was written; a per-entry one is a column's value or a hook's return, and no
  // expansion sees either — so the address's well-formedness is checked where the address is built.
  // What is refused is what no host can hold and never this backend's verbatim charset, which is
  // `ingraph_codegen::extension::admissible_suffix`'s own division, stated there in full.
  if let Some(suffix) = suffix
    && (suffix.is_empty() || suffix == "." || suffix == ".." || suffix.contains(['/', '\\', '\0']))
  {
    return Err(LocalFsBlobError::InvalidSuffix(Utf8Bytes::from(suffix)));
  }
  let mut rendered = Segments::new();
  key.segments(&mut rendered);
  // The last field is the FILE, carrying the address's suffix; the earlier ones are its parent
  // directories — the lineage path.
  let (leaf, parents) = rendered
    .as_slice()
    .split_last()
    .ok_or(LocalFsBlobError::EmptyKey)?;
  // A verbatim leaf carries no `.` and an escaped one carries only base32, so the suffix's `.` is
  // the leaf name's only dot either way — and the floor above is what keeps that true of a suffix a
  // caller computed. Built BEFORE the ceiling check, because the name a filesystem measures is the
  // one with the suffix on it.
  let file_name = match suffix {
    Some(ext) => Cow::Owned(format!("{leaf}.{ext}")),
    None => Cow::Borrowed(leaf.as_str()),
  };

  // The slot is component 0 — it is a directory name this backend mints, so it answers to the same
  // ceiling the segments do. Its identifier rule above is a CHARSET and says nothing about length.
  let mut path = root.to_path_buf();
  for (position, component) in core::iter::once(slot)
    .chain(parents.iter().map(String::as_str))
    .chain(core::iter::once(file_name.as_ref()))
    .enumerate()
  {
    let got = component.len();
    if got > MAX_SEGMENT_LEN {
      return Err(LocalFsBlobError::SegmentTooLong(SegmentTooLong::new(
        position,
        got,
        MAX_SEGMENT_LEN,
      )));
    }
    path.push(component);
  }

  let got = path.as_os_str().len();
  if got > MAX_PATH_LEN {
    return Err(LocalFsBlobError::PathTooLong(PathTooLong::new(
      path,
      got,
      MAX_PATH_LEN,
    )));
  }
  Ok(path)
}

/// Render a resolved blob path to its ADDRESS — the text component of a location.
///
/// The ADDRESS and not the whole location: what a [`AsyncLocate::Location`] carries AROUND the address is
/// the backend's, and this backend's answer is [`BlobLocation`], built from this.
///
/// # Errors
///
/// [`LocalFsBlobError::NonUtf8Address`] if the path is not valid UTF-8.
pub fn blob_address(reference: &Path) -> Result<String, LocalFsBlobError> {
  reference
    .to_str()
    .map(str::to_owned)
    .ok_or_else(|| LocalFsBlobError::NonUtf8Address(reference.to_path_buf()))
}

/// THE NATIVE FACE. `std::fs` is what a file read IS, so this is where the bodies live and the
/// async impl below is what delegates — the opposite of the arrangement a store whose I/O is
/// natively a socket would write.
impl<R> BlobEngine<R> for LocalFsBlob
where
  R: LocalFsBlobRecord,
  R::Bytes: AsRef<[u8]>,
{
  type Options = ();
  type Error = LocalFsBlobError;
  /// `Vec<u8>`: a filesystem read already hands back an owned buffer, so this face has nothing to
  /// gain from a zero-copy body — a remote backend is the one that would choose differently, which
  /// is why the trait leaves the choice open.
  type Payload = Vec<u8>;
  /// The manager, whose one root every op resolves under.
  type Connection = LocalFsStore;
  /// `()`: a key-addressed store reads whatever is at the key's path, so no read knob rides the
  /// scope.
  type ReadContext<'a> = ();
  /// `()`: a standalone blob store threads no cross-face transaction, and each `put` is its own
  /// atomically-visible unit.
  type WriteContext<'a> = ();

  fn put(
    &self,
    ctx: Connected<'_, Self::Connection, Self::WriteContext<'_>>,
    record: &R,
  ) -> Result<(), Self::Error> {
    store_blob::<R>(&self.slot, ctx.connection().root(), record)
  }

  fn get(
    &self,
    ctx: Connected<'_, Self::Connection, Self::ReadContext<'_>>,
    key: &R::Key,
  ) -> Result<Self::Payload, Self::Error>
  where
    R: Transformer,
  {
    read_blob(&self.slot, ctx.connection().root(), key, R::extension())
  }

  /// The absence split this backend already drew INSIDE its error type, moved out to the answer:
  /// [`LocalFsBlobError::Missing`] is what `read_blob` mints for a `NotFound`, so `Ok(None)` here
  /// costs nothing but the match. `get` beside it keeps the narrow shape — the widening is the
  /// `read` road's, which is the road a wire `data` position spends.
  fn read(
    &self,
    ctx: Connected<'_, Self::Connection, Self::ReadContext<'_>>,
    key: &R::Key,
    suffix: Option<&str>,
  ) -> Result<Option<Self::Payload>, Self::Error>
  where
    R: Transformer,
  {
    read_optional_blob(&self.slot, ctx.connection().root(), key, suffix)
  }
}

/// The async face, BRIDGED to the native one above — ONE body per verb, reached from two faces.
///
/// The delegation is written rather than the bodies duplicated, and that is a correctness property
/// and not tidiness: a second copy of `store_blob`'s call is a second place for the slot, the root
/// and the extension to be assembled, and this backend's whole guarantee is that `put`, `get` and
/// `locate` walk ONE address funnel.
impl<R> AsyncBlobEngine<R> for LocalFsBlob
where
  R: LocalFsBlobRecord,
  R::Bytes: AsRef<[u8]>,
{
  type Options = ();
  type Error = LocalFsBlobError;
  type Payload = Vec<u8>;
  type Connection = LocalFsStore;
  type ReadContext<'a> = ();
  type WriteContext<'a> = ();

  fn put(
    &self,
    ctx: Connected<'_, Self::Connection, Self::WriteContext<'_>>,
    record: &R,
  ) -> impl Future<Output = Result<(), Self::Error>> + Send {
    ready(<Self as BlobEngine<R>>::put(self, ctx, record))
  }

  fn get(
    &self,
    ctx: Connected<'_, Self::Connection, Self::ReadContext<'_>>,
    key: &R::Key,
  ) -> impl Future<Output = Result<Self::Payload, Self::Error>> + Send
  where
    R: Transformer,
  {
    ready(<Self as BlobEngine<R>>::get(self, ctx, key))
  }

  fn read(
    &self,
    ctx: Connected<'_, Self::Connection, Self::ReadContext<'_>>,
    key: &R::Key,
    suffix: Option<&str>,
  ) -> impl Future<Output = Result<Option<Self::Payload>, Self::Error>> + Send
  where
    R: Transformer,
  {
    ready(<Self as BlobEngine<R>>::read(self, ctx, key, suffix))
  }
}

/// THE NATIVE FACE of address resolution. Both verbs were already free of I/O — `locate` renders
/// from the key and `location` renders from the reference — so this face is the one that says so
/// without a future in the way.
impl<R> Locate<R> for LocalFsBlob
where
  R: LocalFsBlobRecord,
  R::Bytes: AsRef<[u8]>,
{
  /// OWNED, and the lifetime parameter goes unspent: a resolved address is built out of the root and
  /// the key's own segments, so there is nothing on the connection for it to point into. The seat
  /// takes a lifetime for the backend that WOULD have one — see [`AsyncLocate::Ref`].
  type Ref<'a> = PathBuf;
  /// [`BlobLocation`], the SHIPPED citizen — this store knows where a file is and nothing else about
  /// it, which is exactly the shape that type exists for.
  ///
  /// It is an ELECTION and not an inheritance: nothing about implementing [`AsyncLocate`] hands a backend
  /// this type, and a filesystem store wanting to say more — a `file://` URL, a device id, an inode
  /// — writes its own and changes only this line.
  type Location = BlobLocation;
  type LocateError = LocalFsBlobError;

  fn locate<'a>(
    &'a self,
    ctx: Connected<'a, Self::Connection, Self::ReadContext<'a>>,
    key: &'a R::Key,
    suffix: Option<&str>,
  ) -> Result<Self::Ref<'a>, LocalFsBlobError>
  where
    R: Transformer,
  {
    resolve_path(&self.slot, ctx.connection().root(), key, suffix)
  }

  /// The path, as text. NEITHER optional member is filled, and that is the pin rather than a gap: a
  /// length and a media type would each cost a `stat` — a length directly, a media type through the
  /// sniff a bare extension does not settle — and describing an address does no I/O.
  fn location<'a>(&'a self, reference: Self::Ref<'a>) -> Result<BlobLocation, LocalFsBlobError> {
    blob_address(&reference).map(BlobLocation::new)
  }
}

/// The other face, DELEGATED — and here there is no bridge at all, because neither verb ever touched
/// the disk and neither is wrapped. Both are plain calls onto the face above.
///
/// This is the capability where the two faces became method-identical, and the delegation is what
/// keeps them one body: the address funnel is reached from exactly one place whichever trait a
/// caller's bound named.
impl<R> AsyncLocate<R> for LocalFsBlob
where
  R: LocalFsBlobRecord,
  R::Bytes: AsRef<[u8]>,
{
  type Ref<'a> = PathBuf;
  type Location = BlobLocation;
  type LocateError = LocalFsBlobError;

  fn locate<'a>(
    &'a self,
    ctx: Connected<'a, Self::Connection, Self::ReadContext<'a>>,
    key: &'a R::Key,
    suffix: Option<&str>,
  ) -> Result<Self::Ref<'a>, LocalFsBlobError>
  where
    R: Transformer,
  {
    <Self as Locate<R>>::locate(self, ctx, key, suffix)
  }

  fn location<'a>(&'a self, reference: Self::Ref<'a>) -> Result<BlobLocation, LocalFsBlobError> {
    <Self as Locate<R>>::location(self, reference)
  }
}

fn store_blob<R>(slot: &str, root: &Path, record: &R) -> Result<(), LocalFsBlobError>
where
  R: LocalFsBlobRecord,
  R::Bytes: AsRef<[u8]>,
{
  let path = resolve_path(slot, root, &record.key(), R::extension())?;
  publish(&path, record.bytes().as_ref())?;
  Ok(())
}

fn read_blob<K>(
  slot: &str,
  root: &Path,
  key: &K,
  suffix: Option<&str>,
) -> Result<Vec<u8>, LocalFsBlobError>
where
  K: KeySegments,
{
  let path = resolve_path(slot, root, key, suffix)?;
  match fs::read(&path) {
    Ok(bytes) => Ok(bytes),
    Err(err) if err.kind() == io::ErrorKind::NotFound => Err(LocalFsBlobError::Missing(path)),
    Err(err) => Err(err.into()),
  }
}

/// [`read_blob`] with the MISS as a value — the read road's face, where `get`'s is the one above.
///
/// One body reached from two faces, exactly as the rest of this backend is written: the address
/// funnel, the syscall and the `NotFound` split are all [`read_blob`]'s, and what this adds is the
/// one match that moves a miss out of the error channel. A second `fs::read` here would be a second
/// place for the split to be drawn, and this backend's whole guarantee is that there is one.
///
/// Nothing is looked at twice: the widening reads the answer the syscall already gave.
fn read_optional_blob<K>(
  slot: &str,
  root: &Path,
  key: &K,
  suffix: Option<&str>,
) -> Result<Option<Vec<u8>>, LocalFsBlobError>
where
  K: KeySegments,
{
  match read_blob(slot, root, key, suffix) {
    Ok(bytes) => Ok(Some(bytes)),
    // The MISS, and only the miss. Every other refusal — a slot, a key or a suffix that renders no
    // address, a permission, a component that is not a directory — stays what it was.
    Err(LocalFsBlobError::Missing(_)) => Ok(None),
    Err(err) => Err(err),
  }
}

/// Stage the bytes beside `final_path` and rename the tmp file OVER it — the atomic keyed replace.
fn publish(final_path: &Path, bytes: &[u8]) -> io::Result<()> {
  let parent = final_path
    .parent()
    .expect("a key path always has a parent directory");
  fs::create_dir_all(parent)?;

  let nonce = PUT_NONCE.fetch_add(1, Ordering::Relaxed);
  let file_name = final_path
    .file_name()
    .expect("a key path always has a file name");
  let mut tmp_name = file_name.to_os_string();
  tmp_name.push(format!(".tmp.{}.{nonce}", std::process::id()));
  let tmp_path = parent.join(tmp_name);

  // `create_new` refuses to clobber a colliding tmp, surfacing it as an honest error rather than
  // appending to a file this call did not make. Such a collision can never be a live writer's
  // in-flight stage — the nonce and the pid give concurrent puts to one key distinct tmp paths — so
  // it is crash residue or a foreign file, and either way it is not ours. That is why the open sits
  // OUTSIDE the reaped region: a call may remove only a file it CREATED.
  let file = OpenOptions::new()
    .create_new(true)
    .write(true)
    .open(&tmp_path)?;
  // Every failure from here until the rename leaves that staged tmp on disk, and nothing else ever
  // reaps it. The removal is best-effort and its own error is discarded on purpose: the publish
  // failure is the cause the caller needs, and a cleanup error must not displace it.
  if let Err(err) = stage_and_rename(file, bytes, &tmp_path, final_path) {
    let _ = fs::remove_file(&tmp_path);
    return Err(err);
  }
  Ok(())
}

/// Write the bytes into the tmp file the caller has just created and therefore owns, then rename it
/// over the final path. One function, so the staged tmp has a SINGLE fallible region behind it —
/// which is what makes [`publish`]'s reap-on-failure complete.
fn stage_and_rename(
  mut file: File,
  bytes: &[u8],
  tmp_path: &Path,
  final_path: &Path,
) -> io::Result<()> {
  file.write_all(bytes)?;
  // The descriptor closes before the rename, so the published name never points at an open,
  // still-writable file.
  drop(file);
  fs::rename(tmp_path, final_path)
}

#[cfg(test)]
mod tests;