;; This Source Code Form is subject to the terms of the Mozilla Public ;; License, v. 2.0. If a copy of the MPL was not distributed with this ;; file, You can obtain one at http://mozilla.org/MPL/2.0/. ;; bjomarks/src/bookmark.bjo — the module (bjomarks bookmark): bookmarks, the ;; stamps that order their changes, how two sets of them merge, and their ;; JSON. ;; ;; - A bookmark has an id, an address (`url`), an optional title, the instant ;; it was added, a set of tags, and an optional link to a copy in a web ;; archive. ;; - An entry is one bookmark as one device last knew it: the bookmark, or ;; the fact that it was deleted (a tombstone), with the stamp of the change. ;; - Two devices merge their entries by id. For each id the entry with the ;; later stamp wins (last writer wins). The merge gives the same result in ;; any order, and merging twice changes nothing. ;; - The JSON of an entry keeps the fields that this version does not know, ;; so that an older version does not remove what a newer one wrote. (export ;; Bookmarks Bookmark make-bookmark bookmark-with-tags bookmark-with-archive bookmark-with-title clean-tags clean-title absolute-url? ;; Stamps Stamp stamp->string string->stamp stamp-compare Clock clock-zero clock-observe clock-next ;; Entries Entry EntryState entry-id entry-live? live-entry deleted-entry ;; Merging merge-entry merge-entries merge-entries/count merge-maps entries->map entries-clock live-bookmarks ;; JSON entry->json json->entry DeviceDoc document-format device-doc->string parse-device-doc) (import (std prelude)) (import (std datetime)) (import (std uuid)) (import (std url)) (import (text json)) (import/extern ;; The input, a pattern and its replacement. (clr-collapse (: System.Text.RegularExpressions.Regex.Replace (-> string string string string)))) ;; --------------------------------------------------------------------------- ;; Bookmarks ;; --------------------------------------------------------------------------- ;; `title` is the page's title, as given or fetched: one line, not empty. ;; `tags` is sorted and has each tag once. `archive` is the address of a copy ;; in a web archive, such as https://web.archive.org/web/2026.../https://... (type (: Bookmark (Record (: id Uuid) (: url string) (: title (Option string)) (: added Instant) (: tags (Vec string)) (: archive (Option string))))) ;; The most characters a title keeps. (: int) (def max-title-length 300) ;; A title as kept: each run of white space, line breaks too, made one ;; space, the ends trimmed, and at most 300 characters. `None` for a title ;; that is then empty. (: (-> string (Option string))) (defun (clean-title text) (def one-line (string-trim (clr-collapse text "\\s+" " "))) (cond ((string-empty? one-line) None) ((> (string-count one-line) max-title-length) (Some (string-trim (string-take one-line max-title-length)))) (else (Some one-line)))) ;; True when `text` is an absolute URL by RFC 3986: it has a scheme, as ;; https://example.org/ and mailto:a@example.org have. (: (-> string bool)) (defun (absolute-url? text) (match (parse-url text) ((Ok u) (url-absolute? u)) ((Err _) #f))) ;; Each tag once, in order. The caller removes the empty ones. (: (-> (Vec string) (Vec string))) (defun (sorted-unique tags) (def sorted (vec-sort tags)) (def n (vec-length sorted)) (let go ((i 0) (out [])) (cond ((= i n) out) ((and (> i 0) (= (vec-ref sorted i) (vec-ref sorted (- i 1)))) (go (+ i 1) out)) (else (go (+ i 1) (vec-add out (vec-ref sorted i))))))) ;; The tags trimmed, without the empty ones, each once and in order. (: (-> (Vec string) (Vec string))) (defun (clean-tags tags) (sorted-unique (vec-filter #(not (string-empty? &)) (vec-map string-trim tags)))) ;; A new bookmark with a new random id. `Err` when `url` or `archive` is not ;; an absolute URL. The title is cleaned with `clean-title`, and the tags ;; with `clean-tags`. (: (-> string (#:title (Option string)) (#:tags (Vec string)) (#:added Instant) (#:archive (Option string)) (Result string Bookmark))) (defun (make-bookmark url #:title None #:tags [] #:added (now) #:archive None) (def address (string-trim url)) (cond ((not (absolute-url? address)) (Err (str "Not an absolute URL: " url))) (:def link (match archive ((Some a) (Some (string-trim a))) (None None))) ((match link ((Some a) (not (absolute-url? a))) (None #f)) (Err (str "The archive link is not an absolute URL: " (match link ((Some a) a) (None ""))))) (else (Ok (Bookmark (id (uuid-v4)) (url address) (title (match title ((Some t) (clean-title t)) (None None))) (added added) (tags (clean-tags tags)) (archive link)))))) ;; The bookmark with another title, cleaned with `clean-title`, or none. (: (-> Bookmark (Option string) Bookmark)) (defun (bookmark-with-title b text) (record-set b (title (match text ((Some t) (clean-title t)) (None None))))) ;; The bookmark with other tags, cleaned with `clean-tags`. (: (-> Bookmark (Vec string) Bookmark)) (defun (bookmark-with-tags b tags) (record-set b (tags (clean-tags tags)))) ;; The bookmark with another archive link, or none. `Err` when the link is ;; not an absolute URL. (: (-> Bookmark (Option string) (Result string Bookmark))) (defun (bookmark-with-archive b link) (match link ((Some a) (def address (string-trim a)) (if (absolute-url? address) (Ok (record-set b (archive (Some address)))) (Err (str "The archive link is not an absolute URL: " a)))) (None (Ok (record-set b (archive None)))))) ;; --------------------------------------------------------------------------- ;; Stamps ;; --------------------------------------------------------------------------- ;; ;; A stamp is a hybrid logical clock: the wall-clock time in milliseconds, a ;; counter for changes in the same millisecond or while the wall clock is ;; behind, and the device that made the change. Stamps are ordered by the ;; three, in that order, so two devices never make equal stamps. ;; ;; The text of a stamp is `--`: 12 and 4 lower-case hex ;; digits and the device's uuid. All three have a fixed width, so the order ;; of the texts is the order of the stamps. (type (: Stamp (Record (: ms long) (: counter int) (: device Uuid)))) ;; The largest time that 12 hex digits hold: 2^48 - 1 ms, in the year 10889. (: long) (def max-ms 281474976710655L) (: int) (def max-counter 65535) (: (Array byte)) (def hex-digits (string->bytes "0123456789abcdef")) ;; `v` as `width` lower-case hex digits. `v` is from 0 and fits. (: (-> long int string)) (defun (hex-of v width) (def out (: (make-array width) (Array byte))) (let go ((i (- width 1)) (rest v)) (when (>= i 0) (set! out i (get hex-digits (cast int (bitwise-and rest 15L)))) (go (- i 1) (shift-right rest 4)))) (bytes->string out)) ;; The value of the lower-case hex digits of `bytes` from `start` to `end`. ;; `None` for any other byte. (: (-> (Array byte) int int (Option long))) (defun (hex-value bytes start end) (let go ((i start) (v 0L)) (if (= i end) (Some v) (let ((b (cast int (array-ref bytes i)))) (cond ((and (>= b 48) (<= b 57)) (go (+ i 1) (+ (* v 16L) (cast long (- b 48))))) ((and (>= b 97) (<= b 102)) (go (+ i 1) (+ (* v 16L) (cast long (- b 87))))) (else None)))))) (: (-> Stamp string)) (defun (stamp->string s) (str (hex-of (.ms s) 12) "-" (hex-of (cast long (.counter s)) 4) "-" (uuid->string (.device s)))) ;; `None` unless `text` is exactly what `stamp->string` writes. (: (-> string (Option Stamp))) (defun (string->stamp text) (def bytes (string->bytes text)) (if (not (and (= (array-length bytes) 54) (= (cast int (array-ref bytes 12)) 45) (= (cast int (array-ref bytes 17)) 45))) None (match (Tuple (hex-value bytes 0 12) (hex-value bytes 13 17) (string->uuid (string-drop text 18))) ((Tuple (Some ms) (Some counter) (Some device)) ;; Lower case only, so that the text has one spelling. (if (= (uuid->string device) (string-drop text 18)) (Some (Stamp (ms ms) (counter (cast int counter)) (device device))) None)) (_ None)))) ;; Negative when `a` is earlier than `b`, 0 when they are equal, positive when ;; `a` is later. (: (-> Stamp Stamp int)) (defun (stamp-compare a b) (compare (Tuple (.ms a) (.counter a) (uuid->string (.device a))) (Tuple (.ms b) (.counter b) (uuid->string (.device b))))) ;; The latest time and counter a device has made or seen. A new stamp is ;; always later than all of them. (type (: Clock (Record (: last-ms long) (: last-counter int)))) (: Clock) (def clock-zero (Clock (last-ms 0L) (last-counter 0))) ;; The clock after seeing `s`. (: (-> Clock Stamp Clock)) (defun (clock-observe c s) (if (> (compare (Tuple (.ms s) (.counter s)) (Tuple (.last-ms c) (.last-counter c))) 0) (Clock (last-ms (.ms s)) (last-counter (.counter s))) c)) ;; A new stamp of `device` at the wall-clock time `wall-ms`, later than all ;; that `c` has seen, and the clock after it. ;; - The wall clock is used when it is ahead of the clock. ;; - Else the counter goes up, and after 65535 the time goes up by 1 ms. (: (-> Clock long Uuid (Tuple Clock Stamp))) (defun (clock-next c wall-ms device) (def ms (.last-ms c)) (def counter (.last-counter c)) (def s (cond ((> wall-ms ms) (Stamp (ms (if (> wall-ms max-ms) max-ms wall-ms)) (counter 0) (device device))) ((< counter max-counter) (Stamp (ms ms) (counter (+ counter 1)) (device device))) (else (Stamp (ms (+ ms 1L)) (counter 0) (device device))))) (Tuple (clock-observe c s) s)) ;; --------------------------------------------------------------------------- ;; Entries ;; --------------------------------------------------------------------------- ;; A bookmark, or the id of one that was deleted. (type (: EntryState (Union (: Live Bookmark) (: Deleted Uuid)))) ;; `extra` is the fields of the JSON that this version does not know, in the ;; order they were read. They are written back after the known fields. A ;; deleted entry has none. (type (: Entry (Record (: stamp Stamp) (: state EntryState) (: extra (Vec (Tuple string Json)))))) (: (-> Entry Uuid)) (defun (entry-id e) (match (.state e) ((Live b) (.id b)) ((Deleted id) id))) (: (-> Entry bool)) (defun (entry-live? e) (match (.state e) ((Live _) #t) ((Deleted _) #f))) ;; A changed or new bookmark, with no extra fields. (: (-> Stamp Bookmark Entry)) (defun (live-entry s b) (Entry (stamp s) (state (Live b)) (extra []))) ;; A tombstone: the bookmark with this id was deleted. (: (-> Stamp Uuid Entry)) (defun (deleted-entry s id) (Entry (stamp s) (state (Deleted id)) (extra []))) ;; --------------------------------------------------------------------------- ;; Merging ;; --------------------------------------------------------------------------- ;; ;; Entries are kept in a map by the text of their id. For each id the entry ;; with the later stamp wins. Two different entries with the same stamp come ;; only from a fault, as a device never makes a stamp twice; then the one with ;; the greater JSON text wins, so that all devices still choose the same one. ;; True when `a` wins over `b`. (: (-> Entry Entry bool)) (defun (wins? a b) (def order (stamp-compare (.stamp a) (.stamp b))) (cond ((> order 0) #t) ((< order 0) #f) ((= a b) #f) (else (> (compare (json->string (entry->json a)) (json->string (entry->json b))) 0)))) ;; `entries` with `e` in it, when `e` wins over the entry it has for that id. (: (-> (Map string Entry) Entry (Map string Entry))) (defun (merge-entry entries e) (def key (uuid->string (entry-id e))) (match (map-try-ref entries key) ((Some old) (if (wins? e old) (map-set entries key e) entries)) (None (map-set entries key e)))) (: (-> (Map string Entry) (Vec Entry) (Map string Entry))) (defun (merge-entries entries es) (vec-fold (fun (e acc) (merge-entry acc e)) entries es)) ;; `merge-entries`, and how many entries of `es` won: 0 when the merge ;; changed nothing. (: (-> (Map string Entry) (Vec Entry) (Tuple (Map string Entry) int))) (defun (merge-entries/count entries es) (vec-fold (fun (e acc) (def (Tuple m n) acc) (def key (uuid->string (entry-id e))) (match (map-try-ref m key) ((Some old) (if (wins? e old) (Tuple (map-set m key e) (+ n 1)) acc)) (None (Tuple (map-set m key e) (+ n 1))))) (Tuple entries 0) es)) ;; Every entry of `b` merged into `a`. (: (-> (Map string Entry) (Map string Entry) (Map string Entry))) (defun (merge-maps a b) (map-fold (fun (k e acc) (merge-entry acc e)) a b)) (: (-> (Vec Entry) (Map string Entry))) (defun (entries->map es) (merge-entries (map-empty) es)) ;; The clock after seeing every stamp of `entries`. (: (-> (Map string Entry) Clock)) (defun (entries-clock entries) (map-fold (fun (k e c) (clock-observe c (.stamp e))) clock-zero entries)) ;; The bookmarks that are not deleted, the newest first. (: (-> (Map string Entry) (Vec Bookmark))) (defun (live-bookmarks entries) (def live (map-fold (fun (k e acc) (match (.state e) ((Live b) (vec-add acc b)) ((Deleted _) acc))) [] entries)) (vec-sort-by (fun (a b) (compare (Tuple (- 0L (instant->unix-milliseconds (.added a))) (uuid->string (.id a))) (Tuple (- 0L (instant->unix-milliseconds (.added b))) (uuid->string (.id b))))) live)) ;; --------------------------------------------------------------------------- ;; JSON of an entry ;; --------------------------------------------------------------------------- ;; ;; {"id": "", "stamp": "", "url": "https://...", ;; "title": "Example Domain", "added": "2026-11-11T09:12:00Z", ;; "tags": ["a", "b"], "archive": "https://web.archive.org/web/..."} ;; {"id": "", "stamp": "", "deleted": true} ;; ;; - `title`, `tags` and `archive` can be absent. `title` and `archive` can ;; be null. A title is read as `clean-title` makes it. ;; - `added` is ISO 8601 with an offset. It is read as UTC. ;; - Any other field of a bookmark is kept in `extra`. (: (Vec string)) (def known-fields ["id" "stamp" "deleted" "url" "title" "added" "tags" "archive"]) (: (-> (IArray (Tuple string Json)) string (Option Json))) (defun (lookup fields key) (json-object-ref (JsonFields fields) key)) (: (-> (IArray (Tuple string Json)) string (Result string string))) (defun (required-string fields key) (match (lookup fields key) ((Some (JsonStr s)) (Ok s)) ((Some _) (Err (str key ": expected a string"))) (None (Err (str key ": missing"))))) (: (-> string string (Result string string))) (defun (url-field key text) (match (parse-url text) ((Ok u) (if (url-absolute? u) (Ok text) (Err (str key ": not an absolute URL: " text)))) ((Err why) (Err (str key ": not a URL: " why))))) (: (-> (IArray Json) (Result string (Vec string)))) (defun (read-tags items) (def n (iarray-length items)) (let go ((i 0) (out [])) (if (= i n) (Ok (sorted-unique out)) (match (iarray-ref items i) ((JsonStr "") (Err (str "tags[" (int->string i) "]: a tag cannot be empty"))) ((JsonStr t) (go (+ i 1) (vec-add out t))) (_ (Err (str "tags[" (int->string i) "]: expected a string"))))))) (: (-> (IArray (Tuple string Json)) Uuid (Result string Bookmark))) (defun (read-bookmark fields id) (def (Ok url-text) (required-string fields "url") :propagate) (def (Ok url) (url-field "url" url-text) :propagate) (def (Ok added-text) (required-string fields "added") :propagate) (def (Some added) (iso8601->instant added-text) :leave-with (Err (str "added: not an ISO 8601 date and time with an offset: " added-text))) (def (Ok tags) (match (lookup fields "tags") (None (Ok [])) ((Some (JsonArr items)) (read-tags items)) ((Some _) (Err "tags: expected an array of strings"))) :propagate) (def (Ok archive) (match (lookup fields "archive") (None (Ok None)) ((Some JsonNull) (Ok None)) ((Some (JsonStr a)) (match (url-field "archive" a) ((Ok a) (Ok (Some a))) ((Err why) (Err why)))) ((Some _) (Err "archive: expected a string or null"))) :propagate) (def (Ok title) (match (lookup fields "title") (None (Ok None)) ((Some JsonNull) (Ok None)) ((Some (JsonStr t)) (Ok (clean-title t))) ((Some _) (Err "title: expected a string or null"))) :propagate) (Ok (Bookmark (id id) (url url) (title title) (added added) (tags tags) (archive archive)))) (: (-> (IArray (Tuple string Json)) (Result string Entry))) (defun (read-entry fields) (def (Ok id-text) (required-string fields "id") :propagate) (def (Some id) (string->uuid id-text) :leave-with (Err (str "id: not a uuid: " id-text))) (def (Ok stamp-text) (required-string fields "stamp") :propagate) (def (Some stamp) (string->stamp stamp-text) :leave-with (Err (str "stamp: not a stamp: " stamp-text))) (def (Ok deleted) (match (lookup fields "deleted") (None (Ok #f)) ((Some (JsonBool b)) (Ok b)) ((Some _) (Err "deleted: expected true or false"))) :propagate) (if deleted (Ok (deleted-entry stamp id)) (match (read-bookmark fields id) ((Ok b) (Ok (Entry (stamp stamp) (state (Live b)) (extra (vec-filter (fun (f) (not (vec-contains? known-fields (fst f)))) (iarray->vec fields)))))) ((Err why) (Err why))))) ;; The entry that the JSON `j` holds, or why it does not hold one. An object ;; read as a map, not as fields, is read too, but the order of its extra ;; fields is then the map's. (: (-> Json (Result string Entry))) (defun (json->entry j) (match j ((JsonFields fields) (read-entry fields)) ((JsonObj m) (read-entry (vec->iarray (map->vec m)))) (_ (Err "expected an object")))) (: (-> Entry Json)) (defun (entry->json e) (def head [(Tuple "id" (JsonStr (uuid->string (entry-id e)))) (Tuple "stamp" (JsonStr (stamp->string (.stamp e))))]) (match (.state e) ((Deleted _) (JsonFields (vec->iarray (vec-add head (Tuple "deleted" (JsonBool #t)))))) ((Live b) (def titled (match (.title b) ((Some t) (vec-add (vec-add head (Tuple "url" (JsonStr (.url b)))) (Tuple "title" (JsonStr t)))) (None (vec-add head (Tuple "url" (JsonStr (.url b))))))) (def fields (vec-append titled [(Tuple "added" (JsonStr (written (.added b)))) (Tuple "tags" (JsonArr (vec->iarray (vec-map JsonStr (.tags b)))))])) (def with-archive (match (.archive b) ((Some a) (vec-add fields (Tuple "archive" (JsonStr a)))) (None fields))) (JsonFields (vec->iarray (vec-append with-archive (.extra e))))))) ;; --------------------------------------------------------------------------- ;; The document of a device ;; --------------------------------------------------------------------------- ;; ;; {"format": 1, "device": "", "seen": {"": 41, ...}, ;; "records": [, ...]} ;; ;; - `records` is every entry the device knows, its own and those it merged: ;; the whole state, not only its own changes. ;; - `seen` is the highest revision of each other device's file that this ;; device has merged. ;; - Fields other than these four are not kept. (: int) (def document-format 1) (type (: DeviceDoc (Record (: device Uuid) (: seen (Map string long)) (: entries (Vec Entry))))) ;; Compact JSON. The records are in the order of their ids, so the same ;; entries always give the same text. (: (-> DeviceDoc string)) (defun (device-doc->string doc) (def records (vec-sort-by (fun (a b) (compare (uuid->string (entry-id a)) (uuid->string (entry-id b)))) (.entries doc))) (json->string (JsonFields (vec->iarray [(Tuple "format" (JsonInt (cast long document-format))) (Tuple "device" (JsonStr (uuid->string (.device doc)))) (Tuple "seen" (JsonObj (map-map-values JsonInt (.seen doc)))) (Tuple "records" (JsonArr (vec->iarray (vec-map entry->json records))))])))) (: (-> (IArray (Tuple string Json)) (Result string (Map string long)))) (defun (read-seen fields) (def n (iarray-length fields)) (let go ((i 0) (out (map-empty))) (if (= i n) (Ok out) (match (iarray-ref fields i) ((Tuple k (JsonInt r)) (cond ((match (string->uuid k) ((Some _) #f) (None #t)) (Err (str "seen: not a uuid: " k))) ((< r 0L) (Err (str "seen." k ": a revision cannot be negative"))) (else (go (+ i 1) (map-set out k r))))) ((Tuple k _) (Err (str "seen." k ": expected an integer"))))))) (: (-> (IArray Json) (Result string (Vec Entry)))) (defun (read-records items) (def n (iarray-length items)) (let go ((i 0) (out [])) (if (= i n) (Ok out) (match (json->entry (iarray-ref items i)) ((Ok e) (go (+ i 1) (vec-add out e))) ((Err why) (Err (str "records[" (int->string i) "]: " why))))))) ;; The document that `text` holds, or why it does not hold one: not JSON, a ;; format newer than `document-format`, or a field that is not right. (: (-> string (Result string DeviceDoc))) (defun (parse-device-doc text) (def (Ok j) (parse-json text #:objects 'fields) :propagate) (def (JsonFields fields) j :leave-with (Err "expected an object")) (def (Ok format) (match (lookup fields "format") ((Some (JsonInt f)) (Ok f)) ((Some _) (Err "format: expected an integer")) (None (Err "format: missing"))) :propagate) (cond ((> format (cast long document-format)) (Err (str "format " (long->string format) " is newer than this version reads (" (int->string document-format) ")"))) ((< format 1L) (Err (str "format " (long->string format) " is not a format"))) (else (def (Ok device-text) (required-string fields "device") :propagate) (def (Some device) (string->uuid device-text) :leave-with (Err (str "device: not a uuid: " device-text))) (def (Ok seen) (match (lookup fields "seen") (None (Ok (map-empty))) ((Some (JsonFields s)) (read-seen s)) ((Some _) (Err "seen: expected an object"))) :propagate) (def (Ok entries) (match (lookup fields "records") ((Some (JsonArr items)) (read-records items)) ((Some _) (Err "records: expected an array")) (None (Err "records: missing"))) :propagate) (Ok (DeviceDoc (device device) (seen seen) (entries entries))))))