gitoria
All repositories: gitoria
9.6 KB
# `hl:mpackdb` — the MessagePack file databaseA document store in plain files. Server realm. The class surface and itsgenerated API docs live in `MPackDB.hl` and `cursor.hl`(`projects/homepage/generated/pages/mpackdb.md`).```hybrielimport { MPackDB } from 'hl:mpackdb'db = new MPackDB(file = 'users.db', primaryKey = '*id', indexes = ['!email', 'age'])id = db.put({ name = "Alice"; email = "[email protected]"; age = 30; }) \\ 1```## Primary keys| declaration | key | generated by `put()` ||---|---|---|| `*name` | a number | the table's counter: **1, 2, 3, …** || `@name` | a string | a random 12-character id || `name` | a string | nothing — the record must carry it |**A fresh `*id` table starts at 1** (ticket #4, the creator's ruling "start at1"). The counter is stored as `nextId` in `<base>.meta.json`, and an existingtable keeps counting from its stored value. A table written before this ruletherefore goes on from wherever it was, and its record 0 remains record 0.A record put with an explicit key takes that key if it is free, 0 included.## One open table per process (ticket #110)Within one process, a table path has **one** open table, shared by every`open()` — another module instance, another realm, it doesn't matter, theyall get the same handle. The file is never compacted or rewritten while ahandle on it is live; compaction happens only when asked for explicitly(`compactNow()` / `#handle.compact()`) or when the **last** handle on thatpath closes. A second `open()` of an already-open table ignores its own`primaryKey`/`indexes`/`compact` arguments — the schema was fixed by whoeveropened it first.This matters because compaction rewrites `<base>.mpack` and shifts everyrecord after the first tombstone to a new offset. Before this rule, a second`open()` from anywhere in the process ran its own compact-on-open (ticket#21) against the same file, and the first handle's already-looked-up offsetswent stale under it — reads through the first handle then missed ormisread records until something compacted again. Related: ticket #21("opening a table rewrote its files").## Compaction never loses data (ticket #176)- **Across processes**, too: every open handle holds a shared `flock` on`<base>.flock`. A compaction (on open, `compactNow()`, or the last close)needs it exclusive and is **skipped** — not an error; `lastError()` saysso — while another process has the store open.- A handle notices when its data file was rewritten anyway (anotherprocess's compaction, the JS mpackdb): the inode, a shrink, or a newercompaction generation in the meta. It re-reads the meta and re-indexes thenew file before it answers a read. Before, it read its old offsets in thenew file — the middle of other records.- Compaction checks every frame before it renames anything. A frame of size<= 4, a size past the end of the file that is not a torn tail, a liveframe that does not decode to exactly one map, or a deleted offset that isnot a frame start makes it **refuse**: the error names the offset, the datafile and meta stay as they were. A refused compaction on open does not failthe open. The one thing dropped is a torn tail (an append cut short by acrash), and it is reported.- The new data file is fsynced, renamed, its directory fsynced, and onlythen the meta written. The meta's `dataFile` names the data file it waswritten for (inode, size, compaction generation, a checksum of its deletedlist); a meta of a replaced file has its tombstones dropped, not appliedto the new file. `idxstate.json`'s `dataIno` does the same for the indexfiles.## `find(null, null)` over a big table warns (mission 390)`find()` collects every match into one array, so `find(null, null)` holds the WHOLE table at once(measured: about 27 times the file's size in RAM; the tracker's 621 K persons took 5.6 GB, and theobject table and heap grow to match). When such a call builds an array of more than 100 000records, the plugin prints ONE line per table (per open handle) on stderr:mpackdb: <file>: find(null, null) built an array of <n> records; use iterate()The result and the behaviour are unchanged. Stream instead: `for (rec of db.iterate(null, null)) { ... }`(or `db.cursor(null, null)`); a row is freed when the loop is done with it.## Cursors stream, and they are snapshots (mission 393)`iterate(null, null)` (the full scan), `iterate(field, value)` and the indexrange behind `range()` answer an iterator that decodes **one record per`next()`** into a per-record arena that is reset each time. `iterate(null,null)` holds no record at all (memory is O(1) in the table size: the tracker's1.4 M-row episodes walk in the memory of one row); an index query keeps onlythe matching locations (16 bytes each) and reads each record when asked.`find()` / `range()` still drain the cursor into one array, with the sameresults as before.**The rule when the store changes while a cursor is open: the cursor is asnapshot of the moment the query ran.**- It yields the records that existed and were live then: the file size and theset of tombstones are frozen at the start (a record deleted before is neverseen).- A record inserted, or the new version an `update` appends, after the start isnot seen; the old version, if it was live at the start, still is.- A record deleted after the start is still yielded (the cursor reads thebytes it saw).- A compaction, by this process or another, or a foreign rewrite of the filedoes **not** invalidate it and raises no error: the cursor holds areference to the data file it started on (the handle's own open file, sharedand reference-counted: a cursor costs **no file descriptor of its own**, sothousands of abandoned cursors cannot exhaust `ulimit -n`) and reads that (bythen unlinked) file to the end. After a compaction that file stays open, andits disk space lives, until the last cursor on it is exhausted or collected.- Another process's appends and deletes are not seen (the cursor is a view ofthe state this handle had when it started).- A read error mid-stream ends the cursor early.The tombstone set is built once per handle and kept in step with every delete;it is rebuilt after a compaction or when a meta another writer changed isadopted. Lookups, ranges and scans no longer rebuild it on every call, so thecost of a slice no longer grows with the number of tombstones.`count()` counts frame headers without decoding a record.## Leaving a loop early closes the cursor (mission 404)`break` or `return` out of `for (row of db.iterate(...))` (or `find`-style rawiterators) releases the cursor's snapshot **at that moment** — its reference tothe data generation, its scanner, its locations and buffers — instead of whenthe collector finalizes it. Exhausting the cursor does the same; closing twiceis harmless. After an early close the iterator answers `null` from `next()`.`db.openCursors()` counts the cursors of the process that are neither exhaustednor closed and `db.earlyCloses()` counts those closed by an early exit; both aremeant for tests. `for (r of db.cursor(...))` iterates the `Cursor` class, whichdeclares `close()` (mission 418): a loop left early calls it once, and it releasesthe same snapshot (`cursor.close()` by hand works too, twice is harmless).## The index file line format (mission 486)`<base>.<field>.txt` holds one line per entry, sorted: `key,offset,length` and a newline.Offset and length are whole numbers: the place of the record in `<base>.mpack` and its size.- Writing: the key is written as it is, raw, so a key with commas (`a, b`) stays a plain lineand a file without special keys is byte for byte what it always was. Only a key that holds anewline, a carriage return, or starts with a double quote is written as a JSON string(what `JSON.stringify` makes of it), for example `"x\ny",30,31`.- Reading: a line that starts with a double quote is a JSON string followed by `,offset,length`.Any other line is split from the RIGHT: the last two comma separated parts are offset andlength, everything before them is the key. So files written before this rule with a comma in akey read correctly. On a numeric index (`*field`) a raw key is read as a number when it startslike one; a quoted key always stays a string.- Until this rule the reader cut a line at its first comma and dropped the entry; the nextclose then wrote the index file without it, so records went missing from sorted lists aftera restart. The records in `<base>.mpack` were never touched. `idxstate.json` therefore carries`"idxFmt":2` now: an index whose idxstate lacks it is rebuilt from the data once when it isopened, which brings every dropped entry back.- `tools/check-index-keys.mjs <directory>` (node, read only) lists the records whose indexedtext holds a comma, newline, carriage return or leading quote and says which of them aremissing from their index file.## Compatibility with the JS mpackdbThe on-disk format is the JS mpackdb 1.0.7 format: `<base>.mpack`,`<base>.meta.json`, one `<base>.<field>.txt` per index, `<base>.idxstate.json`and the `<base>.lock` protocol (`<base>.flock` and the #176 fields above arethis engine's additions; the JS mpackdb ignores them). Either side reads and changes the other'sfiles. The first id is not part of the format; `nextId` is. Therefore:- a table the JS mpackdb created carries `nextId` and keeps its sequence here,even when that sequence started at 0;- a table Hybriel created carries `nextId` too, and the JS mpackdb continues it;- the one divergence is a table with **no** `.meta.json` yet: Hybriel's firstid is 1, the JS mpackdb's is 0.The other documented divergences are listed at the top of `engine.zig`.
Branches
- f1-broken-json
- f2-api-bugs
- gp-gate-ports
- heap-revert
- hl25-records
- ident-chooser-selector
- mainmain branch
- p51-public-pr-reads
- records-1112
- s25-no-session-on-login-error
- v59
- w52-person-approval
- w52b-approval-followup
- w52c-header-phone
- w53-pulls-speed-pr
- w54-repo-rename-pr
- w55-rename-org
- w56-owner-members
- w62-pr-close
- w63-force-push
- w64-org-slash
Latest commits
- 54927c9cgitoria#46: PR statuses and required checks before merge (merge w46-status)mre
- 187e1871gitoria#46: badges without decorative bordersmre
- 6b022798gitoria#46: tests/status.mjs in GATESmre
- c6162f00gitoria#46: status badges on /pulls, Required before merge in Settingsmre
- e5a0b64egitoria#46: PUT statuses/<sha>, required contexts block the merge on the servermre
- 26a140e3gitoria#44: reviews, inline threads, replies, conversation for apps (merge w44-reviews)mre
- 888dbf87gitoria#44: unknown API paths answer the contract's JSON 404 and sit above the page routesmre
- ea587d90gitoria#44: reviews with inline threads, replies, resolve and the PR conversation for apps (lib/reviews.hl, tests/reviews.mjs)mre
- 49533a50gitoria#43: signed events to connected apps (merge w43-events)mre
- 1a1e87d5gitoria#43: the sender never writes the apps row; Settings shows the newest deliverymre
- cd442066gitoria#43: app-auth unit test reads the apps table from its new filemre
- 5dccbe38gitoria#43: in-flight rows are left alone by the other process; gate in deploy.sh; READMEmre
- 8c8805f3merge main (gitoria#42), delivery log and redelivery routes, sweep fixmre
- 5a996ea8gitoria#42: short-lived app tokens, read-only git fetch with them (merge w42-app-token)mre
- afdb0cbfgitoria#43: rename the moved helper (name clash in the browser build)mre
- 15e01e94gitoria#43: tests/events.mjs and its probemre
- 77829b73gitoria#43: signed events to connected apps (deliveries table, sender timer, pull_request events, ping)mre
- b5d696fegitoria#42: app tokens (gat_, one hour), appOfRequest, app token as the git read passwordmre
- 1997e77dgitoria#40: stable PR numbers, refs/pull/N/head, ssh pushes reach the app (merge w40-pr-number)mre
- 9364fb16gitoria#40: ssh pushes call /__git/pushed before and after (ensurePulls, notifyPush, syncPulls); gate over the sshd imagemre