package irmin-pack

  1. Overview
  2. Docs
Legend:
Page
Library
Module
Module type
Parameter
Class
Class type
Source

Source file ext.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
(*
 * Copyright (c) 2018-2022 Tarides <contact@tarides.com>
 *
 * 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

module Maker (Config : Conf.S) = struct
  type endpoint = unit

  include Pack_key.Store_spec

  module Make (Schema : Irmin.Schema.Extended) = struct
    open struct
      module P = Schema.Path
      module M = Schema.Metadata
      module C = Schema.Contents
      module B = Schema.Branch
    end

    module H = Schema.Hash
    module Index = Pack_index.Make (H)
    module Io = Io.Unix
    module Async = Async.Unix
    module Errs = Io_errors.Make (Io)
    module Control = Control_file.Make (Io)
    module Aof = Append_only_file.Make (Io)
    module File_manager = File_manager.Make (Control) (Aof) (Aof) (Index) (Errs)
    module Dict = Dict.Make (File_manager)
    module Dispatcher = Dispatcher.Make (File_manager)
    module XKey = Pack_key.Make (H)

    module X = struct
      module Hash = H

      type 'a value = { hash : H.t; kind : Pack_value.Kind.t; v : 'a }
      [@@deriving irmin]

      module Contents = struct
        module Pack_value = Pack_value.Of_contents (Config) (H) (XKey) (C)

        module CA =
          Pack_store.Make (File_manager) (Dict) (Dispatcher) (H) (Pack_value)
            (Errs)

        include Irmin.Contents.Store_indexable (CA) (H) (C)
      end

      module Node = struct
        module Value = Schema.Node (XKey) (XKey)

        module CA = struct
          module Inter =
            Irmin_pack.Inode.Make_internal (Config) (H) (XKey) (Value)

          module Pack' =
            Pack_store.Make (File_manager) (Dict) (Dispatcher) (H) (Inter.Raw)
              (Errs)

          include Inode.Make_persistent (H) (Value) (Inter) (Pack')
        end

        include
          Irmin.Node.Generic_key.Store (Contents) (CA) (H) (CA.Val) (M) (P)
      end

      module Node_portable = Node.CA.Val.Portable

      module Schema = struct
        include Schema
        module Node = Node
      end

      module Commit = struct
        module Value = struct
          include Schema.Commit (Node.Key) (XKey)
          module Info = Schema.Info

          type hash = Hash.t [@@deriving irmin]
        end

        module Pack_value = Pack_value.Of_commit (H) (XKey) (Value)

        module CA =
          Pack_store.Make (File_manager) (Dict) (Dispatcher) (H) (Pack_value)
            (Errs)

        include
          Irmin.Commit.Generic_key.Store (Schema.Info) (Node) (CA) (H) (Value)
      end

      module Commit_portable = struct
        module Hash_key = Irmin.Key.Of_hash (Hash)
        include Schema.Commit (Hash_key) (Hash_key)

        let of_commit : Commit.Value.t -> t =
         fun t ->
          let info = Commit.Value.info t
          and node = Commit.Value.node t |> XKey.to_hash
          and parents = Commit.Value.parents t |> List.map XKey.to_hash in
          v ~info ~node ~parents

        module Info = Schema.Info

        type hash = Hash.t [@@deriving irmin]
      end

      module Branch = struct
        module Key = B
        module Val = XKey
        module AW = Atomic_write.Make_persistent (Key) (Val)
        include Atomic_write.Closeable (AW)

        let v ?fresh ?readonly path =
          AW.v ?fresh ?readonly path >|= make_closeable
      end

      module Slice = Irmin.Backend.Slice.Make (Contents) (Node) (Commit)
      module Remote = Irmin.Backend.Remote.None (Commit.Key) (B)

      module Gc = Gc.Make (struct
        module Fm = File_manager
        module Errs = Errs
        module Dict = Dict
        module Dispatcher = Dispatcher
        module Hash = Schema.Hash
        module Node_value = Node.CA.Inter.Val
        module Node_store = Node.CA
        module Commit_value = Commit.Value
        module Commit_store = Commit.CA

        type hash = Node_value.hash
        type key = Node_value.node_key [@@deriving irmin]
      end)

      type gc_stats = {
        duration : float;
        finalisation_duration : float;
        read_gc_output_duration : float;
        transfer_latest_newies_duration : float;
        swap_duration : float;
        unlink_duration : float;
      }
      [@@deriving irmin ~pp]

      type gc = {
        next_generation : int;
        task : Async.t;
        unlink : bool;
        offset : int63;
        elapsed : unit -> float;
        resolver : (gc_stats, Errs.t) result Lwt.u;
        promise : (gc_stats, Errs.t) result Lwt.t;
        use_auto_finalisation : bool;
      }

      module Repo = struct
        type t = {
          config : Irmin.Backend.Conf.t;
          contents : read Contents.CA.t;
          node : read Node.CA.t;
          commit : read Commit.CA.t;
          branch : Branch.t;
          fm : File_manager.t;
          dict : Dict.t;
          dispatcher : Dispatcher.t;
          mutable during_batch : bool;
          mutable running_gc : gc option;
        }

        let pp_key = Irmin.Type.pp XKey.t
        let contents_t t : 'a Contents.t = t.contents
        let node_t t : 'a Node.t = (contents_t t, t.node)
        let commit_t t : 'a Commit.t = (node_t t, t.commit)
        let branch_t t = t.branch
        let config t = t.config

        let v config =
          let root = Irmin_pack.Conf.root config in
          let fm =
            let readonly = Irmin_pack.Conf.readonly config in
            if readonly then File_manager.open_ro config |> Errs.raise_if_error
            else
              let fresh = Irmin_pack.Conf.fresh config in
              match (Io.classify_path root, fresh) with
              | `No_such_file_or_directory, _ ->
                  File_manager.create_rw ~overwrite:false config
                  |> Errs.raise_if_error
              | `Directory, true ->
                  File_manager.create_rw ~overwrite:true config
                  |> Errs.raise_if_error
              | `Directory, false ->
                  File_manager.open_rw config |> Errs.raise_if_error
              | (`File | `Other), _ -> Errs.raise_error (`Not_a_directory root)
          in
          let dict = Dict.v fm |> Errs.raise_if_error in
          let dispatcher = Dispatcher.v ~root fm |> Errs.raise_if_error in
          let contents = Contents.CA.v ~config ~fm ~dict ~dispatcher in
          let node = Node.CA.v ~config ~fm ~dict ~dispatcher in
          let commit = Commit.CA.v ~config ~fm ~dict ~dispatcher in
          let+ branch =
            let root = Conf.root config in
            let fresh = Conf.fresh config in
            let readonly = Conf.readonly config in
            let path = Irmin_pack.Layout.V3.branch ~root in
            Branch.v ~fresh ~readonly path
          in
          let during_batch = false in
          let running_gc = None in
          {
            config;
            contents;
            node;
            commit;
            branch;
            fm;
            dict;
            during_batch;
            running_gc;
            dispatcher;
          }

        let close t =
          (* Step 1 - Kill the gc process if it is running *)
          let () =
            match t.running_gc with
            | Some { task; _ } ->
                Async.cancel task;
                t.running_gc <- None
            | None -> ()
          in
          (* Step 2 - Close the files *)
          let () = File_manager.close t.fm |> Errs.raise_if_error in
          Branch.close t.branch >>= fun () ->
          (* Step 3 - Close the in-memory abstractions *)
          Dict.close t.dict;
          Contents.CA.close (contents_t t) >>= fun () ->
          Node.CA.close (snd (node_t t)) >>= fun () ->
          Commit.CA.close (snd (commit_t t))

        let flush_with_hook ~hook t =
          File_manager.flush ~hook t.fm |> Errs.raise_if_error

        let reload_with_hook ~hook t =
          File_manager.reload ~hook t.fm |> Errs.raise_if_error

        let flush t = File_manager.flush ?hook:None t.fm |> Errs.raise_if_error
        let reload t = File_manager.reload t.fm |> Errs.raise_if_error

        module Gc = struct
          let unlink_result_file ~root ~generation =
            let result_file =
              Irmin_pack.Layout.V3.gc_result ~root ~generation
            in
            match Io.unlink result_file with
            | Ok () -> ()
            | Error (`Sys_error msg as err) ->
                if msg <> Fmt.str "%s: No such file or directory" result_file
                then
                  [%log.warn
                    "Unlinking temporary files from previous failed gc. Failed \
                     with error %a"
                    Errs.pp err]

          let start ~unlink ~use_auto_finalisation t commit_key =
            let open Result_syntax in
            [%log.info "GC: Starting on %a" pp_key commit_key];
            let* () =
              if t.during_batch then Error `Gc_forbidden_during_batch else Ok ()
            in
            let* commit_key =
              let state : _ Irmin_pack.Pack_key.state =
                Irmin_pack.Pack_key.inspect commit_key
              in
              match state with
              | Direct _ -> Ok commit_key
              | Indexed h -> (
                  match Commit.CA.index_direct_with_kind t.commit h with
                  | None ->
                      Error
                        (`Commit_key_is_dangling
                          (Irmin.Type.to_string XKey.t commit_key))
                  | Some (k, _kind) -> Ok k)
            in
            let offset =
              let state : _ Irmin_pack.Pack_key.state =
                Irmin_pack.Pack_key.inspect commit_key
              in
              match state with
              | Direct x -> x.offset
              | Indexed _ -> assert false
            in
            let root = Conf.root t.config in
            let* () =
              if not (File_manager.gc_allowed t.fm) then Error `Gc_disallowed
              else Ok ()
            in
            let current_generation = File_manager.generation t.fm in
            let next_generation = current_generation + 1 in
            (* Unlink next gc's result file, in case it is on disk, for instance
               after a failed gc. *)
            unlink_result_file ~root ~generation:next_generation;
            let task =
              Async.async (fun () ->
                  let (_ : int63) =
                    Gc.run_and_output_result root commit_key
                      ~generation:next_generation
                  in
                  ())
            in
            let elapsed =
              let c0 = Mtime_clock.counter () in
              fun () -> Mtime_clock.count c0 |> Mtime.Span.to_s
            in
            let promise, resolver = Lwt.wait () in
            t.running_gc <-
              Some
                {
                  next_generation;
                  task;
                  unlink;
                  offset;
                  elapsed;
                  promise;
                  resolver;
                  use_auto_finalisation;
                };
            Ok ()

          let open_new_suffix ~root ~generation ~end_offset =
            let open Result_syntax in
            let path = Irmin_pack.Layout.V3.suffix ~root ~generation in
            (* As the new suffix is necessarily in V3, the dead_header_size is
               0. *)
            let dead_header_size = 0 in
            let auto_flush_threshold = 1_000_000 in
            let auto_flush_callback x = Aof.flush x |> Errs.raise_if_error in
            let* suffix =
              Aof.open_rw ~path ~end_offset ~dead_header_size
                ~auto_flush_callback ~auto_flush_threshold
            in
            Ok suffix

          let transfer_latest_newies ~generation ~right_start_offset
              ~copy_end_offset ~root t =
            [%log.debug "Gc in main: transfer latest newies"];
            let open Result_syntax in
            let open Int63.Syntax in
            let old_end_offset = Dispatcher.end_offset t.dispatcher in
            let remaining = old_end_offset - copy_end_offset in
            (* When opening the suffix in append_only we need to provide a
               (real) suffix offset, computed from the global ones. *)
            let suffix_end_offset = copy_end_offset - right_start_offset in
            let* new_suffix =
              open_new_suffix ~root ~generation ~end_offset:suffix_end_offset
            in
            Errors.finalise (fun _ ->
                Aof.close new_suffix
                |> Errs.log_if_error "GC: Close suffix after copy latest newies")
            @@ fun () ->
            let buffer = Bytes.create 8192 in
            let read_exn = Dispatcher.read_exn t.dispatcher in
            let append_exn = Aof.append_exn new_suffix in
            let flush_and_raise () =
              Aof.flush new_suffix |> Errs.raise_if_error
            in
            let* () =
              Errs.catch (fun () ->
                  Gc.transfer_append_exn ~read_exn ~append_exn
                    ~off:copy_end_offset ~len:remaining buffer;
                  flush_and_raise ())
            in
            Ok old_end_offset

          let swap_and_purge ~generation ~right_start_offset ~right_end_offset t
              =
            let open Result_syntax in
            let c0 = Mtime_clock.counter () in

            let* () =
              File_manager.swap t.fm ~generation ~right_start_offset
                ~right_end_offset
            in
            let span1 = Mtime_clock.count c0 |> Mtime.Span.to_s in

            (* No need to purge dict here, as it is global to the store. *)
            (* No need to purge index here. It is global too, but some hashes may
               not point to valid offsets anymore. Pack_store will just say that
               such keys are not member of the store. *)
            Contents.CA.purge_lru t.contents;
            Node.CA.purge_lru t.node;
            Commit.CA.purge_lru t.commit;
            let span2 = Mtime_clock.count c0 |> Mtime.Span.to_s in
            [%log.debug
              "Gc swap and purge: %.6fs, %.6fs" span1 (span2 -. span1)];
            [%log.info "GC: end"];
            Ok ()

          let pp_status = Irmin.Type.pp Async.status_t
          let pp_gc_error = Irmin.Type.pp File_manager.read_gc_output_error_t

          let unlink_all ~root ~generation =
            let result =
              let open Result_syntax in
              (* Unlink previous suffix. *)
              let suffix =
                Irmin_pack.Layout.V3.suffix ~root ~generation:(generation - 1)
              in
              let* () = Io.unlink suffix in
              let* () =
                if generation >= 2 then
                  (* Unlink previous prefix. *)
                  let prefix =
                    Irmin_pack.Layout.V3.prefix ~root
                      ~generation:(generation - 1)
                  in
                  let* () = Io.unlink prefix in
                  (* Unlink previous mapping. *)
                  let mapping =
                    Irmin_pack.Layout.V3.mapping ~root
                      ~generation:(generation - 1)
                  in
                  let* () = Io.unlink mapping in
                  Ok ()
                else Ok ()
              in
              (* Unlink current gc's result.*)
              let result = Irmin_pack.Layout.V3.gc_result ~root ~generation in
              Io.unlink result
            in
            match result with
            | Error e ->
                [%log.warn
                  "Unlinking temporary files after gc, failed with error %a"
                    Errs.pp e]
            | Ok () -> ()

          let gc_errors status gc_output =
            let extend_error s = function
              | `Gc_process_error str ->
                  `Gc_process_error (Fmt.str "%s %s" s str)
              | `Corrupted_gc_result_file str ->
                  `Gc_process_died_without_result_file (Fmt.str "%s %s" s str)
            in
            match (status, gc_output) with
            | `Failure s, Error e -> Error (extend_error s e)
            | `Cancelled, Error e -> Error (extend_error "cancelled" e)
            | `Success, Error e -> Error (extend_error "success" e)
            | `Cancelled, Ok _ -> Error (`Gc_process_error "cancelled")
            | `Failure s, Ok _ -> Error (`Gc_process_error s)
            | `Success, Ok _ -> assert false
            | `Running, _ -> assert false

          let finalise ~wait t =
            match t.running_gc with
            | None -> Lwt.return_ok `Idle
            | Some
                { next_generation; task; unlink; offset; elapsed; resolver; _ }
              -> (
                let go status =
                  let start = elapsed () in
                  let s =
                    ref
                      {
                        duration = 0.;
                        finalisation_duration = 0.;
                        read_gc_output_duration = 0.;
                        transfer_latest_newies_duration = 0.;
                        swap_duration = 0.;
                        unlink_duration = 0.;
                      }
                  in
                  let root = Conf.root t.config in
                  let time on_end f =
                    let counter = Mtime_clock.counter () in
                    let res = f () in
                    on_end (Mtime_clock.count counter |> Mtime.Span.to_s);
                    res
                  in

                  let gc_output =
                    time (fun t -> s := { !s with read_gc_output_duration = t })
                    @@ fun () ->
                    File_manager.read_gc_output ~root
                      ~generation:next_generation
                  in

                  let result =
                    let open Result_syntax in
                    match (status, gc_output) with
                    | `Success, Ok copy_end_offset ->
                        let* new_suffix_end_offset =
                          time (fun t ->
                              s :=
                                { !s with transfer_latest_newies_duration = t })
                          @@ fun () ->
                          transfer_latest_newies ~generation:next_generation
                            ~right_start_offset:offset ~copy_end_offset ~root t
                        in
                        let* () =
                          time (fun t -> s := { !s with swap_duration = t })
                          @@ fun () ->
                          swap_and_purge ~generation:next_generation
                            ~right_start_offset:offset
                            ~right_end_offset:new_suffix_end_offset t
                        in
                        (if unlink then
                         time (fun t -> s := { !s with unlink_duration = t })
                         @@ fun () ->
                         unlink_all ~root ~generation:next_generation);

                        let duration = elapsed () in
                        s :=
                          {
                            !s with
                            duration;
                            finalisation_duration = duration -. start;
                          };

                        [%log.debug
                          "Gc ended. %a, newies bytes:%a" pp_gc_stats !s
                            Int63.pp
                            (Int63.sub new_suffix_end_offset copy_end_offset)];
                        let () = Lwt.wakeup_later resolver (Ok !s) in
                        Ok (`Finalised !s)
                    | _ ->
                        let err = gc_errors status gc_output in
                        let () = Lwt.wakeup_later resolver err in
                        err
                  in
                  t.running_gc <- None;
                  Lwt.return result
                in
                if t.during_batch then
                  Lwt.return_error `Gc_forbidden_during_batch
                else
                  match wait with
                  | false -> (
                      match Async.status task with
                      | `Running -> Lwt.return_ok `Running
                      | status -> go status)
                  | true ->
                      let* status = Async.await task in
                      go status)

          let start_or_skip ~unlink ~use_auto_finalisation t commit_key =
            let open Lwt_result.Syntax in
            match t.running_gc with
            | None ->
                let* () =
                  start ~unlink ~use_auto_finalisation t commit_key
                  |> Lwt.return
                in
                Lwt.return_ok true
            | Some _ ->
                [%log.info "Repo is alreadying running GC. Skipping."];
                Lwt.return_ok false

          let start_exn ?(unlink = true) ~use_auto_finalisation t commit_key =
            let* result =
              start_or_skip ~unlink ~use_auto_finalisation t commit_key
            in
            match result with
            | Ok launched -> Lwt.return launched
            | Error e -> Errs.raise_error e

          let finalise_exn ?(wait = false) t =
            let* result = finalise ~wait t in
            match result with
            | Ok waited -> Lwt.return waited
            | Error e -> Errs.raise_error e

          let is_finished t = Option.is_none t.running_gc

          let on_finalise t f =
            match t.running_gc with
            | None -> ()
            | Some x ->
                (* Ignore returned promise since the purpose of this
                   function is to add asynchronous callbacks to the GC
                   process -- this promise binding is an internal
                   implementation detail. This is safe since the callback
                   [f] is attached to [t.running_gc.promise], which is
                   referenced for the lifetime of a GC process. *)
                let _ = Lwt.bind x.promise f in
                ()

          let try_auto_finalise_exn t =
            match t.running_gc with
            | None -> Lwt.return_unit
            | Some gc -> (
                match gc.use_auto_finalisation with
                | false -> Lwt.return_unit
                | true ->
                    let* _ = finalise_exn ~wait:false t in
                    Lwt.return_unit)
        end

        let batch t f =
          [%log.debug "[pack] batch start"];
          let c0 = Mtime_clock.counter () in
          let try_finalise () = Gc.try_auto_finalise_exn t in
          let* _ = try_finalise () in
          t.during_batch <- true;
          let contents = Contents.CA.cast t.contents in
          let node = Node.CA.Pack.cast t.node in
          let commit = Commit.CA.cast t.commit in
          let contents : 'a Contents.t = contents in
          let node : 'a Node.t = (contents, node) in
          let commit : 'a Commit.t = (node, commit) in
          let on_success res =
            let s = Mtime_clock.count c0 |> Mtime.Span.to_s in
            [%log.info "[pack] batch completed in %.6fs" s];
            t.during_batch <- false;
            File_manager.flush t.fm |> Errs.raise_if_error;
            let* _ = try_finalise () in
            Lwt.return res
          in
          let on_fail exn =
            t.during_batch <- false;
            [%log.info
              "[pack] batch failed. calling flush. (%s)"
                (Printexc.to_string exn)];
            let () =
              match File_manager.flush t.fm with
              | Ok () -> ()
              | Error err ->
                  [%log.err
                    "[pack] batch failed and flush failed. Silencing flush \
                     fail. (%a)"
                    Errs.pp err]
            in
            (* Kill gc process in at_exit. *)
            raise exn
          in
          Lwt.try_bind (fun () -> f contents node commit) on_success on_fail
      end
    end

    let integrity_check ?ppf ~auto_repair t =
      let module Checks = Checks.Index (Index) in
      let contents = X.Repo.contents_t t in
      let nodes = X.Repo.node_t t |> snd in
      let commits = X.Repo.commit_t t |> snd in
      let check ~kind ~offset ~length k =
        match kind with
        | `Contents -> X.Contents.CA.integrity_check ~offset ~length k contents
        | `Node -> X.Node.CA.integrity_check ~offset ~length k nodes
        | `Commit -> X.Commit.CA.integrity_check ~offset ~length k commits
      in
      let index = File_manager.index t.fm in
      Checks.integrity_check ?ppf ~auto_repair ~check index

    include Irmin.Of_backend (X)

    let integrity_check_inodes ?heads t =
      [%log.debug "Check integrity for inodes"];
      let counter, (_, progress_nodes, progress_commits) =
        Utils.Object_counter.start ()
      in
      let errors = ref [] in
      let nodes = X.Repo.node_t t |> snd in
      let pred_node repo key =
        Lwt.catch
          (fun () -> Repo.default_pred_node repo key)
          (fun _ ->
            errors := "Error in repo iter" :: !errors;
            Lwt.return [])
      in

      let node k =
        progress_nodes ();
        X.Node.CA.integrity_check_inodes nodes k >|= function
        | Ok () -> ()
        | Error msg -> errors := msg :: !errors
      in
      let commit _ =
        progress_commits ();
        Lwt.return_unit
      in
      let* heads =
        match heads with None -> Repo.heads t | Some m -> Lwt.return m
      in
      let hashes = List.map (fun x -> `Commit (Commit.key x)) heads in
      let+ () =
        Repo.iter ~cache_size:1_000_000 ~min:[] ~max:hashes ~pred_node ~node
          ~commit t
      in
      Utils.Object_counter.finalise counter;
      let pp_commits = Fmt.list ~sep:Fmt.comma Commit.pp_hash in
      if !errors = [] then
        Fmt.kstr (fun x -> Ok (`Msg x)) "Ok for heads %a" pp_commits heads
      else
        Fmt.kstr
          (fun x -> Error (`Msg x))
          "Inconsistent inodes found for heads %a: %a" pp_commits heads
          Fmt.(list ~sep:comma string)
          !errors

    module Stats = struct
      let pp_key = Irmin.Type.pp XKey.t

      let traverse_inodes ~dump_blob_paths_to commit repo =
        let module Stats = Checks.Stats (struct
          type nonrec step = step

          let step_t = step_t

          module Hash = Hash
        end) in
        let t = Stats.v () in
        let pred_node repo k =
          X.Node.find (X.Repo.node_t repo) k >|= function
          | None -> Fmt.failwith "key %a not found" pp_key k
          | Some v ->
              let width = X.Node.Val.length v in
              let nb_children = X.Node.CA.Val.nb_children v in
              let preds = X.Node.CA.Val.pred v in
              let () =
                preds
                |> List.map (function
                     | s, `Contents h -> (s, `Contents (XKey.to_hash h))
                     | s, `Inode h -> (s, `Inode (XKey.to_hash h))
                     | s, `Node h -> (s, `Node (XKey.to_hash h)))
                |> Stats.visit_node t (XKey.to_hash k) ~width ~nb_children
              in
              List.rev_map
                (function
                  | s, `Inode x ->
                      assert (s = None);
                      `Node x
                  | _, `Node x -> `Node x
                  | _, `Contents x -> `Contents x)
                preds
        in
        (* We are traversing only one commit. *)
        let pred_commit repo k =
          X.Commit.find (X.Repo.commit_t repo) k >|= function
          | None -> []
          | Some c ->
              let node = X.Commit.Val.node c in
              Stats.visit_commit t (XKey.to_hash node);
              [ `Node node ]
        in
        let pred_contents _repo k =
          Stats.visit_contents t (XKey.to_hash k);
          Lwt.return []
        in
        (* We want to discover all paths to a node, so we don't cache nodes
           during traversal. *)
        let* () =
          Repo.breadth_first_traversal ~cache_size:0 ~pred_node ~pred_commit
            ~pred_contents ~max:[ commit ] repo
        in
        Stats.pp_results ~dump_blob_paths_to t;
        Lwt.return_unit

      let run ~dump_blob_paths_to ~commit repo =
        Printexc.record_backtrace true;
        let key = `Commit (Commit.key commit) in
        traverse_inodes ~dump_blob_paths_to key repo
    end

    let stats = Stats.run
    let reload = X.Repo.reload
    let flush = X.Repo.flush

    module Gc = struct
      type msg = [ `Msg of string ]

      type stats = X.gc_stats = {
        duration : float;
        finalisation_duration : float;
        read_gc_output_duration : float;
        transfer_latest_newies_duration : float;
        swap_duration : float;
        unlink_duration : float;
      }
      [@@deriving irmin]

      type process_state = [ `Idle | `Running | `Finalised of stats ]

      let catch_errors context error =
        let err =
          match error with
          | Errors.Pack_error error ->
              Fmt.str "Pack_error: %a" Errors.pp_base_error error
          | Irmin.Closed -> "Irmin.Closed"
          | Irmin_pack.RO_not_allowed -> "Irmin_pack.RO_not_allowed"
          | Unix.Unix_error (err, s1, s2) ->
              let pp = Irmin.Type.pp Io.misc_error_t in
              Fmt.str "Unix_error: %a" pp (err, s1, s2)
          | exn -> raise exn
        in
        let error_msg = Fmt.str "[%s] resulted in error: %s" context err in
        Lwt.return_error (`Msg error_msg)

      let map_errors context (error : Errs.t) =
        let err = Fmt.str "%a" Errs.pp error in
        let err_msg = Fmt.str "[%s] resulted in error: %s" context err in
        `Msg err_msg

      let finalise_exn = X.Repo.Gc.finalise_exn
      let start_exn = X.Repo.Gc.start_exn ~use_auto_finalisation:false

      let start repo commit_key =
        try
          let* started =
            X.Repo.Gc.start_exn ~unlink:true ~use_auto_finalisation:true repo
              commit_key
          in
          Lwt.return_ok started
        with exn -> catch_errors "Start GC" exn

      let is_finished = X.Repo.Gc.is_finished

      let wait repo =
        try
          let* result = finalise_exn ~wait:true repo in
          match result with
          | `Running ->
              assert false (* [~wait:true] should never return [Running] *)
          | `Idle -> Lwt.return_ok None
          | `Finalised stats -> Lwt.return_ok @@ Some stats
        with exn -> catch_errors "Wait for GC" exn

      let run ?(finished = fun _ -> Lwt.return_unit) repo commit_key =
        let* started = start repo commit_key in
        match started with
        | Ok r ->
            if r then
              X.Repo.Gc.on_finalise repo (fun finalisation_r ->
                  match finalisation_r with
                  | Ok _ as stats -> finished stats
                  | Error err ->
                      let err_msg = map_errors "Finalise GC" err in
                      finished @@ Error err_msg);
            Lwt.return_ok r
        | Error _ as e -> Lwt.return e
    end

    module Traverse_pack_file = Traverse_pack_file.Make (struct
      module File_manager = File_manager
      module Hash = H
      module Index = Index
      module Inode = X.Node.CA
      module Dict = Dict
      module Contents = X.Contents.Pack_value
      module Commit = X.Commit.Pack_value
    end)

    let traverse_pack_file = Traverse_pack_file.run
    let test_traverse_pack_file = Traverse_pack_file.test

    module Snapshot = struct
      include X.Node.CA.Snapshot

      type t = Inode of inode | Blob of Backend.Contents.Val.t
      [@@deriving irmin]

      module S = Snapshot.Make (struct
        module Hash = H
        module Inode = X.Node.CA
        module Contents_pack = X.Contents.CA
        module Fm = File_manager
        module Dispatcher = Dispatcher
      end)

      include S

      module Export = struct
        let iter ?on_disk repo f ~root_key =
          [%log.debug "Iterate over a tree"];
          let contents = X.Repo.contents_t repo in
          let nodes = X.Repo.node_t repo |> snd in
          let export = S.Export.v repo.config contents nodes in
          let f_contents x = f (Blob x) in
          let f_nodes x = f (Inode x) in
          match root_key with
          | `Contents _ -> Fmt.failwith "[root_key] cannot be of type contents"
          | `Node key ->
              let* total =
                Export.run ?on_disk export f_contents f_nodes
                  (key, Pack_value.Kind.Inode_v2_root)
              in
              Export.close export |> Errs.raise_if_error;
              Lwt.return total
      end

      let export = Export.iter

      module Import = struct
        type process = Import.t

        let v ?on_disk repo =
          let contents = X.Repo.contents_t repo in
          let nodes = X.Repo.node_t repo |> snd in
          let log_size = Conf.index_log_size repo.config in
          Import.v ?on_disk log_size contents nodes

        let save_elt process elt =
          match elt with
          | Blob x -> Import.save_contents process x
          | Inode x -> Import.save_inodes process x

        let close process repo =
          flush repo;
          Import.close process
      end
    end
  end
end
OCaml

Innovation. Community. Security.