forked from mirage/irmin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinode.ml
2407 lines (2114 loc) · 86.4 KB
/
inode.ml
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
(*
* Copyright (c) 2018-2022 Tarides <[email protected]>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*)
open! Import
include Inode_intf
exception Max_depth of int
module Make_internal
(Conf : Conf.S)
(H : Irmin.Hash.S) (Key : sig
include Irmin.Key.S with type hash = H.t
val unfindable_of_hash : hash -> t
end)
(Node : Irmin.Node.Generic_key.S
with type hash = H.t
and type contents_key = Key.t
and type node_key = Key.t) =
struct
(** If [should_be_stable ~length ~root] is true for an inode [i], then [i]
hashes the same way as a [Node.t] containing the same entries. *)
let should_be_stable ~length ~root =
if length = 0 then true
else if not root then false
else if length <= Conf.stable_hash then true
else false
module Node = struct
include Node
module H = Irmin.Hash.Typed (H) (Node)
let hash = H.hash
end
(* Keep at most 50 bits of information. *)
let max_depth = int_of_float (log (2. ** 50.) /. log (float Conf.entries))
module T = struct
type hash = H.t [@@deriving irmin ~pp ~to_bin_string ~equal]
type key = Key.t [@@deriving irmin ~pp ~equal]
type node_key = Node.node_key [@@deriving irmin]
type contents_key = Node.contents_key [@@deriving irmin]
type step = Node.step
[@@deriving irmin ~compare ~to_bin_string ~of_bin_string ~short_hash]
type metadata = Node.metadata [@@deriving irmin ~equal]
type value = Node.value [@@deriving irmin ~equal]
module Metadata = Node.Metadata
exception Dangling_hash = Node.Dangling_hash
let raise_dangling_hash c hash =
let context = "Irmin_pack.Inode." ^ c in
raise (Dangling_hash { context; hash })
let unsafe_keyvalue_of_hashvalue = function
| `Contents (h, m) -> `Contents (Key.unfindable_of_hash h, m)
| `Node h -> `Node (Key.unfindable_of_hash h)
let hashvalue_of_keyvalue = function
| `Contents (k, m) -> `Contents (Key.to_hash k, m)
| `Node k -> `Node (Key.to_hash k)
end
module Step =
Irmin.Hash.Typed
(H)
(struct
type t = T.step
let t = T.step_t
end)
module Child_ordering : Child_ordering with type step := T.step = struct
open T
type key = bytes
let log_entry = int_of_float (log (float Conf.entries) /. log 2.)
let () =
assert (log_entry >= 1);
(* NOTE: the [`Hash_bits] mode is restricted to inodes with at most 1024
entries in order to simplify the implementation (see below). *)
assert ((not (Conf.inode_child_order = `Hash_bits)) || log_entry <= 10);
assert (Conf.entries = int_of_float (2. ** float log_entry))
let key =
match Conf.inode_child_order with
| `Hash_bits ->
(* Bytes.unsafe_of_string usage: possibly safe TODO justify safety, or switch to
use the safe Bytes.of_string *)
fun s -> Bytes.unsafe_of_string (hash_to_bin_string (Step.hash s))
| `Seeded_hash | `Custom _ ->
(* Bytes.unsafe_of_string usage: possibly safe TODO justify safety, or switch to
use the safe Bytes.of_string *)
fun s -> Bytes.unsafe_of_string (step_to_bin_string s)
(* Assume [k = cryto_hash(step)] (see {!key}) and [Conf.entry] can
can represented with [n] bits. Then, [hash_bits ~depth k] is
the [n]-bits integer [i] with the following binary representation:
[k(n*depth) ... k(n*depth+n-1)]
When [n] is not a power of 2, [hash_bits] needs to handle
unaligned reads properly. *)
let hash_bits ~depth k =
assert (Bytes.length k = Step.hash_size);
(* We require above that the child indices have at most 10 bits to ensure
that they span no more than 2 bytes of the step hash. The 3 byte case
(with [1 + 8 + 1]) does not happen for 10-bit indices because 10 is
even, but [2 + 8 + 1] would occur with 11-byte indices (e.g. when
[depth=2]). *)
let byte = 8 in
let initial_bit_pos = log_entry * depth in
let n = initial_bit_pos / byte in
let r = initial_bit_pos mod byte in
if n >= Step.hash_size then raise (Max_depth depth);
if r + log_entry <= byte then
(* The index is contained in a single character of the hash *)
let i = Bytes.get_uint8 k n in
let e0 = i lsr (byte - log_entry - r) in
let r0 = e0 land (Conf.entries - 1) in
r0
else
(* The index spans two characters of the hash *)
let i0 = Bytes.get_uint8 k n in
let to_read = byte - r in
let rest = log_entry - to_read in
let mask = (1 lsl to_read) - 1 in
let r0 = (i0 land mask) lsl rest in
if n + 1 >= Step.hash_size then raise (Max_depth depth);
let i1 = Bytes.get_uint8 k (n + 1) in
let r1 = i1 lsr (byte - rest) in
r0 + r1
let short_hash = Irmin.Type.(unstage (short_hash bytes))
let seeded_hash ~depth k = abs (short_hash ~seed:depth k) mod Conf.entries
let index =
match Conf.inode_child_order with
| `Seeded_hash -> seeded_hash
| `Hash_bits -> hash_bits
| `Custom f -> f
end
module StepMap = struct
include Map.Make (struct
type t = T.step
let compare = T.compare_step
end)
let of_list l = List.fold_left (fun acc (k, v) -> add k v acc) empty l
end
module Val_ref : sig
open T
type t [@@deriving irmin]
type v = private Key of Key.t | Hash of hash Lazy.t
val inspect : t -> v
val of_key : key -> t
val of_hash : hash Lazy.t -> t
val promote_exn : t -> key -> unit
val to_hash : t -> hash
val to_lazy_hash : t -> hash Lazy.t
val to_key_exn : t -> key
val is_key : t -> bool
end = struct
open T
(** Nodes that have been persisted to an underlying store are referenced via
keys. Otherwise, when building in-memory inodes (e.g. via [Portable] or
[of_concrete_exn]) lazily-computed hashes are used instead. If such
values are persisted, the hash reference can be promoted to a key
reference (but [Key] values are never demoted to hashes).
NOTE: in future, we could reflect the case of this type in a type
parameter and refactor the [layout] types below to get static guarantees
that [Portable] nodes (with hashes for internal pointers) are not saved
without first saving their children. *)
type v = Key of Key.t | Hash of hash Lazy.t [@@deriving irmin ~pp_dump]
type t = v ref
let inspect t = !t
let of_key k = ref (Key k)
let of_hash h = ref (Hash h)
let promote_exn t k =
let existing_hash =
match !t with
| Key k' ->
(* NOTE: it's valid for [k'] to not be strictly equal to [k], because
of duplicate objects in the store. In this case, we preferentially
take the newer key. *)
Key.to_hash k'
| Hash h -> Lazy.force h
in
if not (equal_hash existing_hash (Key.to_hash k)) then
Fmt.failwith
"Attempted to promote existing reference %a to an inconsistent key %a"
pp_dump_v !t pp_key k;
t := Key k
let to_hash t =
match !t with Hash h -> Lazy.force h | Key k -> Key.to_hash k
let to_lazy_hash t =
match !t with Hash h -> h | Key k -> lazy (Key.to_hash k)
let is_key t = match !t with Key _ -> true | _ -> false
let to_key_exn t =
match !t with
| Key k -> k
| Hash h ->
Fmt.failwith "Encountered unkeyed hash but expected key: %a" pp_hash
(Lazy.force h)
let t =
let pre_hash_hash = Irmin.Type.(unstage (pre_hash hash_t)) in
let pre_hash x f =
match !x with
| Key k -> pre_hash_hash (Key.to_hash k) f
| Hash h -> pre_hash_hash (Lazy.force h) f
in
Irmin.Type.map ~pre_hash v_t (fun x -> ref x) (fun x -> !x)
end
(* Binary representation. Used in two modes:
- with [key]s as pointers to child values, when encoding values to add
to the underlying store (or decoding values read from the store) –
interoperable with the [Compress]-ed binary representation.
- with either [key]s or [hash]es as pointers to child values, when
pre-computing the hash of a node with children that haven't yet been
written to the store. *)
module Bin = struct
open T
(** Distinguishes between the two possible modes of binary value. *)
type _ mode = Ptr_key : key mode | Ptr_any : Val_ref.t mode
type 'vref with_index = { index : int; vref : 'vref } [@@deriving irmin]
type 'vref tree = {
depth : int;
length : int;
entries : 'vref with_index list;
}
[@@deriving irmin]
type 'vref v = Values of (step * value) list | Tree of 'vref tree
[@@deriving irmin ~pre_hash]
module V =
Irmin.Hash.Typed
(H)
(struct
type t = Val_ref.t v [@@deriving irmin]
end)
type 'vref t = { hash : H.t Lazy.t; root : bool; v : 'vref v }
let t : type vref. vref Irmin.Type.t -> vref t Irmin.Type.t =
fun vref_t ->
let open Irmin.Type in
let v_t = v_t vref_t in
let pre_hash_v = pre_hash_v vref_t in
let pre_hash x = pre_hash_v x.v in
record "Bin.t" (fun hash root v -> { hash = Lazy.from_val hash; root; v })
|+ field "hash" H.t (fun t -> Lazy.force t.hash)
|+ field "root" bool (fun t -> t.root)
|+ field "v" v_t (fun t -> t.v)
|> sealr
|> like ~pre_hash
let v ~hash ~root v = { hash; root; v }
let hash t = Lazy.force t.hash
let depth t =
match t.v with
| Values _ -> if t.root then Some 0 else None
| Tree t -> Some t.depth
end
(* Compressed binary representation *)
module Compress = struct
open T
type dict_key = int [@@deriving irmin]
type pack_offset = int63 [@@deriving irmin]
type name = Indirect of dict_key | Direct of step
type address = Offset of pack_offset | Hash of H.t [@@deriving irmin]
type ptr = { index : int; hash : address } [@@deriving irmin]
type tree = { depth : int; length : int; entries : ptr list }
[@@deriving irmin]
type value =
| Contents of name * address * metadata
| Node of name * address
let is_default = T.(equal_metadata Metadata.default)
(* We distribute products over sums in the type representation of [value]
in order to pack many possible cases into a single tag character in the
encoded representation.
- whether the referenced value is a [Node] or a [Contents] value;
- in the [Contents] case, whether the associated metadata is [default]
(in which case the serialised representation elides it), or if it is
included;
- whether the [name] of the entry is provided inline [Direct], or is
stored in the dict and refernced via a dict key [Indirect];
- whether the [address] of the entry is a pack offset or a hash to be
indexed *)
let[@ocamlformat "disable"] value_t : value Irmin.Type.t =
let module Payload = struct
(* Different payload types that can appear after packed tags: *)
let io = [%typ: dict_key * pack_offset]
let ih = [%typ: dict_key * H.t]
let do_ = [%typ: step * pack_offset]
let dh = [%typ: step * H.t]
(* As above but for contents values with non-default metadata: *)
let x_io = [%typ: dict_key * pack_offset * metadata]
let x_ih = [%typ: dict_key * H.t * metadata]
let x_do = [%typ: step * pack_offset * metadata]
let x_dh = [%typ: step * H.t * metadata]
end in
let open Irmin.Type in
variant "Compress.value"
(fun
(* The ordering of these arguments determines which tags are assigned
to the cases, so should not be changed: *)
contents_io contents_x_io node_io contents_ih contents_x_ih node_ih
contents_do contents_x_do node_do contents_dh contents_x_dh node_dh
-> function
| Node (Indirect n, Offset o) -> node_io (n, o)
| Node (Indirect n, Hash h) -> node_ih (n, h)
| Node (Direct n, Offset o) -> node_do (n, o)
| Node (Direct n, Hash h) -> node_dh (n, h)
| Contents (Indirect n, Offset o, m) -> if is_default m then contents_io (n, o) else contents_x_io (n, o, m)
| Contents (Indirect n, Hash h, m) -> if is_default m then contents_ih (n, h) else contents_x_ih (n, h, m)
| Contents (Direct n, Offset o, m) -> if is_default m then contents_do (n, o) else contents_x_do (n, o, m)
| Contents (Direct n, Hash h, m) -> if is_default m then contents_dh (n, h) else contents_x_dh (n, h, m))
|~ case1 "contents-io" Payload.io (fun (n, o) -> Contents (Indirect n, Offset o, Metadata.default))
|~ case1 "contents-x-io" Payload.x_io (fun (n, i, m) -> Contents (Indirect n, Offset i, m))
|~ case1 "node-io" Payload.io (fun (n, i) -> Node (Indirect n, Offset i))
|~ case1 "contents-ih" Payload.ih (fun (n, h) -> Contents (Indirect n, Hash h, Metadata.default))
|~ case1 "contents-x-ih" Payload.x_ih (fun (n, h, m) -> Contents (Indirect n, Hash h, m))
|~ case1 "node-ih" Payload.ih (fun (n, h) -> Node (Indirect n, Hash h))
|~ case1 "contents-do" Payload.do_ (fun (n, i) -> Contents (Direct n, Offset i, Metadata.default))
|~ case1 "contents-x-do" Payload.x_do (fun (n, i, m) -> Contents (Direct n, Offset i, m))
|~ case1 "node-do" Payload.do_ (fun (n, i) -> Node (Direct n, Offset i))
|~ case1 "contents-dh" Payload.dh (fun (n, i) -> Contents (Direct n, Hash i, Metadata.default))
|~ case1 "contents-x-dh" Payload.x_dh (fun (n, i, m) -> Contents (Direct n, Hash i, m))
|~ case1 "node-dd" Payload.dh (fun (n, i) -> Node (Direct n, Hash i))
|> sealv
type v = Values of value list | Tree of tree
[@@deriving irmin ~encode_bin ~decode_bin ~size_of]
let dynamic_size_of_v_encoding =
match Irmin.Type.Size.of_encoding v_t with
| Irmin.Type.Size.Dynamic f -> f
| _ -> assert false
type kind = Pack_value.Kind.t
[@@deriving irmin ~encode_bin ~decode_bin ~size_of]
type nonrec int = int [@@deriving irmin ~encode_bin ~decode_bin]
let no_length = 0
let is_real_length length = not (length = 0)
type v1 = { mutable length : int; v : v } [@@deriving irmin]
(** [length] is the length of the binary encoding of [v]. It is not known
right away. [length] is [no_length] when it isn't known. Calling
[encode_bin] or [size_of] will make [length] known. *)
(** [tagged_v] sits between [v] and [t]. It is a variant with the header
binary encoded as the magic. *)
type tagged_v =
| V0_stable of v
| V0_unstable of v
| V1_root of v1
| V1_nonroot of v1
[@@deriving irmin]
let encode_bin_tv_staggered ({ v; _ } as tv) kind f =
match size_of_v v with
| Some length ->
tv.length <- length;
encode_bin_kind kind f;
encode_bin_int length f;
encode_bin_v v f
| None ->
let buf = Buffer.create 1024 in
encode_bin_v v (Buffer.add_string buf);
let length = Buffer.length buf in
tv.length <- length;
encode_bin_kind kind f;
encode_bin_int length f;
f (Buffer.contents buf)
let encode_bin_tv tv f =
match tv with
| V0_stable _ -> assert false
| V0_unstable _ -> assert false
| V1_root { length; v } when is_real_length length ->
encode_bin_kind Pack_value.Kind.Inode_v2_root f;
encode_bin_int length f;
encode_bin_v v f
| V1_nonroot { length; v } when is_real_length length ->
encode_bin_kind Pack_value.Kind.Inode_v2_nonroot f;
encode_bin_int length f;
encode_bin_v v f
| V1_root tv -> encode_bin_tv_staggered tv Pack_value.Kind.Inode_v2_root f
| V1_nonroot tv ->
encode_bin_tv_staggered tv Pack_value.Kind.Inode_v2_nonroot f
let decode_bin_tv s off =
let kind = decode_bin_kind s off in
match kind with
| Pack_value.Kind.Inode_v1_unstable ->
let v = decode_bin_v s off in
V0_unstable v
| Inode_v1_stable ->
let v = decode_bin_v s off in
V0_stable v
| Inode_v2_root ->
let length = decode_bin_int s off in
assert (is_real_length length);
let v = decode_bin_v s off in
V1_root { length; v }
| Inode_v2_nonroot ->
let length = decode_bin_int s off in
assert (is_real_length length);
let v = decode_bin_v s off in
V1_nonroot { length; v }
| Commit_v1 | Commit_v2 -> assert false
| Contents -> assert false
| Dangling_parent_commit -> assert false
let size_of_tv =
let of_encoding s off =
let offref = ref off in
let kind = decode_bin_kind s offref in
let magic_len = 1 in
match kind with
| Pack_value.Kind.Inode_v1_unstable | Inode_v1_stable ->
let vlen = dynamic_size_of_v_encoding s !offref in
magic_len + vlen
| Inode_v2_root | Inode_v2_nonroot ->
let before = !offref in
let vlen = decode_bin_int s offref in
let after = !offref in
let lenlen = after - before in
magic_len + lenlen + vlen
| Commit_v1 | Commit_v2 | Contents -> assert false
| Dangling_parent_commit -> assert false
in
Irmin.Type.Size.custom_dynamic ~of_encoding ()
let tagged_v_t =
Irmin.Type.like ~bin:(encode_bin_tv, decode_bin_tv, size_of_tv) tagged_v_t
type t = { hash : H.t; tv : tagged_v } [@@deriving irmin]
let v ~root ~hash v =
let length = no_length in
let tv =
if root then V1_root { v; length } else V1_nonroot { v; length }
in
{ hash; tv }
(** The rule to determine the [is_root] property of a v0 [Value] is a bit
convoluted, it relies on the fact that back then the following property
was enforced: [Conf.stable_hash > Conf.entries].
When [t] is of tag [Values], then [t] is root iff [t] is stable.
When [t] is stable, then [t] is a root, because:
- Only 2 functions produce stable inodes: [stabilize] and [empty].
- Only the roots are output of [stabilize].
- An empty map can only be located at the root.
When [t] is a root of tag [Value], then [t] is stable, because:
- All the roots are output of [stabilize].
- When an unstable inode enters [stabilize], it becomes stable if it has
at most [Conf.stable_hash] leaves.
- A [Value] has at most [Conf.stable_hash] leaves because
[Conf.entries <= Conf.stable_hash] is enforced. *)
let is_root = function
| { tv = V0_stable (Values _); _ } -> true
| { tv = V0_unstable (Values _); _ } -> false
| { tv = V0_stable (Tree { depth; _ }); _ }
| { tv = V0_unstable (Tree { depth; _ }); _ } ->
depth = 0
| { tv = V1_root _; _ } -> true
| { tv = V1_nonroot _; _ } -> false
end
(** [Val_impl] defines the recursive structure of inodes.
{3 Inode Layout}
{4 Layout Types}
The layout ['a layout] associated to an inode ['a t] defines certain
properties of the inode:
- When [Total], the inode is self contained and immutable.
- When [Partial], chunks of the inode might be missing but they can be
fetched from the backend when needed using the available [find] function
stored in the layout. Mutable pointers act as cache.
- When [Truncated], chunks of the inode might be missing. Those chunks are
unreachable because the pointer to the backend is missing. The inode is
immutable.
{4 Layout Instantiation}
The layout of an inode is determined from the module [Val], it depends on
the way the inode was constructed:
- When [Total], it originates from [Val.v] or [Val.empty].
- When [Partial], it originates from [Val.of_bin], which is only used by
[Inode.find].
- When [Truncated], it either originates from an [Irmin.Type]
deserialisation or from a proof.
Almost all other functions in [Val_impl] are polymorphic regarding the
layout of the manipulated inode.
{4 Details on the [Truncated] Layout}
The [Truncated] layout is identical to [Partial] except for the missing
[find] function.
On the one hand, when creating the root of a [Truncated] inode, the
pointers to children inodes - if any - are set to the [Broken] tag,
meaning that we know the hash to such children but we will have no way to
load them in the future. On the other hand, when adding child to a
[Truncated] inode, there is no such problem, the pointer is then set to
the [Intact] tag.
A tree of inode only made of [Intact] tags is similar to a [Total] layout.
As of Irmin 2.4 (February 2022), inode deserialisation using Repr happens
in [irmin/slice.ml] and [irmin/sync_ext.ml], and maybe some other places.
At some point we might want to forbid such deserialisations and instead
use something in the flavour of [Val.of_bin] to create [Partial] inodes.
{3 Topmost Inode Ancestor}
[Val_impl.t] is a recursive type, it is labelled with a [depth] integer
that indicates the recursion depth. An inode with [depth = 0] corresponds
to the root of a directory, its hash is the hash of the directory.
A [Val.t] points to the topmost [Val_impl.t] of an inode tree. In most
scenarios, that topmost inode has [depth = 0], but it is also legal for
the topmost inode to be an intermediate inode, i.e. with [depth > 0].
The only way for an inode tree to have an intermediate inode as root is to
fetch it from the backend by calling [Make_ext.find], using the hash of
that inode.
Write-only operations are not permitted when the root is an intermediate
inode. *)
module Val_impl = struct
open T
type _ layout =
| Total : total_ptr layout
| Partial : find -> partial_ptr layout
| Truncated : truncated_ptr layout
and find = expected_depth:int -> key -> partial_ptr t option
and partial_ptr_target =
| Dirty of partial_ptr t
| Lazy of key
| Lazy_loaded of partial_ptr t
(** A partial pointer differentiates the [Dirty] and [Lazy_loaded]
cases in order to remember that only the latter should be
collected when [clear] is called.
The child in [Lazy_loaded] can only emanate from the disk. It can
be savely collected on [clear].
The child in [Dirty] can only emanate from a user modification,
e.g. through the [add] or [to_concrete] functions. It shouldn't be
collected on [clear] because it will be needed for [save]. *)
and partial_ptr = { mutable target : partial_ptr_target }
and total_ptr = Total_ptr of total_ptr t [@@unboxed]
and truncated_ptr =
| Broken of Val_ref.t
(** Initially [Hash.t], then set to [Key.t] when we try to save the
parent and successfully index the hash. *)
| Intact of truncated_ptr t
and 'ptr tree = { depth : int; length : int; entries : 'ptr option array }
and 'ptr v = Values of value StepMap.t | Tree of 'ptr tree
and 'ptr t = {
root : bool;
v : 'ptr v;
v_ref : Val_ref.t;
(** Represents what is known about [v]'s presence in a corresponding
store. Will be a [hash] if [v] is purely in-memory, and a [key] if
[v] has been written to / loaded from a store. *)
}
module Ptr = struct
let val_ref : type ptr. ptr layout -> ptr -> Val_ref.t = function
| Total -> fun (Total_ptr ptr) -> ptr.v_ref
| Partial _ -> (
fun { target } ->
match target with
| Lazy key -> Val_ref.of_key key
| Lazy_loaded { v_ref; _ } | Dirty { v_ref; _ } -> v_ref)
| Truncated -> ( function Broken v -> v | Intact ptr -> ptr.v_ref)
let key_exn : type ptr. ptr layout -> ptr -> key = function
| Total -> fun (Total_ptr ptr) -> Val_ref.to_key_exn ptr.v_ref
| Partial _ -> (
fun { target } ->
match target with
| Lazy key -> key
| Lazy_loaded { v_ref; _ } | Dirty { v_ref; _ } ->
Val_ref.to_key_exn v_ref)
| Truncated -> (
function
| Broken h -> Val_ref.to_key_exn h
| Intact ptr -> Val_ref.to_key_exn ptr.v_ref)
(** [force = false] will cause [target] to raise an exception when
encountering a tag [Lazy] inside a [Partial] inode. This feature is
used by [to_concrete] to make shallow the non-loaded inode branches. *)
let target :
type ptr.
expected_depth:int ->
cache:bool ->
force:bool ->
string ->
ptr layout ->
ptr ->
ptr t =
fun ~expected_depth ~cache ~force context layout ->
match layout with
| Total -> fun (Total_ptr t) -> t
| Partial find -> (
function
| { target = Dirty entry } | { target = Lazy_loaded entry } ->
(* [target] is already cached. [cache] is only concerned with
new cache entries, not the older ones for which the irmin
users can discard using [clear]. *)
entry
| { target = Lazy key } as t -> (
if not force then raise_dangling_hash context (Key.to_hash key);
match find ~expected_depth key with
| None -> Fmt.failwith "%a: unknown key" pp_key key
| Some x ->
if cache then t.target <- Lazy_loaded x;
x))
| Truncated -> (
function
| Intact entry -> entry
| Broken vref ->
let h = Val_ref.to_hash vref in
raise_dangling_hash context h)
let of_target : type ptr. ptr layout -> ptr t -> ptr = function
| Total -> fun target -> Total_ptr target
| Partial _ -> fun target -> { target = Dirty target }
| Truncated -> fun target -> Intact target
let of_key : type ptr. ptr layout -> key -> ptr = function
| Total -> assert false
| Partial _ -> fun key -> { target = Lazy key }
| Truncated -> fun key -> Broken (Val_ref.of_key key)
type ('input, 'output) cps = { f : 'r. 'input -> ('output -> 'r) -> 'r }
[@@ocaml.unboxed]
let save :
type ptr.
broken:(hash, key) cps ->
save_dirty:(ptr t, key) cps ->
clear:bool ->
ptr layout ->
ptr ->
unit =
fun ~broken ~save_dirty ~clear -> function
(* Invariant: after returning, we can recover the key from the saved
pointer (i.e. [key_exn] does not raise an exception). This is necessary
in order to be able to serialise a parent inode (for export) after
having saved its children. *)
| Total ->
fun (Total_ptr entry) ->
save_dirty.f entry (fun key ->
Val_ref.promote_exn entry.v_ref key)
| Partial _ -> (
function
| { target = Dirty entry } as box ->
save_dirty.f entry (fun key ->
if clear then box.target <- Lazy key
else (
box.target <- Lazy_loaded entry;
Val_ref.promote_exn entry.v_ref key))
| { target = Lazy_loaded entry } as box ->
(* In this case, [entry.v_ref] is a [Hash h] such that [mem t
(index t h) = true]. We "save" the entry in order to trigger
the [index] lookup and recover the key, in order to meet the
return invariant above.
TODO: refactor this case to be more precise. *)
save_dirty.f entry (fun key ->
if clear then box.target <- Lazy key)
| { target = Lazy _ } -> ())
| Truncated -> (
function
(* TODO: this branch is currently untested: we never attempt to
save a truncated node as part of the unit tests. *)
| Intact entry ->
save_dirty.f entry (fun key ->
Val_ref.promote_exn entry.v_ref key)
| Broken vref ->
if not (Val_ref.is_key vref) then
broken.f (Val_ref.to_hash vref) (fun key ->
Val_ref.promote_exn vref key))
let clear :
type ptr.
iter_dirty:(ptr layout -> ptr t -> unit) -> ptr layout -> ptr -> unit
=
fun ~iter_dirty layout ptr ->
match layout with
| Partial _ -> (
match ptr with
| { target = Lazy _ } -> ()
| { target = Dirty ptr } -> iter_dirty layout ptr
| { target = Lazy_loaded ptr } as box ->
(* Since a [Lazy_loaded] used to be a [Lazy], the key is always
available. *)
let key = Val_ref.to_key_exn ptr.v_ref in
box.target <- Lazy key)
| Total | Truncated -> ()
end
let pred layout t =
match t.v with
| Tree i ->
let key_of_ptr = Ptr.key_exn layout in
Array.fold_left
(fun acc -> function
| None -> acc
| Some ptr -> (None, `Inode (key_of_ptr ptr)) :: acc)
[] i.entries
| Values l ->
StepMap.fold
(fun s v acc ->
let v =
match v with
| `Node _ as k -> (Some s, k)
| `Contents (k, _) -> (Some s, `Contents k)
in
v :: acc)
l []
let length_of_v = function
| Values vs -> StepMap.cardinal vs
| Tree vs -> vs.length
let length t = length_of_v t.v
let rec clear layout t =
match t.v with
| Tree i ->
Array.iter
(Option.iter (Ptr.clear ~iter_dirty:clear layout))
i.entries
| Values _ -> ()
let nb_children t =
match t.v with
| Tree i ->
Array.fold_left
(fun i -> function None -> i | Some _ -> i + 1)
0 i.entries
| Values vs -> StepMap.cardinal vs
type cont = off:int -> len:int -> (step * value) Seq.node
let rec seq_tree layout bucket_seq ~depth ~cache : cont -> cont =
fun k ~off ~len ->
assert (off >= 0);
assert (len > 0);
match bucket_seq () with
| Seq.Nil -> k ~off ~len
| Seq.Cons (None, rest) -> seq_tree layout rest ~depth ~cache k ~off ~len
| Seq.Cons (Some i, rest) ->
let trg =
let expected_depth = depth + 1 in
Ptr.target ~expected_depth ~cache ~force:true "seq_tree" layout i
in
let trg_len = length trg in
if off - trg_len >= 0 then
(* Skip a branch of the inode tree in case the user asked for a
specific starting offset.
Without this branch the algorithm would keep the same semantic
because [seq_value] would handles the pagination value by value
instead. *)
let off = off - trg_len in
seq_tree layout rest ~depth ~cache k ~off ~len
else
seq_v layout trg.v ~cache
(seq_tree layout rest ~depth ~cache k)
~off ~len
and seq_values layout value_seq : cont -> cont =
fun k ~off ~len ->
assert (off >= 0);
assert (len > 0);
match value_seq () with
| Seq.Nil -> k ~off ~len
| Cons (x, rest) ->
if off = 0 then
let len = len - 1 in
if len = 0 then
(* Yield the current value and skip the rest of the inode tree in
case the user asked for a specific length. *)
Seq.Cons (x, Seq.empty)
else Seq.Cons (x, fun () -> seq_values layout rest k ~off ~len)
else
(* Skip one value in case the user asked for a specific starting
offset. *)
let off = off - 1 in
seq_values layout rest k ~off ~len
and seq_v layout v ~cache : cont -> cont =
fun k ~off ~len ->
assert (off >= 0);
assert (len > 0);
match v with
| Tree t ->
let depth = t.depth in
seq_tree layout (Array.to_seq t.entries) ~depth ~cache k ~off ~len
| Values vs -> seq_values layout (StepMap.to_seq vs) k ~off ~len
let list_v layout v ~cache k ~off ~len =
match v with
| Tree _ ->
let s () = seq_v layout v ~cache k ~off ~len in
List.of_seq s
| Values vs ->
if off = 0 && len = Int.max_int then StepMap.bindings vs
else
let seq () = seq_values layout (StepMap.to_seq vs) k ~off ~len in
List.of_seq seq
let empty_continuation : cont = fun ~off:_ ~len:_ -> Seq.Nil
let seq layout ?offset:(off = 0) ?length:(len = Int.max_int) ?(cache = true)
t : (step * value) Seq.t =
if off < 0 then invalid_arg "Invalid pagination offset";
if len < 0 then invalid_arg "Invalid pagination length";
if len = 0 then Seq.empty
else fun () -> seq_v layout t.v ~cache empty_continuation ~off ~len
let list layout ?offset:(off = 0) ?length:(len = Int.max_int)
?(cache = true) t : (step * value) list =
if off < 0 then invalid_arg "Invalid pagination offset";
if len < 0 then invalid_arg "Invalid pagination length";
if len = 0 then []
else list_v layout t.v ~cache empty_continuation ~off ~len
let seq_tree layout ?(cache = true) i : (step * value) Seq.t =
let off = 0 in
let len = Int.max_int in
fun () -> seq_v layout (Tree i) ~cache empty_continuation ~off ~len
let seq_v layout ?(cache = true) v : (step * value) Seq.t =
let off = 0 in
let len = Int.max_int in
fun () -> seq_v layout v ~cache empty_continuation ~off ~len
let to_bin_v :
type ptr vref. ptr layout -> vref Bin.mode -> ptr v -> vref Bin.v =
fun layout mode node ->
Stats.incr_inode_to_binv ();
match node with
| Values vs ->
let vs = StepMap.bindings vs in
Bin.Values vs
| Tree t ->
let vref_of_ptr : ptr -> vref =
match mode with
| Bin.Ptr_any -> Ptr.val_ref layout
| Bin.Ptr_key -> Ptr.key_exn layout
in
let _, entries =
Array.fold_left
(fun (i, acc) -> function
| None -> (i + 1, acc)
| Some ptr ->
let vref = vref_of_ptr ptr in
(i + 1, { Bin.index = i; vref } :: acc))
(0, []) t.entries
in
let entries = List.rev entries in
Bin.Tree { depth = t.depth; length = t.length; entries }
let is_root t = t.root
let is_stable t = should_be_stable ~length:(length t) ~root:(is_root t)
let to_bin layout mode t =
let v = to_bin_v layout mode t.v in
Bin.v ~root:(is_root t) ~hash:(Val_ref.to_lazy_hash t.v_ref) v
type len = [ `Eq of int | `Ge of int ] [@@deriving irmin]
module Concrete = struct
type kinded_key =
| Contents of contents_key
| Contents_x of metadata * contents_key
| Node of node_key
[@@deriving irmin]
type entry = { name : step; key : kinded_key } [@@deriving irmin]
type 'a pointer = { index : int; pointer : hash; tree : 'a }
[@@deriving irmin]
type 'a tree = { depth : int; length : int; pointers : 'a pointer list }
[@@deriving irmin]
type t = Tree of t tree | Values of entry list | Blinded
[@@deriving irmin]
let to_entry (name, v) =
match v with
| `Contents (contents_key, m) ->
if T.equal_metadata m Metadata.default then
{ name; key = Contents contents_key }
else { name; key = Contents_x (m, contents_key) }
| `Node node_key -> { name; key = Node node_key }
let of_entry e =
( e.name,
match e.key with
| Contents key -> `Contents (key, Metadata.default)
| Contents_x (m, key) -> `Contents (key, m)
| Node key -> `Node key )
type error =
[ `Invalid_hash of hash * hash * t
| `Invalid_depth of int * int * t
| `Invalid_length of len * int * t
| `Duplicated_entries of t
| `Duplicated_pointers of t
| `Unsorted_entries of t
| `Unsorted_pointers of t
| `Blinded_root
| `Too_large_values of t
| `Empty ]
[@@deriving irmin]
let rec length = function
| Values l -> `Eq (List.length l)