(*--------------------------------------------------------------------------- Copyright (c) 2025 Thomas Gazagnaire. All rights reserved. SPDX-License-Identifier: ISC ---------------------------------------------------------------------------*) open Message (* {1 Configuration} *) type config = { local_eid : eid; previous_node : eid option; storage : int } let config ?previous_node ~storage ~local_eid () = { local_eid; previous_node; storage } let local_eid c = c.local_eid let storage c = c.storage (* {1 State} The store keys held bundles by their identity (RFC 9171 Section 4.2) in an immutable map, so insertion and lookup stay logarithmic. Each entry carries a monotone [order] stamp recording when the bundle was stored, so [retained] reports the bundles most recently stored first without the map's key order leaking through, why it is held, the bytes it is charged against storage and when it reached this node. Three queues are maps keyed by the same [order] stamp, oldest first, so each is drained in the order its elements arrived and an element leaves any of them in a logarithmic step: [forwarding], the "Forward pending" bundles not yet handed to the convergence layer, [deferred], the bundles whose delivery waits for the registration to be polled (Section 5.7, Step 2), and [notices], the service events not yet taken. The one bundle handed to the convergence layer is [flight]; it is in neither bundle queue. Fragments pending reassembly (RFC 9171 Section 5.9) are also grouped by source node ID and creation timestamp. A group maps each fragment offset to the fragment's identity, and keeps the union of the fragments' material extents as disjoint, non-adjacent [start -> stop] intervals, so one arrival costs a logarithmic number of map steps. [held] is the sum of the bytes charged by the store, the held service events and an orphaned flight, kept as each changes. *) module Store = Map.Make (struct type t = bundle_id let compare = compare_bundle_id end) module Orders = Map.Make (Int) module Offsets = Map.Make (Int64) type adu = { source : eid; created : timestamp } module Groups = Map.Make (struct type t = adu let compare a b = match compare_eid a.source b.source with | 0 -> compare_timestamp a.created b.created | n -> n end) (* Two of RFC 9171's retention constraints, and the registration's deferral of a delivery, which is not one (Section 5.7, Step 2). *) type hold = Forward_pending | Reassembly_pending | Deferred type entry = { order : int; bundle : Message.t; hold : hold; bytes : int; arrived : int64; } type group = { fragments : bundle_id Offsets.t; extents : int64 Offsets.t } (* The bundle handed to the convergence layer. [orphan] is the bytes it still holds there after its deletion removed it from the store. *) type flight = { id : bundle_id; orphan : int } type notice = { event : Event.t; size : int } type t = { config : config; store : entry Store.t; groups : group Groups.t; next_order : int; forwarding : bundle_id Orders.t; deferred : bundle_id Orders.t; flight : flight option; notices : notice Orders.t; polls : int; watches : int; held : int; reading : bool; refused : int; } let v config = { config; store = Store.empty; groups = Groups.empty; next_order = 0; forwarding = Orders.empty; deferred = Orders.empty; flight = None; notices = Orders.empty; polls = 0; watches = 0; held = 0; reading = config.storage > 0; refused = 0; } let config_of t = t.config let held t = t.held let reading t = t.reading let refused t = t.refused let events t = List.map (fun (_, n) -> n.event) (Orders.bindings t.notices) (* Held entries most recently stored first: descending [order] stamp. *) let entries_recent_first t = Store.bindings t.store |> List.sort (fun (_, a) (_, b) -> Int.compare b.order a.order) let pending t = List.map fst (entries_recent_first t) let retained t = List.map (fun (_, e) -> e.bundle) (entries_recent_first t) let deferred t = List.map (fun (_, id) -> (Store.find id t.store).bundle) (Orders.bindings t.deferred) let in_flight t id e = match (t.flight, e.hold) with | Some f, Forward_pending -> equal_bundle_id f.id id && not (Orders.mem e.order t.forwarding) | Some _, (Reassembly_pending | Deferred) | None, _ -> false (* Remove [id]'s entry. A bundle the convergence layer is still sending keeps its bytes held, as the flight's orphan, until the send concludes. *) let unstore t id = match Store.find_opt id t.store with | None -> (t, None) | Some e -> let orphaned = in_flight t id e in let t = { t with store = Store.remove id t.store } in let t = match e.hold with | Forward_pending -> { t with forwarding = Orders.remove e.order t.forwarding } | Deferred -> { t with deferred = Orders.remove e.order t.deferred } | Reassembly_pending -> t in let t = if orphaned then { t with flight = Some { id; orphan = e.bytes } } else { t with held = t.held - e.bytes } in (t, Some e) (* The bytes free for [id] when it would replace the copy already held. *) let room t id = let replaced = match Store.find_opt id t.store with | Some e when not (in_flight t id e) -> e.bytes | Some _ | None -> 0 in t.config.storage - t.held + replaced let fits t id bytes = bytes <= room t id (* Store [b], replacing a copy held under the same identity. *) let store t hold ~bytes ~arrived b = let id = bundle_id b in let t, _ = unstore t id in let order = t.next_order in let entry = { order; bundle = b; hold; bytes; arrived } in let t = { t with store = Store.add id entry t.store; next_order = order + 1; held = t.held + bytes; } in match hold with | Forward_pending -> { t with forwarding = Orders.add order id t.forwarding } | Deferred -> { t with deferred = Orders.add order id t.deferred } | Reassembly_pending -> t (* A held service event is charged the length of the identity it names. *) let notify t event = let id = match event with | Event.Received id | Delivered id | Forwarded id | Deleted (id, _) -> id in let size = String.length (string_of_bundle_id id) in { t with notices = Orders.add t.next_order { event; size } t.notices; next_order = t.next_order + 1; held = t.held + size; } (* {1 Timers} *) type timer = Lifetime of bundle_id let pp_timer ppf (Lifetime id) = Fmt.pf ppf "Lifetime(%a)" pp_bundle_id id (* A timer identifies the retained bundle it counts down for, so two timers are the same timer when they name the same bundle (RFC 9171 Section 4.2), never when their bundles' contents agree. *) let equal_timer (Lifetime a) (Lifetime b) = equal_bundle_id a b (* {1 Transitions} *) type event = | Receive of string | Transmit_request of Message.t | Forwarding_concluded of bundle_id | Poll_registration | Poll_events | Timer_expired of timer type action = | Read | Forward of Message.t * eid | Deliver of Message.t | Store of Message.t | Release of bundle_id | Discard of Message.t * status_report_reason | Refuse of { reason : Message.error; bytes : int } | Notify of Event.t | Start_timer of timer * int64 | Cancel_timer of timer let is_local t dst = equal_eid dst t.config.local_eid let delete t b reason = (notify t (Event.Deleted (bundle_id b, reason)), [ Discard (b, reason) ]) (* [a - b], saturating at the bounds of [int64]: the operands come off the wire. *) let sub_sat a b = let d = Int64.sub a b in if Int64.compare b 0L < 0 && Int64.compare d a < 0 then Int64.max_int else if Int64.compare b 0L > 0 && Int64.compare d a > 0 then Int64.min_int else d (* RFC 9171 Section 5.5: a bundle's age is the current time minus its creation time when that time is not zero, and otherwise the value of its Bundle Age block (Section 4.4.2), which such a bundle must carry. *) let age_at ~now b = let created = b.primary.creation_timestamp.time in if Int64.equal created 0L then age b else Some (sub_sat now created) (* {1 Forwarding} *) let increment_hop_count blk = match blk.data with | Hop_count_data { limit; count } -> { blk with data = Hop_count_data { limit; count = count + 1 } } | Payload_data _ | Previous_node_data _ | Bundle_age_data _ | Unknown_data _ -> blk (* RFC 9171 Section 5.4, Step 4, applied to the bundle handed to the convergence layer: the hop count is increased by one (Section 4.4.3), a received Previous Node block is removed and, when the node is configured to attach one, replaced by one naming this node, and the Bundle Age block is increased by [residence], the time the bundle has spent at this node. *) let conveyed t ~residence b = let blocks = List.filter_map (fun blk -> match blk.data with | Hop_count_data _ -> Some (increment_hop_count blk) | Bundle_age_data a -> Some { blk with data = Bundle_age_data (Int64.add a residence) } | Previous_node_data _ -> None | Payload_data _ | Unknown_data _ -> Some blk) b.blocks in let blocks = match t.config.previous_node with | None -> blocks | Some node -> let number = List.fold_left (fun n blk -> max n blk.block_number) 1 blocks + 1 in (* RFC 9171 Section 4.1: the payload block is the last block. *) let payload, others = List.partition (fun blk -> blk.block_type = Payload) blocks in others @ [ { block_type = Previous_node; block_number = number; flags = block_flags_default; crc_type = b.primary.crc_type; data = Previous_node_data node; }; ] @ payload in { b with blocks } (* RFC 9171 Section 5.4, Step 1: the bundle is retained ("Forward pending") with its lifetime timer armed with what remains of its lifetime, and waits its turn on the convergence layer. A bundle that would take more than the storage left is deleted for the reason "Depleted storage" (Section 6.1.1). *) let really_forward t ~bytes ~arrived ~remaining b = let id = bundle_id b in if not (fits t id bytes) then delete t b Depleted_storage else let t = store t Forward_pending ~bytes ~arrived b in (t, [ Store b; Start_timer (Lifetime id, remaining) ]) (* RFC 9171 Section 4.4.3: once the incremented hop count exceeds the hop limit the bundle is deleted for the reason "Hop limit exceeded". *) let forward t ~bytes ~arrived ~remaining b = match hop_count b with | Some (limit, count) when count + 1 > limit -> let b = { b with blocks = List.map increment_hop_count b.blocks } in delete t b Hop_limit_exceeded | Some _ | None -> really_forward t ~bytes ~arrived ~remaining b (* RFC 9171 Section 5.4, Step 5: once the convergence layer has concluded its data-sending procedures, the bundle is forwarded and its "Forward pending" retention is removed. The bundle then has no retention constraint left and is discarded (Section 5.11). A bundle deleted while it was being sent has already left the store, and only its bytes are released. *) let on_forwarding_concluded t id = match t.flight with | Some f when equal_bundle_id f.id id -> let sent = match Store.find_opt id t.store with | Some e -> in_flight t id e | None -> false in let t = { t with flight = None; held = t.held - f.orphan } in if not sent then (t, []) else let t, _ = unstore t id in let t = notify t (Event.Forwarded id) in (t, [ Cancel_timer (Lifetime id); Release id ]) | Some _ | None -> (t, []) (* {1 Reassembly} *) let adu_of b = { source = b.primary.source; created = b.primary.creation_timestamp } let empty_group = { fragments = Offsets.empty; extents = Offsets.empty } (* [add_extent (start, stop) extents] is the union of [extents] and [\[start;stop)], merged so the intervals stay disjoint and non-adjacent. *) let add_extent (start, stop) extents = let start, stop, extents = match Offsets.find_last_opt (fun k -> Int64.compare k start <= 0) extents with | Some (s, e) when Int64.compare e start >= 0 -> ( s, (if Int64.compare e stop > 0 then e else stop), Offsets.remove s extents ) | Some _ | None -> (start, stop, extents) in let rec absorb stop extents = match Offsets.find_first_opt (fun k -> Int64.compare k start >= 0) extents with | Some (s, e) when Int64.compare s stop <= 0 -> absorb (if Int64.compare e stop > 0 then e else stop) (Offsets.remove s extents) | Some _ | None -> (stop, extents) in let stop, extents = absorb stop extents in Offsets.add start stop extents let payload_length b = Int64.of_int (String.length (Option.value ~default:"" (payload b))) (* The extent a fragment's payload covers, or [None] when it covers no byte or its offset and length do not name a range of the ADU. *) let extent_of offset b = let len = payload_length b in if Int64.compare offset 0L < 0 || Int64.equal len 0L then None else if Int64.compare offset (Int64.sub Int64.max_int len) > 0 then None else Some (offset, Int64.add offset len) let add_fragment group offset id b = let extents = match extent_of offset b with | None -> group.extents | Some x -> add_extent x group.extents in { fragments = Offsets.add offset id group.fragments; extents } let extents_of t fragments = Offsets.fold (fun offset id extents -> match Store.find_opt id t.store with | None -> extents | Some { bundle; _ } -> ( match extent_of offset bundle with | None -> extents | Some x -> add_extent x extents)) fragments Offsets.empty let complete group total = match Offsets.bindings group.extents with | [ (0L, stop) ] -> Int64.equal stop total | _ -> false (* RFC 9171 Section 5.9: the concatenation of the material extents, as informed by fragment offsets and payload lengths. Only called on a complete group, so every fragment starts at or before the bytes already placed. *) let reassemble t group total = let buf = Buffer.create (Int64.to_int total) in let _ = Offsets.fold (fun offset id cursor -> match Store.find_opt id t.store with | None -> cursor | Some { bundle; _ } -> let p = Option.value ~default:"" (payload bundle) in let stop = Int64.add offset (Int64.of_int (String.length p)) in if Int64.compare stop cursor <= 0 then cursor else begin let skip = Int64.to_int (Int64.sub cursor offset) in Buffer.add_substring buf p skip (String.length p - skip); stop end) group.fragments 0L in Buffer.contents buf let with_payload adu b = { b with blocks = List.map (fun blk -> match blk.data with | Payload_data _ -> { blk with data = Payload_data adu } | Previous_node_data _ | Bundle_age_data _ | Hop_count_data _ | Unknown_data _ -> blk) b.blocks; } (* {1 Local delivery} *) (* RFC 9171 Section 5.7, Step 2. A polled registration is Active: the bundle is presented to the application, which is its delivery. Otherwise the registration's delivery failure action defers it until the registration is polled, least recently received first; the deferred bundle is held in storage with its lifetime timer armed, and one that would take more than the storage left is deleted for the reason "Depleted storage". *) let deliver_whole t ~bytes ~arrived ~remaining b = let id = bundle_id b in if t.polls > 0 then let t = { t with polls = t.polls - 1 } in (notify t (Event.Delivered id), [ Deliver b ]) else if not (fits t id bytes) then delete t b Depleted_storage else let t = store t Deferred ~bytes ~arrived b in (t, [ Store b; Start_timer (Lifetime id, remaining) ]) (* RFC 9171 Section 5.9: once the material extents of the group form the whole ADU, the ADU replaces the payload of the fragment at offset zero, which proceeds to delivery (Section 5.7, Step 2), and the "Reassembly pending" retention of every fragment of the group is removed. *) let deliver_reassembled t ~now ~remaining ~held key group total = let adu = reassemble t group total in (* A complete group covers offset zero, so its first fragment is there. *) let _, first_id = Offsets.min_binding group.fragments in let delivered = with_payload adu (Store.find first_id t.store).bundle in let ids = List.map snd (Offsets.bindings group.fragments) in let t = List.fold_left (fun t id -> fst (unstore t id)) t ids in let t = { t with groups = Groups.remove key t.groups } in let releases = List.concat_map (fun id -> if List.exists (equal_bundle_id id) held then [ Cancel_timer (Lifetime id); Release id ] else []) ids in let bytes = String.length (encode delivered) in let t, actions = deliver_whole t ~bytes ~arrived:now ~remaining delivered in (t, releases @ actions) (* RFC 9171 Section 5.7, Step 1 for a fragment: the ADU Reassembly procedure (Section 5.9) runs, and a fragment that does not complete the ADU is retained ("Reassembly pending") with its lifetime timer armed. A fragment whose identity is already held keeps the longer of the two payloads, so no material extent is lost. *) let reassembly t ~now ~bytes ~remaining b = match (b.primary.fragment_offset, b.primary.total_adu_length) with | None, _ | _, None -> delete t b Block_unintelligible | Some offset, Some total -> let id = bundle_id b in let held = match Store.find_opt id t.store with | Some { hold = Reassembly_pending; bundle; bytes; _ } -> Some (bundle, bytes) | Some { hold = Forward_pending | Deferred; _ } | None -> None in let keep, bytes = match held with | Some (h, n) when Int64.compare (payload_length h) (payload_length b) >= 0 -> (h, n) | Some _ | None -> (b, bytes) in if not (fits t id bytes) then delete t b Depleted_storage else let key = adu_of b in let group = Option.value ~default:empty_group (Groups.find_opt key t.groups) in let group = add_fragment group offset id keep in let t = store t Reassembly_pending ~bytes ~arrived:now keep in let t = { t with groups = Groups.add key group t.groups } in if complete group total then (* The fragments held before this one were stored and timed. *) let held = Offsets.fold (fun _ i acc -> if equal_bundle_id i id && Option.is_none held then acc else i :: acc) group.fragments [] in deliver_reassembled t ~now ~remaining ~held key group total else (t, [ Store keep; Start_timer (Lifetime id, remaining) ]) (* {1 Dispatching} *) (* RFC 9171 Section 5.7 "Local Bundle Delivery". *) let deliver t ~now ~bytes ~arrived ~remaining b = if b.primary.flags.is_fragment then reassembly t ~now ~bytes ~remaining b else deliver_whole t ~bytes ~arrived ~remaining b (* RFC 9171 Section 5.3 "Bundle Dispatching", after the expiry check of Section 5.5: a bundle whose age already reaches its lifetime is deleted for the reason "Lifetime expired"; one whose destination is a local endpoint is delivered (5.7), and the node does not forward it to itself; otherwise it is forwarded (5.4) with what remains of its lifetime. [arrived] is when the bundle reached this node: [now] for a received bundle, its creation time for one created here. [bytes] is its encoding's length as it reached this node. A bundle whose creation time is zero and that carries no Bundle Age block has no age (Section 4.4.2 requires the block), so it is malformed and deleted for the reason "Block unintelligible" (Section 5.6, Step 3). *) let dispatch_bundle t ~now ~arrived ~bytes b = match age_at ~now b with | None -> delete t b Block_unintelligible | Some age -> let remaining = sub_sat b.primary.lifetime age in if Int64.compare remaining 0L <= 0 then delete t b Lifetime_expired else if is_local t b.primary.destination then deliver t ~now ~bytes ~arrived ~remaining b else forward t ~bytes ~arrived ~remaining b (* RFC 9171 Section 5.6 Step 4: a block this node cannot process is one of an unrecognised type. Its "delete bundle" flag deletes the bundle for the reason "Block unsupported"; otherwise its "discard block" flag removes the block. *) let unprocessable blk = match blk.data with | Unknown_data _ -> true | Payload_data _ | Previous_node_data _ | Bundle_age_data _ | Hop_count_data _ -> false let check_blocks b = if List.exists (fun blk -> unprocessable blk && blk.flags.delete_if_unprocessed) b.blocks then Error Block_unsupported else Ok { b with blocks = List.filter (fun blk -> not (unprocessable blk && blk.flags.discard_if_unprocessed)) b.blocks; } (* RFC 9171 Section 4.1: a transfer that is not a bundle is discarded and counted; it names no bundle, so no service event describes it. Otherwise Section 5.6 "Bundle Reception": accept the bundle, apply Step 4 to its unprocessable blocks, then proceed to dispatching (5.3). *) let on_reception t ~now raw = let t = { t with reading = false } in let bytes = String.length raw in match decode raw with | Error reason -> ({ t with refused = t.refused + 1 }, [ Refuse { reason; bytes } ]) | Ok b -> ( let t = notify t (Event.Received (bundle_id b)) in match check_blocks b with | Error reason -> delete t b reason | Ok b -> dispatch_bundle t ~now ~arrived:now ~bytes b) (* RFC 9171 Section 5.2 "Bundle Transmission": the created bundle is dispatched (5.3), so one addressed to a local endpoint is delivered rather than forwarded to self. Its residence at this node counts from its creation time, or from the request when that time is zero. *) let on_transmit_request t ~now b = let created = b.primary.creation_timestamp.time in let arrived = if Int64.equal created 0L then now else created in dispatch_bundle t ~now ~arrived ~bytes:(String.length (encode b)) b let drop_fragment t b = let key = adu_of b in match (Groups.find_opt key t.groups, b.primary.fragment_offset) with | None, _ | _, None -> t | Some group, Some offset -> let fragments = Offsets.remove offset group.fragments in if Offsets.is_empty fragments then { t with groups = Groups.remove key t.groups } else let group = { fragments; extents = extents_of t fragments } in { t with groups = Groups.add key group t.groups } (* RFC 9171 Section 5.10 "Bundle Deletion": the held bundle's lifetime elapsed (Section 5.5), so it is deleted for the reason "Lifetime expired", whatever holds it -- a forward still waiting or already being sent, a reassembly, a deferred delivery -- and the timer is cancelled. A timer for a bundle no longer held is a no-op. *) let on_timer_expired t (Lifetime id) = match unstore t id with | _, None -> (t, []) | t, Some { bundle = b; hold; _ } -> let t = match hold with | Reassembly_pending -> drop_fragment t b | Forward_pending | Deferred -> t in let t, actions = delete t b Lifetime_expired in (t, actions @ [ Cancel_timer (Lifetime id) ]) (* {1 Settling} After every transition the node hands the oldest waiting forward to an idle convergence layer, answers the polls it can, and asks for the next transfer while its storage has room. *) (* RFC 9171 Section 5.4, Step 4, at the time the bundle is handed over: its residence is measured to [now]. *) let send_next t ~now = match (t.flight, Orders.min_binding_opt t.forwarding) with | None, Some (order, id) -> let e = Store.find id t.store in let t = { t with forwarding = Orders.remove order t.forwarding; flight = Some { id; orphan = 0 }; } in let b = conveyed t ~residence:(sub_sat now e.arrived) e.bundle in (t, [ Forward (b, b.primary.destination) ]) | Some _, _ | None, None -> (t, []) (* RFC 9171 Section 5.7, Step 2(a) and (b): a polled registration takes the least recently received deferred bundle. *) let rec answer_polls t acc = match Orders.min_binding_opt t.deferred with | Some (_, id) when t.polls > 0 -> let t, e = unstore t id in let b = (Option.get e).bundle in let t = notify { t with polls = t.polls - 1 } (Event.Delivered id) in answer_polls t (List.rev_append [ Cancel_timer (Lifetime id); Deliver b; Release id ] acc) | Some _ | None -> (t, acc) let rec answer_watches t acc = if t.watches = 0 then (t, acc) else match Orders.min_binding_opt t.notices with | None -> (t, acc) | Some (order, n) -> let t = { t with notices = Orders.remove order t.notices; watches = t.watches - 1; held = t.held - n.size; } in answer_watches t (Notify n.event :: acc) let settle t ~now actions = let t, sends = send_next t ~now in let t, delivered = answer_polls t [] in let t, notified = answer_watches t [] in let t, read = if (not t.reading) && t.held < t.config.storage then ({ t with reading = true }, [ Read ]) else (t, []) in (t, actions @ sends @ List.rev delivered @ List.rev notified @ read) let incoming t ~now event = let t, actions = match event with | Receive raw -> on_reception t ~now raw | Transmit_request b -> on_transmit_request t ~now b | Forwarding_concluded id -> on_forwarding_concluded t id | Poll_registration -> ({ t with polls = t.polls + 1 }, []) | Poll_events -> ({ t with watches = t.watches + 1 }, []) | Timer_expired timer -> on_timer_expired t timer in settle t ~now actions let pp ppf t = Fmt.pf ppf "Node{local=%a; pending=%d; held=%d/%d}" pp_eid t.config.local_eid (Store.cardinal t.store) t.held t.config.storage