diff options
| author | Estevan Castilho <tevo@riajuu.net> | 2026-08-22 17:55:26 +0000 |
|---|---|---|
| committer | Estevan Castilho <tevo@riajuu.net> | 2026-08-23 03:06:58 +0000 |
| commit | db968eccee931abc8ad00d74d152625a2ab3174e (patch) | |
| tree | 3d5018dd9e298cfc1fb14bf404cde3fce5953fca | |
| parent | b242516fc820a0a1ab00e24151a5b978f9a6f4a3 (diff) | |
| download | RNT-db968eccee931abc8ad00d74d152625a2ab3174e.tar.gz RNT-db968eccee931abc8ad00d74d152625a2ab3174e.zip | |
Tidy up
Diffstat (limited to '')
46 files changed, 179 insertions, 1579 deletions
diff --git a/lib/Utilities.ml b/lib/Utilities.ml index 0a5bd9d..a96d16f 100644 --- a/lib/Utilities.ml +++ b/lib/Utilities.ml @@ -1,3 +1,9 @@ +module Ordering = struct + type t = Equal | Smaller | Greater + + let of_int x = if x < 0 then Smaller else if x > 0 then Greater else Equal +end + module Result = struct let ( let* ) = Result.bind let fmap f m = Result.bind m f diff --git a/lib/Utilities.mli b/lib/Utilities.mli index 34a03e9..f9c0c29 100644 --- a/lib/Utilities.mli +++ b/lib/Utilities.mli @@ -1,3 +1,9 @@ +module Ordering : sig + type t = Equal | Smaller | Greater + + val of_int : int -> t +end + module Result : sig val ( let* ) : ('a, 'e) result -> ('a -> ('b, 'e) result) -> ('b, 'e) result val fmap : ('a -> ('b, 'e) result) -> ('a, 'e) result -> ('b, 'e) result diff --git a/lib/abstract/Storage.ml b/lib/abstract/Storage.ml index c936be4..19d6c5c 100644 --- a/lib/abstract/Storage.ml +++ b/lib/abstract/Storage.ml @@ -24,12 +24,12 @@ module type STORAGE = sig val get : transaction -> address -> - (Concepts.Representation.blob option, Concepts.Condition.condition) result + (Concepts.Blob.t option, Concepts.Condition.condition) result (** within a transaction, associate a hash with a blob on disk *) val put : transaction -> address -> - Concepts.Representation.blob -> + Concepts.Blob.t -> (unit, Concepts.Condition.condition) result end diff --git a/lib/backend/execution/FOL.ml b/lib/backend/execution/FOL.ml deleted file mode 100644 index 7da890d..0000000 --- a/lib/backend/execution/FOL.ml +++ /dev/null @@ -1,110 +0,0 @@ -(* @uses Tuple -- project, rename, merge over result streams *) -(* @needs Value *) -(* @needs Path *) -(* @needs Condition *) - -module Plan = struct - type path_arg = Var of string | Const of Concepts.Value.value - - type t = - | Scan of {path: Concepts.Path.t; args: path_arg BatFingerTree.t} - | Natural of {left: t; right: t} - | Take of {limit: int; from: t} - | Project of {attrs: BatSet.String.t; from: t} - | Materialize of t - | Rename of {attrs: string BatMap.String.t; from: t} - | Union of t BatFingerTree.t -end - -type stream = (Concepts.Tuple.t, Concepts.Condition.condition) result BatSeq.t - -let singleton (x : ('a, 'e) result) : ('a, 'e) result BatSeq.t = - fun () -> BatSeq.Cons (x, BatSeq.empty) - -module Error = struct - open Concepts.Condition - - let unbound_variable name = - condition "unbound-variable" - (Printf.sprintf "path variable %S is not bound in the enclosing tuple" name) - ("variable" |=| Concepts.Value.String name) -end - -let resolve (args : Plan.path_arg BatFingerTree.t) (bindings : Concepts.Tuple.t) : - (Concepts.Value.value BatFingerTree.t, Concepts.Condition.condition) result = - let open Utilities.Result in - BatFingerTree.fold_left - (fun acc arg -> - let* acc = acc in - let* value = - match arg with - | Plan.Const value -> Ok value - | Plan.Var name -> - Option.to_result ~none:(Error.unbound_variable name) - (Concepts.Tuple.access name bindings) - in - Ok (BatFingerTree.snoc acc value) ) - (Ok BatFingerTree.empty) args - -module Make (Handler : Managers.Handle.HANDLER) = struct - let scan handler ~path ~args : stream = - let opened = - let open Utilities.Result in - let* handle = Handler.open_ handler ~path in - Handler.open_cursor handle ~args - in - match opened with - | Error condition -> singleton (Error condition) - | Ok cursor -> - let rec pull () = - match Handler.next cursor with - | Error condition -> BatSeq.Cons (Error condition, BatSeq.empty) - | Ok None -> BatSeq.Nil - | Ok (Some tuple) -> BatSeq.Cons (Ok tuple, pull) - in - pull - - let rec compile handler : Plan.t -> Concepts.Tuple.t -> stream = function - | Scan {path; args} -> ( - fun bindings -> - match resolve args bindings with - | Ok args -> scan handler ~path ~args - | Error condition -> singleton (Error condition) ) - | Project {attrs; from} -> - let from = compile handler from in - fun bindings -> BatSeq.map (Result.map (Concepts.Tuple.project attrs)) (from bindings) - | Rename {attrs; from} -> - let from = compile handler from in - fun bindings -> BatSeq.map (Result.map (Concepts.Tuple.rename attrs)) (from bindings) - | Take {limit; from} -> - let from = compile handler from in - fun bindings -> BatSeq.take limit (from bindings) - | Union plans -> - let compiled = BatFingerTree.map (compile handler) plans in - fun bindings -> - BatFingerTree.fold_right - (fun rest c -> BatSeq.append (c bindings) rest) - BatSeq.empty compiled - | Natural {left; right} -> - let left = compile handler left and right = compile handler right in - let matches l r = - BatMap.String.for_all - (fun name value -> - match Concepts.Tuple.access name r with Some value' -> value = value' | None -> true ) - l - in - fun bindings -> - left bindings - |> BatSeq.concat_map (function - | Error _ as error -> singleton error - | Ok l -> - right l - |> BatSeq.filter (function Ok r -> matches l r | Error _ -> true) - |> BatSeq.map (Result.map (Concepts.Tuple.merge l)) ) - | Materialize from -> - let cached = lazy (BatSeq.memoize (compile handler from Concepts.Tuple.empty)) in - fun _ -> Lazy.force cached - - (* TODO: This should produce ephemeral relations with support of the sublanguage to manage it. *) - let run handler plan : stream = compile handler plan Concepts.Tuple.empty -end diff --git a/lib/backend/managers/Cursor.ml b/lib/backend/managers/Cursor.ml deleted file mode 100644 index 7fdbb6f..0000000 --- a/lib/backend/managers/Cursor.ml +++ /dev/null @@ -1,24 +0,0 @@ -(* @composes Storage -- functor parameter *) -(* @needs Path *) -(* @needs Tuple *) -(* @needs Value *) -(* @needs Condition *) - -type descriptor = - | Stored of {merkle_root: string} - | Ephemeral of {merkle_root: string; dependencies: Concepts.Path.t BatFingerTree.t} - -module Make (Store : Abstract.Storage.STORAGE) = struct - type cursor = unit - - let open_ (_txn : Store.transaction) (descriptor : descriptor) - ~(args : Concepts.Value.value BatFingerTree.t) : (cursor, Concepts.Condition.condition) result - = - ignore (descriptor, args); - failwith "NOT IMPLEMENTED: open a cursor by paging the relation's Merkle tree over Store.get" - - let next (_cursor : cursor) : (Concepts.Tuple.t option, Concepts.Condition.condition) result = - failwith "NOT IMPLEMENTED: page the next tuple over Store.get" - - let close (_cursor : cursor) : unit = () -end diff --git a/lib/backend/managers/Cursor.mli b/lib/backend/managers/Cursor.mli deleted file mode 100644 index a4dec44..0000000 --- a/lib/backend/managers/Cursor.mli +++ /dev/null @@ -1,16 +0,0 @@ -type descriptor = - | Stored of {merkle_root: string} - | Ephemeral of {merkle_root: string; dependencies: Concepts.Path.t BatFingerTree.t} - -module Make (Store : Abstract.Storage.STORAGE) : sig - type cursor - - val open_ : - Store.transaction -> - descriptor -> - args:Concepts.Value.value BatFingerTree.t -> - (cursor, Concepts.Condition.condition) result - - val next : cursor -> (Concepts.Tuple.t option, Concepts.Condition.condition) result - val close : cursor -> unit -end diff --git a/lib/backend/managers/Handle.ml b/lib/backend/managers/Handle.ml deleted file mode 100644 index be84972..0000000 --- a/lib/backend/managers/Handle.ml +++ /dev/null @@ -1,64 +0,0 @@ -(* @composes Storage -- functor parameter *) -(* @composes Cursor -- applies Cursor.Make (Store) *) -(* @uses Object -- find, registry/kind inspection *) -(* @uses Condition -- builds not-a-relation / no-such-object errors *) -(* @needs Path *) -(* @needs Tuple *) -(* @needs Value *) - -module type HANDLER = sig - type t - type handle - type cursor - - val open_ : t -> path:Concepts.Path.t -> (handle, Concepts.Condition.condition) result - - val open_cursor : - handle -> - args:Concepts.Value.value BatFingerTree.t -> - (cursor, Concepts.Condition.condition) result - - val next : cursor -> (Concepts.Tuple.t option, Concepts.Condition.condition) result - val close : cursor -> unit -end - -let not_a_relation () : Concepts.Condition.condition = - Concepts.Condition.condition "not-a-relation" - "handle does not refer to a stored or ephemeral relation" Concepts.Condition.empty - -let no_such_object () : Concepts.Condition.condition = - Concepts.Condition.condition "no-such-object" "no object registered at the given path" - Concepts.Condition.empty - -module Make (Store : Abstract.Storage.STORAGE) = struct - module Cur = Cursor.Make (Store) - - type t = {objects: Object.rnt_object_tree; txn: Store.transaction} - type handle = {object_: Object.registry; txn: Store.transaction} - type cursor = Cur.cursor - - let create objects txn = {objects; txn} - - let open_ t ~path = - match Object.find path t.objects with - | Some object_ -> Ok {object_; txn= t.txn} - | None -> Error (no_such_object ()) - - let relation_descriptor (object_ : Object.registry) : - (Cursor.descriptor, Concepts.Condition.condition) result = - let {Object.entry; _} = object_ in - match entry.Object.kind with - | Object.Relation {merkle_root} -> Ok (Cursor.Stored {merkle_root}) - | Object.EphemeralRelation {merkle_root; dependencies} -> - Ok (Cursor.Ephemeral {merkle_root; dependencies}) - | _ -> Error (not_a_relation ()) - - let open_cursor handle ~args = - let open Utilities.Result in - let* descriptor = relation_descriptor handle.object_ in - Cur.open_ handle.txn descriptor ~args - - let next = Cur.next - let close = Cur.close - let object_ (handle : handle) = handle.object_ -end diff --git a/lib/backend/managers/Handle.mli b/lib/backend/managers/Handle.mli deleted file mode 100644 index 5fc82b8..0000000 --- a/lib/backend/managers/Handle.mli +++ /dev/null @@ -1,22 +0,0 @@ -module type HANDLER = sig - type t - type handle - type cursor - - val open_ : t -> path:Concepts.Path.t -> (handle, Concepts.Condition.condition) result - - val open_cursor : - handle -> - args:Concepts.Value.value BatFingerTree.t -> - (cursor, Concepts.Condition.condition) result - - val next : cursor -> (Concepts.Tuple.t option, Concepts.Condition.condition) result - val close : cursor -> unit -end - -module Make (Store : Abstract.Storage.STORAGE) : sig - include HANDLER - - val create : Object.rnt_object_tree -> Store.transaction -> t - val object_ : handle -> Object.registry -end diff --git a/lib/backend/managers/Identity.ml b/lib/backend/managers/Identity.ml deleted file mode 100644 index bfde226..0000000 --- a/lib/backend/managers/Identity.ml +++ /dev/null @@ -1,7 +0,0 @@ -(* @needs Object *) - -let permits (object_ : Object.registry) (method_ : Object.rnt_method) : bool = - BatSet.mem method_ object_.Object.entry.Object.methods - -let can_open (object_ : Object.registry) : bool = permits object_ Object.OPEN -let can_close (object_ : Object.registry) : bool = permits object_ Object.CLOSE diff --git a/lib/backend/managers/Identity.mli b/lib/backend/managers/Identity.mli deleted file mode 100644 index 589002e..0000000 --- a/lib/backend/managers/Identity.mli +++ /dev/null @@ -1,3 +0,0 @@ -val permits : Object.registry -> Object.rnt_method -> bool -val can_open : Object.registry -> bool -val can_close : Object.registry -> bool diff --git a/lib/backend/managers/Lifecycle.ml b/lib/backend/managers/Lifecycle.ml deleted file mode 100644 index d104249..0000000 --- a/lib/backend/managers/Lifecycle.ml +++ /dev/null @@ -1,110 +0,0 @@ -(* The lifecycle manager decides when a registered object may leave memory. - It works purely on the object tree and never touches storage: collection - here means dropping the in-memory registry entry, not deleting anything on - disk. Durable-backed objects (relations, multigroups, branch trees) can be - rebuilt from their encoded form on the next access, so evicting them is - safe and keeps memory bounded. Runtime-only objects (sessions, and later - transactions) have no durable form, so their collection is a real teardown; - the manager surfaces those to the caller as disposals rather than acting on - storage itself. *) - -(* @uses Object -- find/update, unregister, reference_edges, has_children *) -(* @needs Path *) -(* @needs Condition *) - -type tree = Object.rnt_object_tree - -(* A runtime object that was collected and now needs an external teardown the - lifecycle manager cannot perform on its own: closing a session, and later - rolling back a transaction. The caller drains these after a collect. *) -type disposal = {path: Concepts.Path.t; kind: Object.rnt_object_kind} - -let monitor (tree : tree) (path : Concepts.Path.t) : tree = - Object.update path (fun r -> {r with Object.handle_count= r.Object.handle_count + 1}) tree - -(* Pin is an explicit keep-alive that bypasses collection. It does not touch - reference_count: pinning is a decision, reference counting is bookkeeping of - real edges. Keeping them separate is what stops the two from being mistaken - for each other. *) -let pin (tree : tree) (path : Concepts.Path.t) : tree = - Object.update path (fun r -> {r with Object.pinned= true}) tree - -let unpin (tree : tree) (path : Concepts.Path.t) : tree = - Object.update path (fun r -> {r with Object.pinned= false}) tree - -(* An object may be collected only when nothing holds it open, nothing depends - on it, it has not been pinned, and its kind is not exempt (a branch). This - works on the registry record directly so callers that already hold it (the - cascade) need not walk the tree a second time. *) -let registry_eligible (r : Object.registry) : bool = - r.Object.handle_count = 0 - && r.Object.reference_count = 0 - && (not r.Object.pinned) - && not (Object.is_gc_exempt r.Object.entry.Object.kind) - -let is_eligible_for_gc (tree : tree) (path : Concepts.Path.t) : bool = - match Object.find path tree with Some r -> registry_eligible r | None -> false - -(* Contention reports whether a mutation must wait. An exclusive object with an - open handle, such as a branch head being read, cannot be modified until the - handle closes. This gates writers; it is not part of collection. *) -let contention (tree : tree) (path : Concepts.Path.t) : bool = - match Object.find path tree with - | Some r -> r.Object.entry.Object.exclusive && r.Object.handle_count > 0 - | None -> false - -(* Cascade the collection at path, threading the pruned tree and the disposals - gathered so far. Disposals are appended (snoc) as each object is torn down, - so the finger tree hands them back parent-first, left-to-right without any - reversal pass. - - Order of teardown falls out of the counts. Collecting an object drops the - reference_count of every input it depended on (Object.unregister undoes the - edges), which can make those inputs eligible in turn, so we recurse into - them. A populated namespace is kept, not collected and not an error: it is - scaffolding for the objects still living under it. *) -let rec cascade (tree : tree) (disposals : disposal BatFingerTree.t) (path : Concepts.Path.t) : - (tree * disposal BatFingerTree.t, Concepts.Condition.condition) result = - match Object.find path tree with - | None -> Ok (tree, disposals) - | Some r when not (registry_eligible r) -> Ok (tree, disposals) - | Some r -> - let kind = r.Object.entry.Object.kind in - begin match kind with - | Object.Namespace _ when Object.has_children path tree -> Ok (tree, disposals) - | _ -> - let edges = Object.reference_edges kind in - let disposals = - if Object.is_runtime kind then BatFingerTree.snoc disposals {path; kind} else disposals - in - Result.bind (Object.unregister path tree) (fun tree -> - BatFingerTree.fold_left - (fun acc dep -> Result.bind acc (fun (tree, disposals) -> cascade tree disposals dep)) - (Ok (tree, disposals)) - edges ) - end - -let try_collect (tree : tree) (path : Concepts.Path.t) : - (tree * disposal BatFingerTree.t, Concepts.Condition.condition) result = - cascade tree BatFingerTree.empty path - -(* Close a handle, then see whether the object can now go. *) -let unmonitor (tree : tree) (path : Concepts.Path.t) : - (tree * disposal BatFingerTree.t, Concepts.Condition.condition) result = - let tree = - Object.update path - (fun r -> - if r.Object.handle_count = 0 then r - else {r with Object.handle_count= r.Object.handle_count - 1} ) - tree - in - try_collect tree path - -(* Public entry point for an explicit collection request. *) -let collect (tree : tree) (path : Concepts.Path.t) : - (tree * disposal BatFingerTree.t, Concepts.Condition.condition) result = - try_collect tree path - -(* Session reaping is not built here yet. A lost connection is detected by a - per-session inactivity timer whose expiry drives collect on the session. - Design and tasks are tracked in issue #24. *) diff --git a/lib/backend/managers/Lifecycle.mli b/lib/backend/managers/Lifecycle.mli deleted file mode 100644 index f8cec1a..0000000 --- a/lib/backend/managers/Lifecycle.mli +++ /dev/null @@ -1,17 +0,0 @@ -type tree = Object.rnt_object_tree - -(* A collected runtime object that still needs an external teardown: a session - to close, and later a transaction to roll back. The caller drains these. *) -type disposal = {path: Concepts.Path.t; kind: Object.rnt_object_kind} - -val monitor : tree -> Concepts.Path.t -> tree -val pin : tree -> Concepts.Path.t -> tree -val unpin : tree -> Concepts.Path.t -> tree -val is_eligible_for_gc : tree -> Concepts.Path.t -> bool -val contention : tree -> Concepts.Path.t -> bool - -val unmonitor : - tree -> Concepts.Path.t -> (tree * disposal BatFingerTree.t, Concepts.Condition.condition) result - -val collect : - tree -> Concepts.Path.t -> (tree * disposal BatFingerTree.t, Concepts.Condition.condition) result diff --git a/lib/backend/managers/Namespace.ml b/lib/backend/managers/Namespace.ml deleted file mode 100644 index a48fef9..0000000 --- a/lib/backend/managers/Namespace.ml +++ /dev/null @@ -1,14 +0,0 @@ -(* @composes Storage -- functor parameter *) -(* @needs Object *) -(* @needs Path *) -(* @needs Condition *) - -module Make (Store : Abstract.Storage.STORAGE) = struct - type tree = Object.rnt_object_tree - - let resolve (_txn : Store.transaction) (_tree : tree) (_path : Concepts.Path.t) : - (Concepts.Path.t, Concepts.Condition.condition) result = - failwith - "NOT IMPLEMENTED: reparse loop with cycle guard; /system/branches/<n>/<sub> -> \ - /system/snapshots/<target_hash>/<sub> via Branch.target_hash" -end diff --git a/lib/backend/managers/Namespace.mli b/lib/backend/managers/Namespace.mli deleted file mode 100644 index 1ee9651..0000000 --- a/lib/backend/managers/Namespace.mli +++ /dev/null @@ -1,9 +0,0 @@ -module Make (Store : Abstract.Storage.STORAGE) : sig - type tree = Object.rnt_object_tree - - val resolve : - Store.transaction -> - tree -> - Concepts.Path.t -> - (Concepts.Path.t, Concepts.Condition.condition) result -end diff --git a/lib/backend/managers/Object.ml b/lib/backend/managers/Object.ml deleted file mode 100644 index d54c89d..0000000 --- a/lib/backend/managers/Object.ml +++ /dev/null @@ -1,343 +0,0 @@ -(* @uses Path -- snoc, to_string when building registry paths *) -(* @uses Condition -- builds registry-object/path errors *) -(* @needs Value *) - -type multigroup = {merkle_root: string} -type relation = {merkle_root: string} - -(* An ephemeral relation is a stored plan that reads other relations. Its - dependencies are the inputs that plan replays over. They are branch-local - symlink paths, not version-pinned paths: as the branch head advances the - inputs move with it, and Namespace.resolve turns the symlink into whatever - object is current on this branch hash. Keeping them as paths (not hashes) - is what lets an ephemeral relation behave like a view. *) -type ephemeral_relation = {merkle_root: string; dependencies: Concepts.Path.t BatFingerTree.t} -type transaction = unit -type session = {connection_context: unit; branch_overrides: string BatMap.String.t} -type branch = {name: string; target_hash: string} -type branch_tree = {merkle_root: string} - -type rnt_object_kind = - | Multigroup of multigroup - | Relation of relation - | EphemeralRelation of ephemeral_relation - | Session of session - | Branch of branch - | BranchTree of branch_tree - | Namespace of namespace - -and namespace = {label: string; predicate: rnt_object_kind -> bool} - -type rnt_method = OPEN | CLOSE - -type rnt_object = - {kind: rnt_object_kind; disposable: bool; methods: rnt_method BatSet.t; exclusive: bool} - -(* Three independent facts about a registered object, kept apart on purpose: - - - handle_count: how many handles are open on it right now (open/close). - - reference_count: how many other objects depend on it staying resident. - This is bookkeeping of real edges, nothing more. It goes up because a - dependency exists, not because someone asked to keep the object alive. - - pinned: an explicit override that bypasses collection regardless of the - counts. Used when something must not be evicted even though nothing - currently points at it or holds it open. This is deliberately separate - from reference_count so the two reasons never get confused. *) -type registry = {reference_count: int; handle_count: int; pinned: bool; entry: rnt_object} - -(* - /system/branch/branch1/multigrop/multigroup1/relation/relation1 - /system/branch1/multigrop/multigroup1/relation/relation2 - /system/branch1/multigrop/multigroup1/ephemeral_relation/ephemeral_relation1 - /system/transaction/xyz_txn - *) - -type rnt_object_tree = {data: registry; subsequent: rnt_object_tree BatMap.String.t} - -module type RUNTIME_STRATEGY = sig - type 'a state - - (* The exact snapshot observed on acquire *) - type 'a token - - val create : 'a -> 'a state - val acquire : 'a state -> 'a * 'a token - val publish : 'a state -> 'a token -> 'a -> (unit, Concepts.Condition.condition) result -end - -module Error = struct - open Concepts.Condition - - let registry_object_already_registered path = - let msg = "An object is already registered in the path" in - condition "registry-object-already-registered" msg - ("path" |=| Concepts.Value.String (Concepts.Path.to_string path)) - - let registry_path_not_found path = - let msg = "The provided path was not found" in - condition "registry-path-not-found" msg - ("path" |=| Concepts.Value.String (Concepts.Path.to_string path)) -end - -let make_object ?(disposable = false) ?(exclusive = false) ?(methods = BatSet.empty) - (kind : rnt_object_kind) : rnt_object = - {kind; disposable; methods; exclusive} - -(* The empty registry. The root node is the system namespace itself, and every - other object is registered under it. Path separators are only a string - rendering concern, so there is no distinct "/" node above system: system is - the root. It is exempt from collection for the same reason a branch is, it - is the way in to everything else. *) -let root : rnt_object_tree = - { data= - { reference_count= 0; - handle_count= 0; - pinned= false; - entry= make_object (Namespace {label= "system"; predicate= (fun _ -> true)}) }; - subsequent= BatMap.String.empty } - -let find (path : Concepts.Path.t) (tree : rnt_object_tree) : registry option = - let rec walk components node = - match BatFingerTree.front components with - | None -> Some node.data - | Some (tail, head) -> Option.bind (BatMap.String.find_opt head node.subsequent) (walk tail) - in - walk path tree - -let update (path : Concepts.Path.t) (f : registry -> registry) (tree : rnt_object_tree) : - rnt_object_tree = - let rec walk components node = - match BatFingerTree.front components with - | None -> {node with data= f node.data} - | Some (tail, head) -> - begin match BatMap.String.find_opt head node.subsequent with - | None -> node - | Some child -> - {node with subsequent= BatMap.String.add head (walk tail child) node.subsequent} - end - in - walk path tree - -(* The objects that must stay resident for this object to remain replayable. - Registering an object bumps the reference_count of each edge target and - unregistering drops it, so reference counts stay in step with the real - dependency graph. Only ephemeral relations carry edges today. Which kinds - grow edges is a per-kind decision, which is why this lives next to the - registry and not in the lifecycle manager: the object knows its own shape. *) -let reference_edges (kind : rnt_object_kind) : Concepts.Path.t BatFingerTree.t = - match kind with - | EphemeralRelation {dependencies; _} -> dependencies - | Multigroup _ | Relation _ | Session _ | Branch _ | BranchTree _ | Namespace _ -> - BatFingerTree.empty - -(* Adjust the reference_count of every edge target by delta. A target that is - not present is skipped: update leaves the tree untouched when the path is - missing. That is fine for a skeleton, but it hides a dangling dependency, - so registration will eventually want to fail loudly on a missing input. *) -let adjust_references (delta : int) (paths : Concepts.Path.t BatFingerTree.t) - (tree : rnt_object_tree) : rnt_object_tree = - BatFingerTree.fold_left - (fun tree path -> - update path (fun r -> {r with reference_count= r.reference_count + delta}) tree ) - tree paths - -(* A branch is exempt from collection because everything is reachable through - it: collecting a branch would orphan its whole subtree. Every other kind is - collectable, including sessions. A session is runtime-only state with no - durable encoding, so collecting one is a real teardown rather than an - eviction, but it still happens (see Lifecycle for how a dead session is - detected). *) -let is_gc_exempt (kind : rnt_object_kind) : bool = match kind with Branch _ -> true | _ -> false - -(* Runtime-only kinds have no durable encoding, so collecting them cannot be - undone by rehydrating from disk. The lifecycle manager surfaces these to - its caller as disposals to run (a session close, and later a transaction - rollback once transactions become objects in their own right). *) -let is_runtime (kind : rnt_object_kind) : bool = match kind with Session _ -> true | _ -> false - -let has_children (path : Concepts.Path.t) (tree : rnt_object_tree) : bool = - let rec walk components node = - match BatFingerTree.front components with - | None -> not (BatMap.String.is_empty node.subsequent) - | Some (tail, head) -> - begin match BatMap.String.find_opt head node.subsequent with - | None -> false - | Some child -> walk tail child - end - in - walk path tree - -(* TODO: This function is not tail call optimized. We ventured with - the idea of using CPS, but that's not going to solve anything here, - so the probable best course of action is relying on the growing map - to carry on the state. This is not a big deal as the structure is - expected to be small enough to live in memory and these operations - are relatively uncommon. *) -let register (path : Concepts.Path.t) (object' : rnt_object) (tree : rnt_object_tree) : - (rnt_object_tree, Concepts.Condition.condition) result = - let rec insert components node = - match BatFingerTree.front components with - | None -> Error (Error.registry_object_already_registered path) - | Some (tail, head) when BatFingerTree.is_empty tail -> - if BatMap.String.mem head node.subsequent then - Error (Error.registry_object_already_registered path) - else - let child = - { data= {reference_count= 0; handle_count= 0; pinned= false; entry= object'}; - subsequent= BatMap.String.empty } - in - Ok {node with subsequent= BatMap.String.add head child node.subsequent} - | Some (tail, head) -> - begin match BatMap.String.find_opt head node.subsequent with - | None -> Error (Error.registry_path_not_found path) - | Some child -> - Result.map (fun child' -> - {node with subsequent= BatMap.String.add head child' node.subsequent} ) - @@ insert tail child - end - in - (* On success, record the new object's dependency edges by bumping the - reference_count of each input it reads. This is the polymorphic part of - registration: the edge set comes from the object's own kind. *) - Result.map - (fun tree -> adjust_references 1 (reference_edges object'.kind) tree) - (insert path tree) - -let with_namespace (parent : Concepts.Path.t) (namespace_label : string) - (predicate : rnt_object_kind -> bool) (name : string) (object' : rnt_object) - (tree : rnt_object_tree) : (rnt_object_tree, Concepts.Condition.condition) result = - let namespace_path = Concepts.Path.snoc parent namespace_label in - let tree_with_namespace = - match find namespace_path tree with - | None -> - register namespace_path (make_object (Namespace {label= namespace_label; predicate})) tree - | Some _ -> Ok tree - in - Result.bind tree_with_namespace (fun tree -> - register (Concepts.Path.snoc namespace_path name) object' tree ) - -let construct_multigroup parent name (mg : multigroup) tree = - with_namespace parent "multigroup" - (function Multigroup _ -> true | _ -> false) - name (make_object (Multigroup mg)) tree - -let construct_relation parent name (rel : relation) tree = - with_namespace parent "relation" - (function Relation _ -> true | _ -> false) - name (make_object (Relation rel)) tree - -let unregister (path : Concepts.Path.t) (tree : rnt_object_tree) : - (rnt_object_tree, Concepts.Condition.condition) result = - (* Read the edges before removing the node so we can undo what register did: - dropping an object releases its hold on the inputs it depended on. *) - let edges = - match find path tree with Some r -> reference_edges r.entry.kind | None -> BatFingerTree.empty - in - let rec remove components node = - match BatFingerTree.front components with - | None -> Error (Error.registry_path_not_found path) - | Some (tail, head) when BatFingerTree.is_empty tail -> - if BatMap.String.mem head node.subsequent then - Ok {node with subsequent= BatMap.String.remove head node.subsequent} - else Error (Error.registry_path_not_found path) - | Some (tail, head) -> - begin match BatMap.String.find_opt head node.subsequent with - | None -> Error (Error.registry_path_not_found path) - | Some child -> - Result.map (fun child' -> - {node with subsequent= BatMap.String.add head child' node.subsequent} ) - @@ remove tail child - end - in - Result.map (fun tree -> adjust_references (-1) edges tree) (remove path tree) - -module type MANAGER = sig - type t - - val create : branch_index_root:Concepts.Hash.hash -> registry:rnt_object_tree -> t - val branch_index_root : t -> Concepts.Hash.hash - val find : t -> Concepts.Path.t -> registry option - - val update : - t -> Concepts.Path.t -> (registry -> registry) -> (unit, Concepts.Condition.condition) result - - val register : t -> Concepts.Path.t -> rnt_object -> (unit, Concepts.Condition.condition) result - val unregister : t -> Concepts.Path.t -> (unit, Concepts.Condition.condition) result - - val with_namespace : - t -> - Concepts.Path.t -> - string -> - (rnt_object_kind -> bool) -> - string -> - rnt_object -> - (unit, Concepts.Condition.condition) result - - val construct_multigroup : - t -> Concepts.Path.t -> string -> multigroup -> (unit, Concepts.Condition.condition) result - - val construct_relation : - t -> Concepts.Path.t -> string -> relation -> (unit, Concepts.Condition.condition) result -end - -(* Keep the immutable tree operations above as the implementation core, while - this functor owns publication of the current photograph. Runtime bootstraps - the first photograph and exposes this opaque manager to its consumers. *) -module Make (Strategy : RUNTIME_STRATEGY) : MANAGER = struct - type photograph = {branch_index_root: Concepts.Hash.hash; registry: rnt_object_tree} - type t = {state: photograph Strategy.state} - - let create ~branch_index_root ~registry = {state= Strategy.create {branch_index_root; registry}} - - let branch_index_root manager = - let photograph, _ = Strategy.acquire manager.state in - photograph.branch_index_root - - let find manager path = - let photograph, _ = Strategy.acquire manager.state in - find path photograph.registry - - let modify manager transformation = - let open Utilities.Result in - let photograph, token = Strategy.acquire manager.state in - let* next, result = transformation photograph in - let* () = Strategy.publish manager.state token next in - Ok result - - let update manager path f = - modify manager (fun photograph -> - let registry = update path f photograph.registry in - Ok ({photograph with registry}, ()) ) - - let register manager path object_ = - modify manager (fun photograph -> - let open Utilities.Result in - let* registry = register path object_ photograph.registry in - Ok ({photograph with registry}, ()) ) - - let unregister manager path = - modify manager (fun photograph -> - let open Utilities.Result in - let* registry = unregister path photograph.registry in - Ok ({photograph with registry}, ()) ) - - let with_namespace manager parent namespace_label predicate name object_ = - modify manager (fun photograph -> - let open Utilities.Result in - let* registry = - with_namespace parent namespace_label predicate name object_ photograph.registry - in - Ok ({photograph with registry}, ()) ) - - let construct_multigroup manager parent name multigroup = - modify manager (fun photograph -> - let open Utilities.Result in - let* registry = construct_multigroup parent name multigroup photograph.registry in - Ok ({photograph with registry}, ()) ) - - let construct_relation manager parent name relation = - modify manager (fun photograph -> - let open Utilities.Result in - let* registry = construct_relation parent name relation photograph.registry in - Ok ({photograph with registry}, ()) ) -end diff --git a/lib/backend/storage/LMDB.ml b/lib/backend/storage/LMDB.ml index dc7f510..0f65aaf 100644 --- a/lib/backend/storage/LMDB.ml +++ b/lib/backend/storage/LMDB.ml @@ -178,14 +178,14 @@ let bytes_of_address = function let get ({tx; dbi} : transaction) (addr : address) = begin match C.mdb_get' tx dbi (bytes_of_address addr) with - | Ok x -> Ok (Some (Concepts.Representation.blob_of_bytes x)) + | Ok x -> Ok (Some (Concepts.Blob.blob_of_bytes x)) | Error e when e = C.Errors.mdb_notfound -> Ok None | Error e -> Error e end |> Result.map_error Error.lmdb_error -let put ({tx; dbi} : transaction) (addr : address) (b : Concepts.Representation.blob) = +let put ({tx; dbi} : transaction) (addr : address) (b : Concepts.Blob.t) = C.mdb_put' tx dbi (bytes_of_address addr) - (Concepts.Representation.bytes_of_blob b) + (Concepts.Blob.bytes_of_blob b) Unsigned.UInt.zero |> Result.map_error Error.lmdb_error diff --git a/lib/concepts/Blob.ml b/lib/concepts/Blob.ml new file mode 100644 index 0000000..c5d7d5c --- /dev/null +++ b/lib/concepts/Blob.ml @@ -0,0 +1,17 @@ +(* @needs Value *) + +(* The intent of this being an abstract type is to allow for switching + the implementation to one backed by a C array later on, which would + let us avoid copying when passing it through FFI boundaries. *) +type t = bytes + +let blob_of_bytes (b : bytes) = b +let bytes_of_blob (b : t) = b +let create = Bytes.create +let set = Bytes.set +let set_int64_be = Bytes.set_int64_be +let blit_string = Bytes.blit_string +let length = Bytes.length +let get = Bytes.get +let sub_string = Bytes.sub_string +let get_int64_be = Bytes.get_int64_be diff --git a/lib/concepts/Blob.mli b/lib/concepts/Blob.mli new file mode 100644 index 0000000..b7c5da3 --- /dev/null +++ b/lib/concepts/Blob.mli @@ -0,0 +1,26 @@ +(** an abstract representation of an encoded value *) +type t + +(* TODO: see the comments on Backend.Storage.LMDB *) + +(** create a blob from the data represented by bytes *) +val blob_of_bytes : bytes -> t + +(** return a bytes containing the data underlying a blob *) +val bytes_of_blob : t -> bytes + +val create : int -> t + +val set : t -> int -> char -> unit + +val set_int64_be : t -> int -> int64 -> unit + +val blit_string : string -> int -> t -> int -> int -> unit + +val length : t -> int + +val get : t -> int -> char + +val sub_string : t -> int -> int -> string + +val get_int64_be : t -> int -> int64 diff --git a/lib/concepts/Branch.ml b/lib/concepts/Branch.ml deleted file mode 100644 index cd4213b..0000000 --- a/lib/concepts/Branch.ml +++ /dev/null @@ -1,49 +0,0 @@ -type address = Hash.hash - -type t = - { name: string; - target: address } - -module Field = struct - let name = "name" - let target = "target" -end - -module Error = struct - open Condition - - let malformed_branch () = - condition "branch-malformed" "A branch representation did not conform to what was expected" - empty - - let malformed_hash length = - condition "branch-malformed-hash" "A branch target root was not a valid hash" - ("length" |=| Value.Integer length) -end - -let make ~name ~target = {name; target} - -let name branch = branch.name -let target branch = branch.target - -module Body = struct - type nonrec t = t - - let tag = 'b' - let malformed = Error.malformed_branch - - let equal left right = - left.name = right.name && Hash.hash_equals left.target right.target - - let fields branch = - [ Field.name, Object.Field.string branch.name; - Field.target, Object.Field.address branch.target ] - - let of_fields data = - let open Utilities.Result in - let* name = Object.Field.require_string Field.name data in - let* target = Object.Field.require_address ~malformed:Error.malformed_hash Field.target data in - Ok {name; target} -end - -include (Object.Codec.Make (Body) : Object.S with type t := t) diff --git a/lib/concepts/Branch.mli b/lib/concepts/Branch.mli deleted file mode 100644 index 0e7e9f9..0000000 --- a/lib/concepts/Branch.mli +++ /dev/null @@ -1,9 +0,0 @@ -type t -type address = Hash.hash - -include Object.S with type t := t - -val make : name:string -> target:address -> t - -val name : t -> string -val target : t -> address diff --git a/lib/concepts/BranchState.ml b/lib/concepts/BranchState.ml deleted file mode 100644 index e8c6636..0000000 --- a/lib/concepts/BranchState.ml +++ /dev/null @@ -1,87 +0,0 @@ -type address = Hash.hash - -(* A branch state records durable branch data only. The runtime registry paths - mounted around it, such as /system/branches/master, are derived at - initialization and should not be persisted as part of [current]. *) -type t = {current: address; history: address; tip: address option} - -module Field = struct - let current = "current" - let history = "history" - let tip = "tip" -end - -module Error = struct - open Condition - - let malformed_branch_state () = - condition "branch-state-malformed" - "A branch state representation did not conform to what was expected" empty - - let malformed_hash length = - condition "branch-state-malformed-hash" "A branch state address was not a valid hash" - ("length" |=| Value.Integer length) -end - -let make ~current ~history ~tip = {current; history; tip} -let current branch_state = branch_state.current -let history branch_state = branch_state.history -let tip branch_state = branch_state.tip -let address_bencode address = Object.Field.address address - -let address_option_bencode = function - | None -> Codec.Bencode.List [] - | Some address -> Codec.Bencode.List [address_bencode address] - -let require_address_bencode = function - | Codec.Bencode.String raw -> - if String.length raw = Hash.size then Ok (Hash.of_raw_string raw) - else Error (Error.malformed_hash (String.length raw)) - | _ -> Error (Error.malformed_branch_state ()) - -let require_address_option key data = - let open Utilities.Result in - let* value = Codec.Bencode.field key data in - let* entries = Codec.Bencode.as_list value in - match entries with - | [] -> Ok None - | [value] -> - let* address = require_address_bencode value in - Ok (Some address) - | _ -> Error (Error.malformed_branch_state ()) - -let equal_address_option left right = - match left, right with - | None, None -> true - | Some left, Some right -> Hash.hash_equals left right - | _ -> false - -module Body = struct - type nonrec t = t - - let tag = 's' - let malformed = Error.malformed_branch_state - - let equal left right = - Hash.hash_equals left.current right.current - && Hash.hash_equals left.history right.history - && equal_address_option left.tip right.tip - - let fields branch_state = - [ Field.current, address_bencode branch_state.current; - Field.history, address_bencode branch_state.history; - Field.tip, address_option_bencode branch_state.tip ] - - let of_fields data = - let open Utilities.Result in - let* current = - Object.Field.require_address ~malformed:Error.malformed_hash Field.current data - in - let* history = - Object.Field.require_address ~malformed:Error.malformed_hash Field.history data - in - let* tip = require_address_option Field.tip data in - Ok {current; history; tip} -end - -include (Object.Codec.Make (Body) : Object.S with type t := t) diff --git a/lib/concepts/BranchState.mli b/lib/concepts/BranchState.mli deleted file mode 100644 index 45792cc..0000000 --- a/lib/concepts/BranchState.mli +++ /dev/null @@ -1,17 +0,0 @@ -type t -type address = Hash.hash - -include Object.S with type t := t - -(** Durable state of one branch head. - - [current] is the branch-visible catalog root, not the runtime namespace - rooted at [/system]. Runtime scaffolding is rebuilt during initialization. - [history] is the ordered commit-stream tree root. [tip] is absent until the - first real commit, so initialization does not create a synthetic commit just - to make the branch non-empty. *) -val make : current:address -> history:address -> tip:address option -> t - -val current : t -> address -val history : t -> address -val tip : t -> address option diff --git a/lib/concepts/Codec.ml b/lib/concepts/Encoding.ml index 758d718..121e98d 100644 --- a/lib/concepts/Codec.ml +++ b/lib/concepts/Encoding.ml @@ -1,3 +1,33 @@ +(* A blob is a one-byte constructor tag followed by its payload. The + tag makes the encoding self-describing so [value_of_blob] can + recover the constructor: + - String ['\000'] ++ raw utf-8 bytes + - Integer ['\001'] ++ 8-byte big-endian int64 *) +let tag_string = '\000' +let tag_integer = '\001' + +let blob_of_value = function + | Value.String s -> + let b = Blob.create (1 + String.length s) in + Blob.set b 0 tag_string; + Blob.blit_string s 0 b 1 (String.length s); + b + | Value.Integer n -> + let b = Blob.create 9 in + Blob.set b 0 tag_integer; + Blob.set_int64_be b 1 (Int64.of_int n); + b + +let value_of_blob (b : Blob.t) = + let n = Blob.length b in + if n = 0 then invalid_arg "value_of_blob: empty blob"; + match Blob.get b 0 with + | c when c = tag_string -> Value.String (Blob.sub_string b 1 (n - 1)) + | c when c = tag_integer -> + if n <> 9 then invalid_arg "value_of_blob: malformed integer payload"; + Value.Integer (Int64.to_int (Blob.get_int64_be b 1)) + | c -> invalid_arg (Printf.sprintf "value_of_blob: unknown tag %C" c) + module Error = struct open Condition @@ -162,8 +192,8 @@ module Bencode = struct if !pos <> n then Error Error.trailing_bytes else Ok value - let to_blob x = to_bytes x |> Representation.blob_of_bytes - let of_blob b = Representation.bytes_of_blob b |> of_bytes + let to_blob x = to_bytes x |> Blob.blob_of_bytes + let of_blob b = Blob.bytes_of_blob b |> of_bytes let with_tag t = function | Tagged (t', v) -> @@ -180,3 +210,62 @@ module Bencode = struct | None -> Error (Error.missing_field key) ) | _ -> Error (Error.type_mismatch ~expected:"dict") end + +module Field = struct + let string value = Bencode.String value + let address address = Bencode.String (Hash.to_raw_string address) + + let require_string key data = + Bencode.field key data |> Utilities.Result.fmap Bencode.as_string + + let require_address ~malformed key data = + let open Utilities.Result in + let* raw = require_string key data in + if String.length raw = Hash.size then Ok (Hash.of_raw_string raw) + else Error (malformed (String.length raw)) +end + +module Record = struct + module type S = sig + type t + + val equal : t -> t -> bool + + val to_bencode : t -> Bencode.t + val of_bencode : Bencode.t -> (t, Condition.condition) result + + val to_blob : t -> Blob.t + val of_blob : Blob.t -> (t, Condition.condition) result + + val to_bytes : t -> bytes + val of_bytes : bytes -> (t, Condition.condition) result + end + + module type BODY = sig + type t + + val tag : char + val malformed : unit -> Condition.condition + val equal : t -> t -> bool + val fields : t -> (string * Bencode.t) list + val of_fields : Bencode.t -> (t, Condition.condition) result + end + + module Make (B : BODY) = struct + type t = B.t + + let equal = B.equal + let to_bencode object_ = Bencode.Tagged (B.tag, Bencode.Dict (B.fields object_)) + + let of_bencode = function + | Bencode.Tagged (tag, (Bencode.Dict _ as data)) when Char.equal tag B.tag -> + B.of_fields data + | _ -> Error (B.malformed ()) + + let to_blob object_ = to_bencode object_ |> Bencode.to_blob + let of_blob blob = Bencode.of_blob blob |> Utilities.Result.fmap of_bencode + + let to_bytes object_ = to_blob object_ |> Blob.bytes_of_blob + let of_bytes bytes = Bencode.of_bytes bytes |> Utilities.Result.fmap of_bencode + end +end diff --git a/lib/concepts/Hash.ml b/lib/concepts/Hash.ml index 62c7789..ae0a178 100644 --- a/lib/concepts/Hash.ml +++ b/lib/concepts/Hash.ml @@ -7,12 +7,9 @@ let size = 256/8 let compare h1 h2 = Digestif.SHA256.unsafe_compare h1 h2 |> Ordering.of_int -let hash_of_value (v : Value.value) = - Representation.(blob_of_value v |> bytes_of_blob) |> Digestif.SHA256.digest_bytes - let hash_of_bytes bytes = Digestif.SHA256.digest_bytes bytes -let hash_of_blob blob = Representation.bytes_of_blob blob |> Digestif.SHA256.digest_bytes +let hash_of_blob blob = Blob.bytes_of_blob blob |> Digestif.SHA256.digest_bytes let to_raw_string hash = Digestif.SHA256.to_raw_string hash diff --git a/lib/concepts/Hash.mli b/lib/concepts/Hash.mli index f40d9aa..b3ae2dc 100644 --- a/lib/concepts/Hash.mli +++ b/lib/concepts/Hash.mli @@ -4,14 +4,11 @@ type hash (** the size of a hash, in bytes *) val size : int -(** given a value, compute it's hash *) -val hash_of_value : Value.value -> hash - (** given a bag of bytes, compute it's hash *) val hash_of_bytes : bytes -> hash (** given a blob, compute it's hash *) -val hash_of_blob : Representation.blob -> hash +val hash_of_blob : Blob.t -> hash (** given a hash, return a representation of it as a string (/not/ the usual hex representation!) *) val to_raw_string : hash -> string diff --git a/lib/concepts/Multigroup.ml b/lib/concepts/Multigroup.ml deleted file mode 100644 index 863cd26..0000000 --- a/lib/concepts/Multigroup.ml +++ /dev/null @@ -1,51 +0,0 @@ -type address = Hash.hash - -type t = - { name: string; - relations: address } - -module Field = struct - let name = "name" - let relations = "relations" -end - -module Error = struct - open Condition - - let malformed_multigroup () = - condition "multigroup-malformed" - "A multigroup representation did not conform to what was expected" empty - - let malformed_hash length = - condition "multigroup-malformed-hash" "A multigroup relation root was not a valid hash" - ("length" |=| Value.Integer length) -end - -let make ~name ~relations = {name; relations} - -let name multigroup = multigroup.name -let relations multigroup = multigroup.relations - -module Body = struct - type nonrec t = t - - let tag = 'm' - let malformed = Error.malformed_multigroup - - let equal left right = - left.name = right.name && Hash.hash_equals left.relations right.relations - - let fields multigroup = - [ Field.name, Object.Field.string multigroup.name; - Field.relations, Object.Field.address multigroup.relations ] - - let of_fields data = - let open Utilities.Result in - let* name = Object.Field.require_string Field.name data in - let* relations = - Object.Field.require_address ~malformed:Error.malformed_hash Field.relations data - in - Ok {name; relations} -end - -include (Object.Codec.Make (Body) : Object.S with type t := t) diff --git a/lib/concepts/Multigroup.mli b/lib/concepts/Multigroup.mli deleted file mode 100644 index 1a76dce..0000000 --- a/lib/concepts/Multigroup.mli +++ /dev/null @@ -1,9 +0,0 @@ -type t -type address = Hash.hash - -include Object.S with type t := t - -val make : name:string -> relations:address -> t - -val name : t -> string -val relations : t -> address diff --git a/lib/concepts/Object.ml b/lib/concepts/Object.ml deleted file mode 100644 index 22fb14a..0000000 --- a/lib/concepts/Object.ml +++ /dev/null @@ -1,64 +0,0 @@ -type bencode = Codec.Bencode.t - -module Bencode = Codec.Bencode - -module type S = sig - type t - - val equal : t -> t -> bool - - val to_bencode : t -> bencode - val of_bencode : bencode -> (t, Condition.condition) result - - val to_blob : t -> Representation.blob - val of_blob : Representation.blob -> (t, Condition.condition) result - - val to_bytes : t -> bytes - val of_bytes : bytes -> (t, Condition.condition) result -end - -module type OBJECT = S - -module Field = struct - let string value = Bencode.String value - let address address = Bencode.String (Hash.to_raw_string address) - - let require_string key data = - Codec.Bencode.field key data |> Utilities.Result.fmap Codec.Bencode.as_string - - let require_address ~malformed key data = - let open Utilities.Result in - let* raw = require_string key data in - if String.length raw = Hash.size then Ok (Hash.of_raw_string raw) - else Error (malformed (String.length raw)) -end - -module Codec = struct - module type BODY = sig - type t - - val tag : char - val malformed : unit -> Condition.condition - val equal : t -> t -> bool - val fields : t -> (string * bencode) list - val of_fields : bencode -> (t, Condition.condition) result - end - - module Make (B : BODY) = struct - type t = B.t - - let equal = B.equal - let to_bencode object_ = Bencode.Tagged (B.tag, Bencode.Dict (B.fields object_)) - - let of_bencode = function - | Bencode.Tagged (tag, (Bencode.Dict _ as data)) when Char.equal tag B.tag -> - B.of_fields data - | _ -> Error (B.malformed ()) - - let to_blob object_ = to_bencode object_ |> Bencode.to_blob - let of_blob blob = Bencode.of_blob blob |> Utilities.Result.fmap of_bencode - - let to_bytes object_ = to_blob object_ |> Representation.bytes_of_blob - let of_bytes bytes = Bencode.of_bytes bytes |> Utilities.Result.fmap of_bencode - end -end diff --git a/lib/concepts/Object.mli b/lib/concepts/Object.mli deleted file mode 100644 index e132673..0000000 --- a/lib/concepts/Object.mli +++ /dev/null @@ -1,45 +0,0 @@ -type bencode = Codec.Bencode.t - -module type S = sig - type t - - val equal : t -> t -> bool - - val to_bencode : t -> bencode - val of_bencode : bencode -> (t, Condition.condition) result - - val to_blob : t -> Representation.blob - val of_blob : Representation.blob -> (t, Condition.condition) result - - val to_bytes : t -> bytes - val of_bytes : bytes -> (t, Condition.condition) result -end - -module type OBJECT = S - -module Field : sig - val string : string -> bencode - val address : Hash.hash -> bencode - - val require_string : string -> bencode -> (string, Condition.condition) result - - val require_address : - malformed:(int -> Condition.condition) -> - string -> - bencode -> - (Hash.hash, Condition.condition) result -end - -module Codec : sig - module type BODY = sig - type t - - val tag : char - val malformed : unit -> Condition.condition - val equal : t -> t -> bool - val fields : t -> (string * bencode) list - val of_fields : bencode -> (t, Condition.condition) result - end - - module Make (B : BODY) : S with type t = B.t -end diff --git a/lib/concepts/Ordering.mli b/lib/concepts/Ordering.mli deleted file mode 100644 index ab8a3f4..0000000 --- a/lib/concepts/Ordering.mli +++ /dev/null @@ -1,3 +0,0 @@ -type ordering = Equal | Smaller | Greater - -val of_int : int -> ordering diff --git a/lib/concepts/Path.ml b/lib/concepts/Path.ml deleted file mode 100644 index c751301..0000000 --- a/lib/concepts/Path.ml +++ /dev/null @@ -1,16 +0,0 @@ -type t = string BatFingerTree.t - -let empty : t = BatFingerTree.empty -let of_list (components : string list) : t = BatFingerTree.of_list components -let to_list (path : t) : string list = BatFingerTree.to_list path -let snoc (path : t) (component : string) : t = BatFingerTree.snoc path component -let to_string (path : t) : string = String.concat "/" (to_list path) - -let is_prefix ~(prefix : t) (path : t) : bool = - let rec walk prefix path = - match prefix, path with - | [], _ -> true - | p :: prefix, x :: path -> p = x && walk prefix path - | _ :: _, [] -> false - in - walk (to_list prefix) (to_list path) diff --git a/lib/concepts/Path.mli b/lib/concepts/Path.mli deleted file mode 100644 index bec4221..0000000 --- a/lib/concepts/Path.mli +++ /dev/null @@ -1,8 +0,0 @@ -type t = string BatFingerTree.t - -val empty : t -val of_list : string list -> t -val to_list : t -> string list -val snoc : t -> string -> t -val to_string : t -> string -val is_prefix : prefix:t -> t -> bool diff --git a/lib/concepts/Relation.ml b/lib/concepts/Relation.ml deleted file mode 100644 index a4fb341..0000000 --- a/lib/concepts/Relation.ml +++ /dev/null @@ -1,81 +0,0 @@ -type address = Hash.hash -type schema = string BatMap.String.t - -type t = - { name: string; - tuples: address; - schema: schema } - -module Field = struct - let name = "name" - let tuples = "tuples" - let schema = "schema" -end - -module Error = struct - open Condition - - let malformed_relation () = - condition "relation-malformed" "A relation representation did not conform to what was expected" - empty - - let malformed_hash length = - condition "relation-malformed-hash" "A relation tuple root was not a valid hash" - ("length" |=| Value.Integer length) -end - -let make ~name ~tuples ~schema = {name; tuples; schema} - -let name relation = relation.name -let tuples relation = relation.tuples -let schema relation = relation.schema - -let schema_empty = BatMap.String.empty - -let schema_of_list fields = - List.fold_left (fun acc (name, domain) -> BatMap.String.add name domain acc) schema_empty - fields - -let schema_to_list schema = BatMap.String.bindings schema - -let schema_to_bencode schema = - Codec.Bencode.Dict - (schema_to_list schema - |> List.map (fun (name, domain) -> name, Codec.Bencode.String domain) ) - -let schema_of_bencode value = - let open Utilities.Result in - let* fields = Codec.Bencode.as_dict value in - fields - |> List.map (fun (name, domain) -> - let* domain = Codec.Bencode.as_string domain in - Ok (name, domain) ) - |> sequence - |> Result.map schema_of_list - -module Body = struct - type nonrec t = t - - let tag = 'r' - let malformed = Error.malformed_relation - - let equal left right = - left.name = right.name - && Hash.hash_equals left.tuples right.tuples - && BatMap.String.equal String.equal left.schema right.schema - - let fields relation = - [ Field.name, Object.Field.string relation.name; - Field.schema, schema_to_bencode relation.schema; - Field.tuples, Object.Field.address relation.tuples ] - - let of_fields data = - let open Utilities.Result in - let* name = Object.Field.require_string Field.name data in - let* tuples = Object.Field.require_address ~malformed:Error.malformed_hash Field.tuples data in - let* schema_data = Codec.Bencode.field Field.schema data in - let* schema = schema_of_bencode schema_data in - Ok {name; tuples; schema} -end - -include (Object.Codec.Make (Body) : Object.S with type t := t) diff --git a/lib/concepts/Relation.mli b/lib/concepts/Relation.mli deleted file mode 100644 index 5319a3d..0000000 --- a/lib/concepts/Relation.mli +++ /dev/null @@ -1,15 +0,0 @@ -type t -type address = Hash.hash -type schema - -include Object.S with type t := t - -val make : name:string -> tuples:address -> schema:schema -> t - -val name : t -> string -val tuples : t -> address -val schema : t -> schema - -val schema_empty : schema -val schema_of_list : (string * string) list -> schema -val schema_to_list : schema -> (string * string) list diff --git a/lib/concepts/Representation.ml b/lib/concepts/Representation.ml deleted file mode 100644 index 12c3624..0000000 --- a/lib/concepts/Representation.ml +++ /dev/null @@ -1,36 +0,0 @@ -(* @needs Value *) - -type blob = bytes - -let blob_of_bytes (b : bytes) = b -let bytes_of_blob (b : blob) = b - -(* A blob is a one-byte constructor tag followed by its payload. The - tag makes the encoding self-describing so [value_of_blob] can - recover the constructor: - - String ['\000'] ++ raw utf-8 bytes - - Integer ['\001'] ++ 8-byte big-endian int64 *) -let tag_string = '\000' -let tag_integer = '\001' - -let blob_of_value = function - | Value.String s -> - let b = Bytes.create (1 + String.length s) in - Bytes.set b 0 tag_string; - Bytes.blit_string s 0 b 1 (String.length s); - b - | Value.Integer n -> - let b = Bytes.create 9 in - Bytes.set b 0 tag_integer; - Bytes.set_int64_be b 1 (Int64.of_int n); - b - -let value_of_blob (b : blob) = - let n = Bytes.length b in - if n = 0 then invalid_arg "value_of_blob: empty blob"; - match Bytes.get b 0 with - | c when c = tag_string -> Value.String (Bytes.sub_string b 1 (n - 1)) - | c when c = tag_integer -> - if n <> 9 then invalid_arg "value_of_blob: malformed integer payload"; - Value.Integer (Int64.to_int (Bytes.get_int64_be b 1)) - | c -> invalid_arg (Printf.sprintf "value_of_blob: unknown tag %C" c) diff --git a/lib/concepts/Representation.mli b/lib/concepts/Representation.mli deleted file mode 100644 index 21c43a4..0000000 --- a/lib/concepts/Representation.mli +++ /dev/null @@ -1,16 +0,0 @@ -(** an abstract representation of an encoded value *) -type blob - -(** encode a blob into a value *) -val blob_of_value : Value.value -> blob - -(** decode a value from a blob *) -val value_of_blob : blob -> Value.value - -(* TODO: see the comments on Backend.Storage.LMDB *) - -(** create a blob from the data represented by bytes *) -val blob_of_bytes : bytes -> blob - -(** return a bytes containing the data underlying a blob *) -val bytes_of_blob : blob -> bytes diff --git a/lib/concepts/Tuple.ml b/lib/concepts/Tuple.ml deleted file mode 100644 index 8fac426..0000000 --- a/lib/concepts/Tuple.ml +++ /dev/null @@ -1,48 +0,0 @@ -(* @needs Value *) - -module AttributeMap = BatMap.String - -(** A tuple: a finite map from attribute name to attribute. *) -type t = Value.value AttributeMap.t - -(** [empty] The tuple with no attributes. *) -let empty : t = AttributeMap.empty - -(** [access name t] Looks up the attribute bound to [name] in [t]. - @param name attribute name to look up. - @param t tuple to search. - @return the attribute, or [None] when [name] is unbound. *) -let access (name : string) (t : t) : Value.value option = AttributeMap.find_opt name t - -(** [merge left right] Unions two tuples. Shared attributes take the - [left] value; one-sided attributes are kept. Precondition: shared - attributes agree (the natural-join matcher guarantees this), so the - [left] bias is never observable. - @param left first tuple. - @param right second tuple. - @return the merged tuple. *) -let merge (left : t) (right : t) : t = - let merger _ (left : Value.value option) (right : Value.value option) : Value.value option = - match left, right with (Some _ as v), _ | None, (Some _ as v) -> v | None, None -> None - in - AttributeMap.merge merger left right - -(** [project keep t] Keeps only the attributes of [t] whose names are - in [keep]. - @param keep set of attribute names to retain. - @param t tuple to project. - @return the projected tuple. *) -let project (keep : BatSet.String.t) (t : t) : t = - AttributeMap.filter (fun name _ -> BatSet.String.mem name keep) t - -(** [rename mapping t] Renames the attributes of [t] through - [mapping]; names absent from [mapping] are left unchanged. - @param mapping map from old name to new name. - @param t tuple to rename. - @return the renamed tuple. *) -let rename (mapping : string BatMap.String.t) (t : t) : t = - AttributeMap.fold - (fun name attr acc -> - let name = BatMap.String.find_default name name mapping in - AttributeMap.add name attr acc ) - t AttributeMap.empty diff --git a/lib/concepts/Tuple.mli b/lib/concepts/Tuple.mli deleted file mode 100644 index 07f7a24..0000000 --- a/lib/concepts/Tuple.mli +++ /dev/null @@ -1,9 +0,0 @@ -module AttributeMap = BatMap.String - -type t = Value.value AttributeMap.t - -val empty : t -val access : string -> t -> Value.value option -val merge : t -> t -> t -val project : BatSet.String.t -> t -> t -val rename : string BatMap.String.t -> t -> t diff --git a/lib/kernel/BranchManager.ml b/lib/kernel/BranchManager.ml index 80e32a4..03a2765 100644 --- a/lib/kernel/BranchManager.ml +++ b/lib/kernel/BranchManager.ml @@ -1,5 +1,3 @@ -type branch = string - module Error = struct open Concepts.Condition @@ -7,6 +5,10 @@ module Error = struct condition "invalid-root" "The root hash for the database state is missing from the backend. Either your storage is corrupted, or this is a bug in RNT!" ("hash" |=| (Concepts.Value.String (Concepts.Hash.to_hum_string head))) + let no_such_branch branch_name = + condition "no-such-branch" "A branch with the specified name was not found" + ("branch" |=| Concepts.Value.String branch_name) + let comparison_failed branch_name reference head = condition "comparison-failed" "The HEAD of the branch did not match what was expected" ("branch" |=| Concepts.Value.String branch_name & @@ -44,16 +46,18 @@ module Make (S : Abstract.Storage.STORAGE) = struct let head = Atomic.get head in M.lookup tx branch_name head) - let update ({ storage; head; label } as manager) branch_name reference new_branch = + let update { storage; head; label } branch_name reference new_branch = let open Utilities.Result in let* _ = SI.with_transaction storage (fun tx -> Utilities.Atomic.mswap head (fun head -> - let* branch = M.lookup tx branch_name head in + let* branch = M.lookup tx branch_name head + |> Result.map (Option.to_result ~none:(Error.no_such_branch branch_name)) + |> Result.join in if branch = reference then let* new_head = M.insert tx label new_branch head in - new_head + Ok new_head else - Error.comparison_failed branch_name reference branch)) in + Error (Error.comparison_failed branch_name reference branch))) in Ok () end diff --git a/lib/kernel/Merkle.ml b/lib/kernel/Merkle.ml index 60a10a7..c2c2932 100644 --- a/lib/kernel/Merkle.ml +++ b/lib/kernel/Merkle.ml @@ -1,8 +1,8 @@ module type VALUE = sig type t - val encode : t -> Concepts.Representation.blob - val decode : Concepts.Representation.blob -> (t, Concepts.Condition.condition) result + val encode : t -> Concepts.Blob.t + val decode : Concepts.Blob.t -> (t, Concepts.Condition.condition) result end module type KEY = sig @@ -65,12 +65,12 @@ module Make : TREE = functor (S : Abstract.Storage.STORAGE) (K : KEY) -> struct | Trunk { keys; _ } -> keys let of_bencode = - let open Concepts.Codec.Bencode in + let open Concepts.Encoding.Bencode in let open Utilities.Result in (* This is terrible *) let decode_key t = as_string t |> Result.map String.to_bytes - |> Result.map Concepts.Representation.blob_of_bytes + |> Result.map Concepts.Blob.blob_of_bytes |> fmap K.decode in let decode_value t = as_string t |> Result.map Concepts.Hash.of_raw_string in let decode_list f data = data @@ -89,14 +89,14 @@ module Make : TREE = functor (S : Abstract.Storage.STORAGE) (K : KEY) -> struct Ok (Trunk { keys; children }) | _ -> Error (Error.malformed_node ()) - let from_blob blob = Concepts.Codec.Bencode.of_blob blob + let from_blob blob = Concepts.Encoding.Bencode.of_blob blob |> Utilities.Result.fmap of_bencode let to_bencode = - let open Concepts.Codec.Bencode in + let open Concepts.Encoding.Bencode in (* Ditto. *) let bencode_key k = K.encode k - |> Concepts.Representation.bytes_of_blob + |> Concepts.Blob.bytes_of_blob |> String.of_bytes |> (fun s -> String s) in let bencode_hash h = String (Concepts.Hash.to_raw_string h) in @@ -108,7 +108,7 @@ module Make : TREE = functor (S : Abstract.Storage.STORAGE) (K : KEY) -> struct Tagged ('#', Dict [("keys", List (BatFingerTree.to_list keys |> List.map bencode_key)); ("children", List (BatFingerTree.to_list children |> List.map bencode_hash))]) - let to_blob node = to_bencode node |> Concepts.Codec.Bencode.to_blob + let to_blob node = to_bencode node |> Concepts.Encoding.Bencode.to_blob (* TODO: we should probably cache this inside the node itself rather than recalculating it every time. We could also allow the user to @@ -216,7 +216,7 @@ module Make : TREE = functor (S : Abstract.Storage.STORAGE) (K : KEY) -> struct BatFingerTree.iter (fun k -> K.encode k - |> Concepts.Representation.bytes_of_blob + |> Concepts.Blob.bytes_of_blob |> Buffer.add_bytes buffer) ks; Concepts.Hash.hash_of_bytes (Buffer.to_bytes buffer) @@ -343,7 +343,7 @@ end module StringKey : KEY with type t = string = struct type t = string - let encode s = String.to_bytes s |> Concepts.Representation.blob_of_bytes + let encode s = String.to_bytes s |> Concepts.Blob.blob_of_bytes let compare s1 s2 = String.compare s1 s2 |> Concepts.Ordering.of_int - let decode b = Concepts.Representation.bytes_of_blob b |> String.of_bytes |> Result.ok + let decode b = Concepts.Blob.bytes_of_blob b |> String.of_bytes |> Result.ok end diff --git a/lib/kernel/Runtime.ml b/lib/kernel/Runtime.ml deleted file mode 100644 index aa69791..0000000 --- a/lib/kernel/Runtime.ml +++ /dev/null @@ -1,45 +0,0 @@ -module Error = struct - open Concepts.Condition - - let registry_conflict () = - condition "registry-object-update-conflict" "Failed to update the in-memory object registry" - empty -end - -module CAS : Backend.Managers.Object.RUNTIME_STRATEGY = struct - type 'a state = 'a Atomic.t - type 'a token = 'a - - let create = Atomic.make - - let acquire state = - let photograph = Atomic.get state in - photograph, photograph - - let publish state token next = - if Atomic.compare_and_set state token next then Ok () else Error (Error.registry_conflict ()) -end - -(* module MVCC : REGISTRY_STRATEGY = struct end *) -(* module RCU : REGISTRY_STRATEGY = struct end *) - -module Make (Strategy : Backend.Managers.Object.RUNTIME_STRATEGY) (Store : Abstract.Storage.STORAGE) = -struct - module Init = Initialization.Make (Store) - module Objects = Backend.Managers.Object.Make (Strategy) - - type t = {connection: Store.connection; objects: Objects.t} - - let initialize configuration : (t, Concepts.Condition.condition) result = - let open Utilities.Result in - let* connection = Store.connect configuration in - let* branch_index_root = Init.initialize connection in - (* Registry reconstruction from the branch index is the loader boundary. - Until that loader exists, publish only the permanent /system namespace; - importantly, the discovered root remains part of the photograph. *) - let objects = Objects.create ~branch_index_root ~registry:Backend.Managers.Object.root in - Ok {connection; objects} - - let connection runtime = runtime.connection - let objects runtime = runtime.objects -end diff --git a/lib/kernel/Storage.mli b/lib/kernel/Storage.mli index 3ef1ffc..1148fba 100644 --- a/lib/kernel/Storage.mli +++ b/lib/kernel/Storage.mli @@ -1,5 +1,5 @@ module Make : functor (S : Abstract.Storage.STORAGE) -> sig val finish : S.transaction -> ('a, Concepts.Condition.condition) result -> ('a, Concepts.Condition.condition) result val with_transaction : S.connection -> (S.transaction -> ('a, Concepts.Condition.condition) result) -> ('a, Concepts.Condition.condition) result - val store_blob : S.transaction -> Concepts.Representation.blob -> (Concepts.Hash.hash, Concepts.Condition.condition) result + val store_blob : S.transaction -> Concepts.Blob.t -> (Concepts.Hash.hash, Concepts.Condition.condition) result end diff --git a/test/test_rnt.ml b/test/test_rnt.ml index d46be1e..c4fbbaf 100644 --- a/test/test_rnt.ml +++ b/test/test_rnt.ml @@ -1,7 +1,4 @@ let all_suites = - Unit.Concepts.Serialization.suites () - @ Unit.Backend.Storage.suites () - @ Unit.Backend.Lifecycle.suites () - @ Unit.Kernel.Merkle.suites () + Unit.Backend.Storage.suites () let () = Alcotest.run "RNT" all_suites diff --git a/test/unit/backend/Lifecycle.ml b/test/unit/backend/Lifecycle.ml deleted file mode 100644 index 3e5b3e9..0000000 --- a/test/unit/backend/Lifecycle.ml +++ /dev/null @@ -1,147 +0,0 @@ -module Object = Rnt.Backend.Managers.Object -module Lifecycle = Rnt.Backend.Managers.Lifecycle -module Path = Rnt.Concepts.Path - -(* Small builders so the tests read like the invariants they check. *) - -let path segments = Path.of_list segments -let relation name = Object.make_object (Object.Relation {merkle_root= name}) - -let session () = - Object.make_object (Object.Session {connection_context= (); branch_overrides= BatMap.String.empty}) - -let branch name = Object.make_object (Object.Branch {name; target_hash= "hash"}) -let namespace label = Object.make_object (Object.Namespace {label; predicate= (fun _ -> true)}) -let dependencies paths = List.fold_left BatFingerTree.snoc BatFingerTree.empty paths - -let ephemeral name deps = - Object.make_object (Object.EphemeralRelation {merkle_root= name; dependencies= dependencies deps}) - -let register_exn tree p object' = Helpers.condition_as_failure (Object.register p object' tree) -let unregister_exn tree p = Helpers.condition_as_failure (Object.unregister p tree) -let collect_exn tree p = Helpers.condition_as_failure (Lifecycle.collect tree p) - -let reference_count tree p = - match Object.find p tree with Some r -> r.Object.reference_count | None -> -1 - -let present tree p = Object.find p tree <> None - -(* An ephemeral relation holds its inputs resident. Registering it raises the - input's reference_count; unregistering it lowers it again. This is the - distinction between reference counting (real edges) and pinning. *) -let test_edges_track_dependents () = - let tree = register_exn Object.root (path ["r1"]) (relation "r1") in - let tree = register_exn tree (path ["er1"]) (ephemeral "er1" [path ["r1"]]) in - Alcotest.(check int) - "dependent raises the input's reference count" 1 - (reference_count tree (path ["r1"])); - let tree = unregister_exn tree (path ["er1"]) in - Alcotest.(check int) - "removing the dependent releases the input" 0 - (reference_count tree (path ["r1"])) - -(* The four gates of eligibility, each shown to block on its own. *) -let test_eligibility_gates () = - let tree = register_exn Object.root (path ["r1"]) (relation "r1") in - Alcotest.(check bool) - "a fresh durable object is collectable" true - (Lifecycle.is_eligible_for_gc tree (path ["r1"])); - Alcotest.(check bool) - "an open handle blocks collection" false - (Lifecycle.is_eligible_for_gc (Lifecycle.monitor tree (path ["r1"])) (path ["r1"])); - Alcotest.(check bool) - "a pin blocks collection" false - (Lifecycle.is_eligible_for_gc (Lifecycle.pin tree (path ["r1"])) (path ["r1"])); - let with_branch = register_exn Object.root (path ["b1"]) (branch "b1") in - Alcotest.(check bool) - "a branch is exempt even with zero counts" false - (Lifecycle.is_eligible_for_gc with_branch (path ["b1"])) - -(* Collecting a dependent cascades into the inputs it releases, and the input - cannot be collected first while the dependent is alive. *) -let test_cascade_follows_edges () = - let tree = register_exn Object.root (path ["r1"]) (relation "r1") in - let tree = register_exn tree (path ["er1"]) (ephemeral "er1" [path ["r1"]]) in - Alcotest.(check bool) - "a live dependent keeps its input" false - (Lifecycle.is_eligible_for_gc tree (path ["r1"])); - let tree, disposals = collect_exn tree (path ["er1"]) in - Alcotest.(check bool) "the dependent is collected" false (present tree (path ["er1"])); - Alcotest.(check bool) "the released input is cascaded out" false (present tree (path ["r1"])); - Alcotest.(check int) "durable collection needs no disposal" 0 (BatFingerTree.size disposals) - -(* A pin overrides the cascade: the input stays even after its dependent goes. *) -let test_pin_survives_cascade () = - let tree = register_exn Object.root (path ["r1"]) (relation "r1") in - let tree = register_exn tree (path ["er1"]) (ephemeral "er1" [path ["r1"]]) in - let tree = Lifecycle.pin tree (path ["r1"]) in - let tree, _ = collect_exn tree (path ["er1"]) in - Alcotest.(check bool) "the dependent is still collected" false (present tree (path ["er1"])); - Alcotest.(check bool) "the pinned input survives" true (present tree (path ["r1"])) - -(* Collecting a runtime object surfaces a disposal for the caller to run, - because there is no durable form to rehydrate from. *) -let test_runtime_collection_surfaces_disposal () = - let tree = register_exn Object.root (path ["s1"]) (session ()) in - let tree, disposals = collect_exn tree (path ["s1"]) in - Alcotest.(check bool) "the session is removed" false (present tree (path ["s1"])); - match BatFingerTree.front disposals with - | Some (rest, {Lifecycle.kind= Object.Session _; _}) when BatFingerTree.is_empty rest -> () - | _ -> Alcotest.fail "expected exactly one session disposal" - -(* A namespace with objects under it is scaffolding, so it is kept rather than - collected, and this is not an error. *) -let test_populated_namespace_is_kept () = - let tree = register_exn Object.root (path ["ns"]) (namespace "ns") in - let tree = register_exn tree (path ["ns"; "r1"]) (relation "r1") in - let tree, _ = collect_exn tree (path ["ns"]) in - Alcotest.(check bool) "a populated namespace is kept" true (present tree (path ["ns"])) - -(* Property: pinning is a decision, reference counting is bookkeeping. No - sequence of pin/unpin may ever move the reference count. *) -let prop_pin_never_moves_reference_count = - QCheck.Test.make ~name:"pin/unpin never changes reference_count" ~count:200 - QCheck.(list bool) - (fun operations -> - let tree = register_exn Object.root (path ["r1"]) (relation "r1") in - let tree = - List.fold_left - (fun tree pin -> - if pin then Lifecycle.pin tree (path ["r1"]) else Lifecycle.unpin tree (path ["r1"]) ) - tree operations - in - reference_count tree (path ["r1"]) = 0 ) - -(* Property: reference edges are balanced. Registering an ephemeral relation - over any selection of inputs and then unregistering it returns every input - to its baseline count, whatever the selection or its duplicates. *) -let prop_edges_are_balanced = - QCheck.Test.make ~name:"register then unregister an ER restores input counts" ~count:200 - QCheck.(pair (int_range 1 5) (list (int_range 0 4))) - (fun (input_count, selection) -> - let inputs = List.init input_count (fun i -> path [Printf.sprintf "r%d" i]) in - let tree = - List.fold_left - (fun tree p -> register_exn tree p (relation (Path.to_string p))) - Object.root inputs - in - let chosen = - List.filter (fun i -> i < input_count) selection - |> List.map (fun i -> path [Printf.sprintf "r%d" i]) - in - let tree = register_exn tree (path ["er"]) (ephemeral "er" chosen) in - let tree = unregister_exn tree (path ["er"]) in - List.for_all (fun p -> reference_count tree p = 0) inputs ) - -let suites () = - [ ( "lifecycle/registry", - [ Alcotest.test_case "edges track dependents" `Quick test_edges_track_dependents; - Alcotest.test_case "eligibility gates" `Quick test_eligibility_gates; - Alcotest.test_case "cascade follows edges" `Quick test_cascade_follows_edges; - Alcotest.test_case "pin survives cascade" `Quick test_pin_survives_cascade; - Alcotest.test_case "runtime collection surfaces disposal" `Quick - test_runtime_collection_surfaces_disposal; - Alcotest.test_case "populated namespace is kept" `Quick test_populated_namespace_is_kept ] ); - ( "lifecycle/properties", - List.map QCheck_alcotest.to_alcotest - [prop_pin_never_moves_reference_count; prop_edges_are_balanced] ) ] diff --git a/test/unit/backend/Storage.ml b/test/unit/backend/Storage.ml index e184e1b..a6765bf 100644 --- a/test/unit/backend/Storage.ml +++ b/test/unit/backend/Storage.ml @@ -6,9 +6,9 @@ module Make (S : Abstract.Storage.STORAGE) (C : Helpers.Storage.CONFIGURATOR) = module H = Helpers.Storage.Make (S) (C) let storage_and_retrieval conn = - let key = Concepts.Hash.hash_of_value (Concepts.Value.String "value") in + let key = Concepts.Value.String "value" |> Concepts.Encoding.blob_of_value |> Concepts.Hash.hash_of_blob in let value = Concepts.Value.Integer 42 in - let blob = Concepts.Representation.blob_of_value value in + let blob = Concepts.Encoding.blob_of_value value in let v, v' = begin let open Utilities.Result in @@ -16,7 +16,7 @@ module Make (S : Abstract.Storage.STORAGE) (C : Helpers.Storage.CONFIGURATOR) = let* v = S.get tx (S.Hash key) in let* () = S.put tx (S.Hash key) blob in let* v' = S.get tx (S.Hash key) in - Ok Concepts.Representation.(Option.map value_of_blob v, Option.map value_of_blob v') + Ok Concepts.Encoding.(Option.map value_of_blob v, Option.map value_of_blob v') end |> Helpers.condition_as_failure in diff --git a/test/unit/concepts/Serialization.ml b/test/unit/concepts/Serialization.ml deleted file mode 100644 index 9df8d26..0000000 --- a/test/unit/concepts/Serialization.ml +++ /dev/null @@ -1,45 +0,0 @@ -module Branch = Rnt.Concepts.Branch -module Hash = Rnt.Concepts.Hash -module Multigroup = Rnt.Concepts.Multigroup -module Relation = Rnt.Concepts.Relation - -let fail_condition c = Alcotest.fail (Rnt.Concepts.Condition.to_string_hum c) -let hash text = Hash.hash_of_bytes (Bytes.of_string text) - -let check_hash label expected actual = - Alcotest.(check bool) label true (Hash.hash_equals expected actual) - -let test_branch_round_trips () = - let expected = Branch.make ~name:"master" ~target:(hash "master-target") in - match Branch.(expected |> to_bytes |> of_bytes) with - | Ok actual -> - Alcotest.(check string) "name" (Branch.name expected) (Branch.name actual); - check_hash "target" (Branch.target expected) (Branch.target actual) - | Error c -> fail_condition c - -let test_multigroup_round_trips () = - let expected = Multigroup.make ~name:"public" ~relations:(hash "public-relations") in - match Multigroup.(expected |> to_bytes |> of_bytes) with - | Ok actual -> - Alcotest.(check string) "name" (Multigroup.name expected) (Multigroup.name actual); - check_hash "relations" (Multigroup.relations expected) (Multigroup.relations actual) - | Error c -> fail_condition c - -let test_relation_round_trips () = - let schema = Relation.schema_of_list ["tag", "string"; "name", "string"] in - let expected = Relation.make ~name:"users" ~tuples:(hash "users-tuples") ~schema in - match Relation.(expected |> to_bytes |> of_bytes) with - | Ok actual -> - Alcotest.(check string) "name" (Relation.name expected) (Relation.name actual); - check_hash "tuples" (Relation.tuples expected) (Relation.tuples actual); - Alcotest.(check (list (pair string string))) - "schema" - (Relation.schema expected |> Relation.schema_to_list) - (Relation.schema actual |> Relation.schema_to_list) - | Error c -> fail_condition c - -let suites () = - [ ( "concepts/serialization", - [ Alcotest.test_case "branch round-trips" `Quick test_branch_round_trips; - Alcotest.test_case "multigroup round-trips" `Quick test_multigroup_round_trips; - Alcotest.test_case "relation round-trips" `Quick test_relation_round_trips ] ) ] |
