Something went wrong. Try again.
Git format in pure OCaml
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391(* Copyright (c) 2024-2026 Thomas Gazagnaire <thomas@gazagnaire.org>
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. *)
module Hash = Git.Hash
let src = Logs.Src.create "git.subtree.cache" ~doc:"Git subtree split caches"
module L = (val Logs.src_log src : Logs.LOG)
let prefix_fields = Probe.Fields.( obj (fun prefix -> prefix) |> field "prefix" string ~enc:(fun prefix -> prefix) |> seal)
let load_span = Probe.span "git.subtree.cache.load" ~doc:"Read one prefix's split cache" prefix_fields
let save_span = Probe.span "git.subtree.cache.save" ~doc:"Write one prefix's split cache" prefix_fields
(* A prefix names its own refs, and a prefix holds separators, so [src] and [src/lib] would want to be a file and a directory of the same name under one namespace. Percent-encode the separator, and the escape itself, so every prefix maps to one ref name and no two prefixes can collide. *)let ref_in ~namespace ~prefix = let b = Buffer.create (String.length prefix + 16) in String.iter (function | '%' -> Buffer.add_string b "%25" | '/' -> Buffer.add_string b "%2F" | c -> Buffer.add_char b c) prefix; namespace ^ Buffer.contents b
(* The chain a split produces is reachable from nothing: it is written into the object database and named only by the cache, so git's next prune of unreachable objects takes it and leaves the cache naming commits that are gone. This ref is what makes it reachable, and it is written wherever the tip is recorded so the two cannot disagree. *)let anchor_ref ~prefix = ref_in ~namespace:"refs/subtree/" ~prefix
(* A prefix's cache is two files of records "<commit> <split>\n", each hash in 40 lowercase hex digits. [<prefix>] is the table, sorted by commit and read in place by binary search, so loading it parses nothing. [<prefix>.log] holds the records added since the table was written, in the order they were added; a save appends to it. Once the log holds [compact_at] records, or an entry was removed, the next save merges it into a new table. *)
let record = 82let hash_hex = 40let compact_at = 4096
type t = { mutable table : string; (** Sorted records, as read or last written. *) added : (Hash.t, Hash.t) Hashtbl.t; (** The bindings over the table: the log's, then this process's. *) removed : (Hash.t, unit) Hashtbl.t; (** Commits of the table removed since it was written. *) pending : Buffer.t; (** Records added since the last save. *) mutable logged : int; (** Records in the log file. *) mutable rewrite : bool; (** The files hold what a load must not see again: a removed entry, or a malformed record. The next save writes a new table. *)}
let empty () = { table = ""; added = Hashtbl.create 256; removed = Hashtbl.create 1; pending = Buffer.create 0; logged = 0; rewrite = false; }
let hex_value c = match c with | '0' .. '9' -> Char.code c - 48 | 'a' .. 'f' -> Char.code c - 87 | _ -> -1
let byte_at s off i = (hex_value (String.unsafe_get s (off + (2 * i))) * 16) + hex_value (String.unsafe_get s (off + (2 * i) + 1))
let hash_at s off = Hash.of_raw_string (String.init Hash.digest_size (fun i -> Char.chr (byte_at s off i)))
(* The order of the commit of the record at [off] against [raw], a raw hash, from its byte [i]: lowercase hex sorts as the bytes it spells. The loops over a table are closed functions, so reading one allocates nothing. *)let rec compare_from s off raw i = if i = Hash.digest_size then 0 else let d = byte_at s off i - Char.code (String.unsafe_get raw i) in if d <> 0 then d else compare_from s off raw (i + 1)
let compare_at s off raw = compare_from s off raw 0let records s = String.length s / record
(* The index of the record of [h] in [table], or [-1]. *)let rec search table raw lo hi = if lo >= hi then -1 else let mid = (lo + hi) / 2 in let c = compare_at table (mid * record) raw in if c = 0 then mid else if c < 0 then search table raw (mid + 1) hi else search table raw lo mid
let table_index table h = search table (Hash.to_raw_string h) 0 (records table)
let find t h = match Hashtbl.find_opt t.added h with | Some _ as found -> found | None when Hashtbl.mem t.removed h -> None | None -> ( match table_index t.table h with | -1 -> None | i -> Some (hash_at t.table ((i * record) + hash_hex + 1)))
let mem t h = Hashtbl.mem t.added h || ((not (Hashtbl.mem t.removed h)) && table_index t.table h >= 0)
let add_record buf old_hash new_hash = Buffer.add_string buf (Hash.to_hex old_hash); Buffer.add_char buf ' '; Buffer.add_string buf (Hash.to_hex new_hash); Buffer.add_char buf '\n'
let add t old_hash new_hash = Hashtbl.replace t.added old_hash new_hash; add_record t.pending old_hash new_hash
let is_dirty t = Buffer.length t.pending > 0 || t.rewrite
let remove t h = Hashtbl.remove t.added h; if table_index t.table h >= 0 then Hashtbl.replace t.removed h (); t.rewrite <- true
let cache_dir_name prefix = let s = String.map (fun c -> if c = '/' then '_' else c) prefix in (* Avoid "." as a filename (would conflict with the directory itself). *) if s = "." || s = ".." then "_root_" else s
let rec hex_run s off i = i = hash_hex || match String.unsafe_get s (off + i) with | '0' .. '9' | 'a' .. 'f' -> hex_run s off (i + 1) | _ -> false
let well_formed_at s off = hex_run s off 0 && String.unsafe_get s (off + hash_hex) = ' ' && hex_run s (off + hash_hex + 1) 0 && String.unsafe_get s (off + record - 1) = '\n'
(* Whether the commit of the record at [a] sorts before the one at [b], from their digit [i]. *)let rec increasing s a b i = i < hash_hex && let x = String.unsafe_get s (a + i) and y = String.unsafe_get s (b + i) in if x = y then increasing s a b (i + 1) else x < y
let rec sorted_from s n i = i = n || well_formed_at s (i * record) && (i = 0 || increasing s ((i - 1) * record) (i * record) 0) && sorted_from s n (i + 1)
(* Whether [s] is a table: whole records, each well formed, their commits strictly increasing. *)let is_table s = String.length s mod record = 0 && sorted_from s (records s) 0
let cache_dir repo = let git_dir = Fpath.to_string (Repository.git_dir repo) in Eio.Path.(Repository.fs repo / git_dir / "subtree-cache")
(* The cache directory made when missing; a cache that cannot be made is not kept. *)let make_cache_dir repo = try Shared_perm.mkdir (Repository.shared repo) ~perm:0o755 (cache_dir repo) with Eio.Io _ -> ()
let path_in repo name = Eio.Path.(cache_dir repo / name)let table_path repo ~prefix = path_in repo (cache_dir_name prefix)let log_path repo ~prefix = path_in repo (cache_dir_name prefix ^ ".log")let load_file path = try Eio.Path.load path with Eio.Io _ -> ""
(* The log's records, in order, up to the first one that is not whole and well formed, as an append cut short leaves it. *)let replay t log = let n = String.length log / record in let rec go i = if i < n && well_formed_at log (i * record) then begin let off = i * record in Hashtbl.replace t.added (hash_at log off) (hash_at log (off + hash_hex + 1)); go (i + 1) end else i in let whole = go 0 in t.logged <- whole; if whole * record <> String.length log then t.rewrite <- true
(* One table per (repository, prefix) for the life of the process. A run splits a prefix more than once -- the batch prewarm, then the per-package no-op check -- and the entries are derived from committed history, so two readers of one file want the same table anyway. *)let loaded : (string * string, t) Hashtbl.t = Hashtbl.create 64
let read_file repo ~prefix = Probe.with_span load_span prefix @@ fun () -> let t = empty () in let table = load_file (table_path repo ~prefix) in if is_table table then t.table <- table else begin L.warn (fun m -> m "cache for %s: the table is not sorted records; deriving it again" prefix); t.rewrite <- true end; replay t (load_file (log_path repo ~prefix)); t
let load repo ~prefix = let key = (Fpath.to_string (Repository.git_dir repo), prefix) in match Hashtbl.find_opt loaded key with | Some t -> t | None -> let t = read_file repo ~prefix in Hashtbl.replace loaded key t; t
(* The table of [t]'s bindings: the old table's records that were neither removed nor bound again, merged with the added bindings in order. *)let merged t = let added = Array.of_seq (Hashtbl.to_seq t.added) |> fun a -> Array.sort (fun (a, _) (b, _) -> Hash.compare a b) a; a in let n = records t.table and m = Array.length added in let buf = Buffer.create ((n + m) * record) in let kept i = Hashtbl.length t.removed = 0 || not (Hashtbl.mem t.removed (hash_at t.table (i * record))) in let rec go i j = if i = n && j = m then () else if j = m || i < n && compare_at t.table (i * record) (Hash.to_raw_string (fst added.(j))) < 0 then begin if kept i then Buffer.add_substring buf t.table (i * record) record; go (i + 1) j end else begin let k, v = added.(j) in add_record buf k v; let i = if i < n && compare_at t.table (i * record) (Hash.to_raw_string k) = 0 then i + 1 else i in go i (j + 1) end in go 0 0; Buffer.contents buf
let compact repo ~prefix t = let table = merged t in let path = table_path repo ~prefix in let tmp = path_in repo (cache_dir_name prefix ^ ".new") in Eio.Path.save ~create:(`Or_truncate 0o644) tmp table; Shared_perm.adjust (Repository.shared repo) tmp; Eio.Path.rename tmp path; (try Eio.Path.unlink (log_path repo ~prefix) with Eio.Io _ -> ()); t.table <- table; Hashtbl.reset t.added; Hashtbl.reset t.removed; t.logged <- 0; t.rewrite <- false
let append repo ~prefix t = Eio.Path.with_open_out ~append:true ~create:(`If_missing 0o644) (log_path repo ~prefix) (fun flow -> Shared_perm.adjust (Repository.shared repo) (log_path repo ~prefix); Eio.Flow.copy_string (Buffer.contents t.pending) flow); t.logged <- t.logged + (Buffer.length t.pending / record)
let save repo ~prefix t = Probe.with_span save_span prefix @@ fun () -> make_cache_dir repo; let unlogged = Buffer.length t.pending / record in if t.rewrite || t.table = "" || t.logged + unlogged >= compact_at then compact repo ~prefix t else if unlogged > 0 then append repo ~prefix t; Buffer.clear t.pending
let iter t f = for i = 0 to records t.table - 1 do let k = hash_at t.table (i * record) in if not (Hashtbl.mem t.added k || Hashtbl.mem t.removed k) then f k (hash_at t.table ((i * record) + hash_hex + 1)) done; Hashtbl.iter f t.added
let length t = let n = ref 0 in iter t (fun _ _ -> incr n); !n
(* Hold the chain [split] heads, so git's next prune of unreachable objects leaves it alone. An absence anchors nothing and drops whatever the prefix held before. The ref is read before it is written: a push with nothing to send anchors every prefix it answers, and paying a write for each of them would turn that run into a few hundred pointless ref updates. A ref that cannot be read is written: only a read of the same split skips it. *)let anchor repo ~prefix split = let name = anchor_ref ~prefix in if Hash.equal split Hash.null then Repository.delete_ref repo name else match Repository.read_ref repo name with | Ok (Some h) when Hash.equal h split -> () | Ok _ | Error _ -> Repository.write_ref repo name split
(* The entry for the commit the cache was last saved at, in a file of its own. Answering "what is the split of HEAD" -- the question a push asks once per package, and the only one it asks when there is nothing to send -- otherwise reads and parses the whole cache to reach a single line. *)let tip_path repo ~prefix = path_in repo (cache_dir_name prefix ^ ".tip")
let read_tip repo ~prefix = match Eio.Path.load (tip_path repo ~prefix) with | exception (Eio.Io _ | Invalid_argument _) -> None | data -> if String.length data >= 81 then Some ( Hash.of_hex (String.sub data 0 40), Hash.of_hex (String.sub data 41 40) ) else None
let write_tip repo ~prefix ~head ~split = make_cache_dir repo; (* Anchor first: a tip file naming a commit that nothing keeps is the state a prune turns into a broken cache. *) anchor repo ~prefix split; try Eio.Path.save ~create:(`Or_truncate 0o644) (tip_path repo ~prefix) (Hash.to_hex head ^ " " ^ Hash.to_hex split ^ "\n"); Shared_perm.adjust (Repository.shared repo) (tip_path repo ~prefix) with Eio.Io _ -> ()
let clear_tip repo ~prefix = try Eio.Path.unlink (tip_path repo ~prefix) with Eio.Io _ -> ()
let clear repo ~prefix = Hashtbl.remove loaded (Fpath.to_string (Repository.git_dir repo), prefix); clear_tip repo ~prefix; (* The anchor goes with the derivation it kept alive. Leaving it would hold a chain nothing names any more -- a prefix that was removed keeps its whole history out of reach of every prune. *) Repository.delete_ref repo (anchor_ref ~prefix); List.iter (fun path -> try Eio.Path.unlink path with Eio.Io _ -> ()) [ table_path repo ~prefix; log_path repo ~prefix ]