diff options
Diffstat (limited to 'lib')
55 files changed, 544 insertions, 1291 deletions
diff --git a/lib/Utilities.ml b/lib/Utilities.ml index a6b36c7..e4ee9c3 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 @@ -69,3 +75,25 @@ module FingerTree = struct BatFingerTree.print ~first:"" ~last:"" ~sep:sep BatIO.nwrite |> Fun.flip BatIO.to_string ss end + +module Option = struct + let ( let* ) = Option.bind + let fmap f m = Option.bind m f +end + +module Atomic = struct + let rec swap atom f = + let v = Atomic.get atom in + let v' = f v in + if Atomic.compare_and_set atom v v' + then atom + else swap atom f + + let rec mswap atom f = + let open Result in + let v = Atomic.get atom in + let* v' = f v in + if Atomic.compare_and_set atom v v' + then Ok atom + else mswap atom f +end diff --git a/lib/Utilities.mli b/lib/Utilities.mli index 2735009..f149889 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 @@ -7,6 +13,17 @@ module List : sig val sequence : ('a, 'b) result list -> ('a list, 'b) result end +module Option : sig + val ( let* ) : 'a option -> ('a -> 'b option) -> 'b option + val fmap : ('a -> 'b option) -> 'a option -> 'b option +end + +module Atomic : sig + val swap : 'a Atomic.t -> ('a -> 'a) -> 'a Atomic.t + (* This is silly *) + val mswap : 'a Atomic.t -> ('a -> ('a, 'b) result) -> ('a Atomic.t, 'b) result +end + module FingerTree : sig val map2 : ('a -> 'b -> 'c) -> 'a BatFingerTree.t -> 'b BatFingerTree.t -> 'c BatFingerTree.t val zip : 'a BatFingerTree.t -> 'b BatFingerTree.t -> ('a * 'b) BatFingerTree.t diff --git a/lib/abstract/Storage.ml b/lib/abstract/Storage.ml index 5eaeba3..19d6c5c 100644 --- a/lib/abstract/Storage.ml +++ b/lib/abstract/Storage.ml @@ -7,6 +7,8 @@ module type STORAGE = sig type connection type transaction + type address = Label of string | Hash of Concepts.Hash.hash + val connect : Concepts.Configuration.term -> (connection, Concepts.Condition.condition) result (** begin a transaction within `connection` *) @@ -21,13 +23,13 @@ module type STORAGE = sig (** within a transaction, fetch a blob from disk *) val get : transaction -> - Concepts.Hash.hash -> - (Concepts.Representation.blob option, Concepts.Condition.condition) result + address -> + (Concepts.Blob.t option, Concepts.Condition.condition) result (** within a transaction, associate a hash with a blob on disk *) val put : transaction -> - Concepts.Hash.hash -> - Concepts.Representation.blob -> + address -> + 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 ae5f5c1..0000000 --- a/lib/backend/managers/Object.ml +++ /dev/null @@ -1,241 +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 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) diff --git a/lib/backend/storage/LMDB.ml b/lib/backend/storage/LMDB.ml index ff5eb3d..0f65aaf 100644 --- a/lib/backend/storage/LMDB.ml +++ b/lib/backend/storage/LMDB.ml @@ -129,6 +129,8 @@ end type connection = {env: C.mdb_env_ptr; dbi: C.mdb_dbi} type transaction = {tx: C.mdb_txn_ptr; dbi: C.mdb_dbi} +type address = Label of string | Hash of Concepts.Hash.hash + let parse (c : Concepts.Configuration.term) = let open Concepts.Configuration in let open Utilities.Result in @@ -170,16 +172,20 @@ let abort ({tx; _} : transaction) = C.mdb_txn_abort tx |> Result.map_error Error * opens the path for avoiding a copy on the FFI boundary later on *) -let get ({tx; dbi} : transaction) (h : Concepts.Hash.hash) = - begin match C.mdb_get' tx dbi (Concepts.Hash.bytes_of_hash h) with - | Ok x -> Ok (Some (Concepts.Representation.blob_of_bytes x)) +let bytes_of_address = function + | Label s -> String.to_bytes s + | Hash h -> Concepts.Hash.bytes_of_hash h + +let get ({tx; dbi} : transaction) (addr : address) = + begin match C.mdb_get' tx dbi (bytes_of_address addr) with + | 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) (h : Concepts.Hash.hash) (b : Concepts.Representation.blob) = - C.mdb_put' tx dbi (Concepts.Hash.bytes_of_hash h) - (Concepts.Representation.bytes_of_blob b) +let put ({tx; dbi} : transaction) (addr : address) (b : Concepts.Blob.t) = + C.mdb_put' tx dbi (bytes_of_address addr) + (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 aac7428..ae0a178 100644 --- a/lib/concepts/Hash.ml +++ b/lib/concepts/Hash.ml @@ -7,17 +7,16 @@ 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 let of_raw_string str = Digestif.SHA256.of_raw_string str +let to_hum_string hash = Digestif.SHA256.to_hex hash + let hash_equals = Digestif.SHA256.equal let bytes_of_hash (h : hash) = Bytes.of_string (Digestif.SHA256.to_raw_string h) diff --git a/lib/concepts/Hash.mli b/lib/concepts/Hash.mli index 44fb3d0..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 @@ -19,6 +16,9 @@ val to_raw_string : hash -> string (** given a string containing a representation of a hash (as per `to_raw_string`), return the corresponding hash *) val of_raw_string : string -> hash +(** given a hash, return a representation of it as a string suitable for being displayed to humans *) +val to_hum_string : hash -> string + (** compare two hashes lexicographically *) val compare : hash -> hash -> Ordering.ordering 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 ef5ac12..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) ) - |> Utilities.List.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/BranchIndex.ml b/lib/kernel/BranchIndex.ml deleted file mode 100644 index d1efa9a..0000000 --- a/lib/kernel/BranchIndex.ml +++ /dev/null @@ -1,29 +0,0 @@ -type address = Concepts.Hash.hash -type root = address -type branch_name = string -type branch_state_root = address - -let default_branch_name = "master" - -module Branch_name = struct - type t = branch_name - - let encode name = Concepts.Codec.Bencode.(String name |> to_blob) - let compare left right = Concepts.Ordering.of_int (String.compare left right) - - let decode blob = - Concepts.Codec.Bencode.of_blob blob |> Utilities.Result.fmap Concepts.Codec.Bencode.as_string -end - -module Make (Store : Abstract.Storage.STORAGE) = struct - module Tree = Merkle.Make (Store) (Branch_name) - - type tree = Tree.node - - let empty = Tree.empty - let hash_of = Tree.hash_of - let persist = Tree.persist - let find = Tree.find - let find_branch = Tree.lookup - let put_branch = Tree.insert -end diff --git a/lib/kernel/BranchIndex.mli b/lib/kernel/BranchIndex.mli deleted file mode 100644 index 5a867bf..0000000 --- a/lib/kernel/BranchIndex.mli +++ /dev/null @@ -1,28 +0,0 @@ -type address = Concepts.Hash.hash -type root = address -type branch_name = string -type branch_state_root = address - -val default_branch_name : branch_name - -module Make (Store : Abstract.Storage.STORAGE) : sig - type tree - - val empty : tree - val hash_of : tree -> root - val persist : Store.transaction -> tree -> (root, Concepts.Condition.condition) result - val find : Store.transaction -> root -> (tree option, Concepts.Condition.condition) result - - val find_branch : - Store.transaction -> - branch_name -> - tree -> - (branch_state_root option, Concepts.Condition.condition) result - - val put_branch : - Store.transaction -> - branch_name -> - branch_state_root -> - tree -> - (tree, Concepts.Condition.condition) result -end diff --git a/lib/kernel/BranchManager.ml b/lib/kernel/BranchManager.ml new file mode 100644 index 0000000..03a2765 --- /dev/null +++ b/lib/kernel/BranchManager.ml @@ -0,0 +1,63 @@ +module Error = struct + open Concepts.Condition + + let invalid_root head = + 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 & + "reference" |=| Concepts.Value.String (Concepts.Hash.to_hum_string reference) & + "head" |=| Concepts.Value.String (Concepts.Hash.to_hum_string head)) +end + +module Make (S : Abstract.Storage.STORAGE) = struct + module M = Merkle.Make (S) (Merkle.StringKey) + module SI = Storage.Make (S) + + type manager = { storage: S.connection; + label : string; + head: M.node Atomic.t } + + let root_for tx label = + let open Utilities.Result in + let* label = S.get tx (S.Label label) in + let label = Option.map Concepts.Hash.hash_of_blob label in + Ok label + + let initialize storage label = + let open Utilities.Result in + SI.with_transaction storage (fun tx -> + let* addr = root_for tx label in + match addr with + | None -> failwith "TODO" + | Some addr -> + let* head = M.find tx addr in + let* head = Option.to_result ~none:(Error.invalid_root addr) head in + Ok { storage; label; head = Atomic.make head }) + + let fetch { storage; head; _ } branch_name = + SI.with_transaction storage (fun tx -> + let head = Atomic.get head in + M.lookup tx branch_name head) + + 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 + |> 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 + Ok new_head + else + Error (Error.comparison_failed branch_name reference branch))) in + Ok () + +end diff --git a/lib/kernel/BranchManager.mli b/lib/kernel/BranchManager.mli new file mode 100644 index 0000000..052f9a1 --- /dev/null +++ b/lib/kernel/BranchManager.mli @@ -0,0 +1,9 @@ +module Make (S : Abstract.Storage.STORAGE) : sig + type manager + + val initialize : S.connection -> string -> (manager, Concepts.Condition.condition) result + val fetch : manager -> string -> (Concepts.Hash.hash option, Concepts.Condition.condition) result + val update : manager -> string -> Concepts.Hash.hash -> Concepts.Hash.hash -> (unit, Concepts.Condition.condition) result + + (* TODO: fork, join *) +end diff --git a/lib/kernel/Lifecycle.ml b/lib/kernel/Lifecycle.ml new file mode 100644 index 0000000..ff67ecf --- /dev/null +++ b/lib/kernel/Lifecycle.ml @@ -0,0 +1,29 @@ +class type lifecycle = object + method reference : bool + method release : unit +end + +class type virtual controlled_lifecycle = object + inherit lifecycle + method virtual destroy : unit +end + +class null = object + method reference = true + method release = () +end + +class virtual counted = object (self) + val references = Atomic.make 1 + + method virtual destroy : unit + + method reference = + Atomic.incr references; + true + + method release = + Atomic.decr references; + if Atomic.get references <= 0 then + self#destroy +end diff --git a/lib/kernel/Lifecycle.mli b/lib/kernel/Lifecycle.mli new file mode 100644 index 0000000..f110768 --- /dev/null +++ b/lib/kernel/Lifecycle.mli @@ -0,0 +1,12 @@ +class type lifecycle = object + method reference : bool + method release : unit +end + +class type virtual controlled_lifecycle = object + inherit lifecycle + method virtual destroy : unit +end + +class null : lifecycle +class virtual counted : controlled_lifecycle diff --git a/lib/kernel/Merkle.ml b/lib/kernel/Merkle.ml index af703d7..ababb03 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 @@ -19,6 +19,7 @@ module type TREE = functor (S : Abstract.Storage.STORAGE) (K : KEY) -> sig val find : S.transaction -> address -> (node option, Concepts.Condition.condition) result val empty : node + val empty_under : S.transaction -> (address, Concepts.Condition.condition) result val hash_of : node -> address @@ -68,12 +69,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 @@ -92,14 +93,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 @@ -111,7 +112,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 @@ -121,7 +122,7 @@ module Make : TREE = functor (S : Abstract.Storage.STORAGE) (K : KEY) -> struct let find tx addr = let open Utilities.Result in - let* data = S.get tx addr in + let* data = S.get tx (S.Hash node) in match data with | None -> Ok None | Some data -> @@ -149,9 +150,11 @@ module Make : TREE = functor (S : Abstract.Storage.STORAGE) (K : KEY) -> struct let open Utilities.Result in let data = to_blob node in let addr = Concepts.Hash.hash_of_blob data in - let* () = S.put tx addr data in + let* () = S.put tx (S.Hash addr) data in Ok addr + let empty_under tx = persist tx empty + type op = Update of address * node | Split of address * K.t * address let emplace i v ft = @@ -217,7 +220,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) @@ -303,7 +306,7 @@ module Make : TREE = functor (S : Abstract.Storage.STORAGE) (K : KEY) -> struct end module type INTERFACE = functor (S : Abstract.Storage.STORAGE) (K : KEY) (V : VALUE) -> sig - type address + type address = Concepts.Hash.hash type node val find : S.transaction -> address -> (node option, Concepts.Condition.condition) result @@ -332,11 +335,11 @@ module Interface : INTERFACE = functor (S : Abstract.Storage.STORAGE) (K : KEY) let intern tx v = let data = V.encode v in let addr = Concepts.Hash.hash_of_blob data in - let* () = S.put tx addr data in + let* () = S.put tx (S.Hash addr) data in Ok addr let retrieve tx addr = - let* data = S.get tx addr in + let* data = S.get tx (S.Hash addr) in match data with | None -> Ok None | Some data -> @@ -379,3 +382,11 @@ module Interface : INTERFACE = functor (S : Abstract.Storage.STORAGE) (K : KEY) (fun _ k v -> f k v |> ignore) () node end + +module StringKey : KEY with type t = string = struct + type t = string + + 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.Blob.bytes_of_blob b |> String.of_bytes |> Result.ok +end diff --git a/lib/kernel/Namespace.ml b/lib/kernel/Namespace.ml new file mode 100644 index 0000000..7c9cd2b --- /dev/null +++ b/lib/kernel/Namespace.ml @@ -0,0 +1,49 @@ +module Errors = struct + include Concepts.Condition + + let key_already_exists key = + condition "key-already-exists" "The specified key already exists in the namespace" + ("key" |=| Concepts.Value.String key) + + let no_such_key key = + condition "no-such-key" "The specified key does not exist in the namespace" + ("key" |=| Concepts.Value.String key) +end + +class namespace = object (self) + inherit Lifecycle.null + + val entries : (string, Protocols.Handle.t) BatMap.t Atomic.t = + Atomic.make BatMap.empty + + method protocols = Protocols.[Directory.make self; Registry.make self] + + method register key value = + Utilities.Atomic.mswap entries + (fun e -> + match BatMap.find_opt key e with + | None -> Ok (BatMap.add key value e) + | Some _ -> Error (Errors.key_already_exists key)) + |> Result.map ignore + + method unregister key = + Utilities.Atomic.mswap entries + (fun e -> + try + Ok (BatMap.remove_exn key e) + with Not_found -> + Error (Errors.no_such_key key)) + |> Result.map ignore + + method list = + Atomic.get entries + |> BatMap.keys + |> BatList.of_enum + + method find key = + Atomic.get entries + |> BatMap.find_opt key + |> Utilities.Option.fmap Protocols.Handle.copy +end + +let make () = new namespace diff --git a/lib/kernel/Namespace.mli b/lib/kernel/Namespace.mli new file mode 100644 index 0000000..3ed64a3 --- /dev/null +++ b/lib/kernel/Namespace.mli @@ -0,0 +1,7 @@ +class namespace : object + inherit Protocols.Handle.obj + inherit Protocols.Directory.implementation + inherit Protocols.Registry.implementation +end + +val make : unit -> namespace diff --git a/lib/kernel/Storage.ml b/lib/kernel/Storage.ml new file mode 100644 index 0000000..376d839 --- /dev/null +++ b/lib/kernel/Storage.ml @@ -0,0 +1,22 @@ +module Make (S : Abstract.Storage.STORAGE) = struct + let finish tx = function + | Ok value -> + let open Utilities.Result in + let* () = S.commit tx in + Ok value + | Error condition -> + let _ = S.abort tx in + Error condition + + let with_transaction connection body = + let open Utilities.Result in + let* tx = S.start connection in + body tx |> finish tx + + let store_blob tx blob = + let open Utilities.Result in + let address = Concepts.Hash.hash_of_blob blob in + let* () = S.put tx (S.Hash address) blob in + Ok address + +end diff --git a/lib/kernel/Storage.mli b/lib/kernel/Storage.mli new file mode 100644 index 0000000..1148fba --- /dev/null +++ b/lib/kernel/Storage.mli @@ -0,0 +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.Blob.t -> (Concepts.Hash.hash, Concepts.Condition.condition) result +end diff --git a/lib/protocols/Directory.ml b/lib/protocols/Directory.ml new file mode 100644 index 0000000..5b21668 --- /dev/null +++ b/lib/protocols/Directory.ml @@ -0,0 +1,16 @@ +class type implementation = object + method list : string list + method find : string -> Handle.t option +end + +type Handle.protocol += Directory of implementation + +type t = implementation + +let make impl = Directory (impl :> implementation) + +let from handle = Handle.into handle (function Directory impl -> Some impl | _ -> None) + +let list i = Handle.invoke i (fun o -> o#list) + +let find i name = Handle.invoke i (fun o -> o#find name) diff --git a/lib/protocols/Directory.mli b/lib/protocols/Directory.mli new file mode 100644 index 0000000..5bf5277 --- /dev/null +++ b/lib/protocols/Directory.mli @@ -0,0 +1,13 @@ +type t + +class type implementation = object + method list : string list + method find : string -> Handle.t option +end + +val make : #implementation -> Handle.protocol + +val from : Handle.t -> t Handle.interface option + +val list : t Handle.interface -> string list +val find : t Handle.interface -> string -> Handle.t option diff --git a/lib/protocols/Handle.ml b/lib/protocols/Handle.ml new file mode 100644 index 0000000..9fd1f29 --- /dev/null +++ b/lib/protocols/Handle.ml @@ -0,0 +1,41 @@ +type protocol = .. + +class type obj = object + method reference : bool + method release : unit + method protocols : protocol list +end + +type t = { valid : bool ref; refers_to : obj } + +type 'a interface = { handle : t; interface : 'a } + +let object_of { valid; refers_to } = + if !valid then + refers_to + else + failwith "Attempt to dereference an invalid handle!" + +let interface_of handle interface = { handle; interface } + +let make o = { valid = ref true; refers_to = (o :> obj) } + +let into handle f = + List.find_map f (object_of handle)#protocols + |> Option.map (interface_of handle) + +let invoke { handle; interface } f = + let _ = object_of handle in + f interface + +let copy handle = + let o = object_of handle in + if o#reference then + Some (make o) + else + None + +let release ({ valid; _ } as handle) = + let o = object_of handle in + valid := false; + o#release diff --git a/lib/protocols/Handle.mli b/lib/protocols/Handle.mli new file mode 100644 index 0000000..099f563 --- /dev/null +++ b/lib/protocols/Handle.mli @@ -0,0 +1,20 @@ +type t + +type 'a interface + +type protocol = .. + +class type obj = object + method reference : bool + method release : unit + method protocols : protocol list +end + +val make : #obj -> t + +val into : t -> (protocol -> 'a option) -> 'a interface option + +val invoke : 'a interface -> ('a -> 'b) -> 'b + +val copy : t -> t option +val release : t -> unit diff --git a/lib/protocols/Registry.ml b/lib/protocols/Registry.ml new file mode 100644 index 0000000..4c47001 --- /dev/null +++ b/lib/protocols/Registry.ml @@ -0,0 +1,16 @@ +class type implementation = object + method register : string -> Handle.t -> (unit, Concepts.Condition.condition) result + method unregister : string -> (unit, Concepts.Condition.condition) result +end + +type Handle.protocol += Registry of implementation + +type t = implementation + +let make impl = Registry (impl :> implementation) + +let from handle = Handle.into handle (function Registry impl -> Some impl | _ -> None) + +let register i key value = Handle.invoke i (fun o -> o#register key value) + +let unregister i key = Handle.invoke i (fun o -> o#unregister key) diff --git a/lib/protocols/Registry.mli b/lib/protocols/Registry.mli new file mode 100644 index 0000000..175ebed --- /dev/null +++ b/lib/protocols/Registry.mli @@ -0,0 +1,13 @@ +type t + +class type implementation = object + method register : string -> Handle.t -> (unit, Concepts.Condition.condition) result + method unregister : string -> (unit, Concepts.Condition.condition) result +end + +val make : #implementation -> Handle.protocol + +val from : Handle.t -> t Handle.interface option + +val register : t Handle.interface -> string -> Handle.t -> (unit, Concepts.Condition.condition) result +val unregister : t Handle.interface -> string -> (unit, Concepts.Condition.condition) result |
