8000 GitHub - project-minigraf/minigraf-wasm: Browser WASM and WASI bindings for Minigraf — bi-temporal graph database · GitHub
[go: up one dir, main page]

Skip to content

About

Browser WASM and WASI bindings for Minigraf — bi-temporal graph database

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

83 Commits

Folders and files

Repository files navigation

minigraf (WebAssembly)

WebAssembly builds of Minigraf, an embedded graph database. Use bi-temporal Datalog queries without running a separate database server. The browser and WASI packages have different storage options, described below.

This branch documents the 3.x API. An unversioned npm install uses npm's latest tag. If that tag still points to 2.x, use the 2.x README. For a 3.x prerelease, install an exact version listed on the relevant npm package page below.

This repo publishes two packages:

Package Target Install
@minigraf/browser Browser (wasm-bindgen) npm install @minigraf/browser
@minigraf/wasi Node.js / WASI runtimes npm install @minigraf/wasi

Browser (@minigraf/browser)

import init, { BrowserDb } from '@minigraf/browser'

await init()

const db = await BrowserDb.open('mydb')   // IndexedDB-backed; BrowserDb.openInMemory() for tests
await db.execute('(transact [[:alice :name "Alice"]])')

const result = JSON.parse(await db.execute('(query [:find ?n :where [?e :name ?n]])'))
console.log(result.results[0][0])  // "Alice"

Choosing a storage mode

From core v3.0.0, BrowserDb.openOpfs(name) stores a <name>.graph file in the Origin Private File System (OPFS). It requires a dedicated module worker in a secure context (HTTPS or localhost). Pages are read on demand through a 256-page cache; commits write directly to the file, with no WAL. OPFS starts at Tier 2 support. BrowserDb.open(name) uses IndexedDB on the main thread or in a worker and keeps the database's pages in wasm memory. openInMemory() does not persist data.

Using the same name in IndexedDB and OPFS opens separate databases. There is no automatic fallback or migration. Invalid OPFS names (empty, ., .., a slash/backslash, or NUL) throw [API-017]; names are not normalised. OPFS stores the database in <name>.graph and stages imports in <name>.graph-import until the import or recovery finishes. No database name maps to the staging file, so no suffix is reserved. A second worker/tab opening an in-use OPFS file gets [STG-026]. Call close() to release its handle and lock immediately; terminating the worker also releases it. Main-thread or unsupported OPFS opens give [API-026].

close() is synchronous and idempotent in all modes. It performs no save and discards an open transaction. Earlier cursors and prepared queries fail with [API-018] after close. Calling close() from a running UDF or using the database during an OPFS import fails with [API-027]. You can still free dependent objects, close cursors, and roll back transactions. An OPFS import accepts an empty blob, a complete and verified v8 image with a usable metadata page (including an image of an empty v8 database), or a supported v7 image that can be migrated in full. If interrupted, reopening gives you the complete old or new database. A successful import invalidates earlier cursors and prepared queries. A failure while replacing the database closes the handle; reopen to recover.

A write resolves after both page and meta flushes. Browser flush() does not promise power-loss durability. A rejected write is unconfirmed: it may still be present in full when you reopen. Later writes fail with [STG-046] until you close and reopen it. If the newest metadata page becomes corrupt, OPFS can reopen the older valid page and lose an acknowledged commit. Origin quota and eviction are browser-managed, as with IndexedDB. The application may request navigator.storage.persist(); Minigraf never does so itself. See the core durability contract.

OPFS worker

Serve these files alongside the installed package (the worker's import URL below assumes /node_modules is served; a bundler may resolve the package instead). Save this as opfs-example-worker.js:

import init, { BrowserDb } from '/node_modules/@minigraf/browser/minigraf_wasm.js'

const ready = init()
self.onmessage = async ({ data: { name } }) => {
  let db
  try {
    await ready
    db = await BrowserDb.openOpfs(name)
    await db.execute('(transact [[:alice :name "Alice"]])')
    const names = JSON.parse(await db.execute('(query [:find ?n :where [?e :name ?n]])')).results
    self.postMessage({ names })
  } catch (error) {
    self.postMessage({ error: String(error) })
  } finally {
    db?.close()
  }
}

From a page module:

const worker = new Worker('./opfs-example-worker.js', { type: 'module' })
worker.onmessage = ({ data }) => {
  if (data.error) console.error(data.error)
  else console.log(data.names) // [["Alice"]]
  worker.terminate()
}
worker.postMessage({ name: 'agent-memory' })

To move a database between modes, export its v8 bytes with source.exportGraph() and pass them to await target.importGraph(bytes) in the other mode. With a worker, send the Uint8Array by postMessage; after importing, close both handles when finished. Migration is explicit and replaces the target's contents.

Query cursors

db.query(datalog) returns a BrowserCursor whose answer is fixed when it opens. nextBatch(n) returns up to n rows as a JSON array (encoded like execute()'s results), or undefined at the end; close() releases it. A transact, retract or rule throws [API-012].

const cursor = db.query('(query [:find ?n :where [?e :name ?n]])')
try {
  let batch
  while ((batch = cursor.nextBatch(1000)) !== undefined) {
    for (const row of JSON.parse(batch)) console.log(row)
  }
} finally {
  cursor.close()
}

Prepared queries

db.prepare(datalog) parses a query once and returns a BrowserPreparedQuery; execute(bindings) returns the same JSON as db.execute(). query(bindings) returns a BrowserCursor. Both are synchronous. Use slot names without the $ as keys. The supported values are a boolean, a string, null, a bigint or a number (an integer when Number.isInteger accepts it, else a float), or a typed { type, value } form: { type: 'float', value: 2 }, 'keyword', 'ref', { type: 'entity', value: uuid }, { type: 'txCount' | 'timestamp', value } for :as-of, and { type: 'anyValidTime' } for :valid-at. Unsupported binding values throw TypeError. A missing slot throws [API-022], a slot in an attribute position [API-023], and a value of the wrong kind for its slot [API-024].

const pq = db.prepare('(query [:find ?n :where [?e :age $age] [?e :name ?n]])')
JSON.parse(pq.execute({ age: 30 })).results

withMaxDerivedFacts(n), withQueryMemoryLimit(bytes) and withMaxIterations(n) each return a new BrowserPreparedQuery with that limit, leaving the original unchanged. Both keep the database open. An allowed keyword in the query text still overrides them. The argument is a non-negative integer number; at or above 2^32 − 1 (the browser's largest usize) it means no limit, and a negative, fractional or non-finite number throws [API-017]. These setters are the browser's way to set a query memory limit: BrowserDb takes no options, so the default override list applies and :query-memory-limit in query text throws [API-025].

const reach = db.prepare('(query [:find ?x ?y :where (reach ?x ?y)])')
const small = reach.withMaxDerivedFacts(10000).withQueryMemoryLimit(16 * 1024 * 1024)
small.execute({}) // [INT-020] or [QRY-012] past a limit; reach is unchanged

User functions

db.registerPredicate(name, fn) adds a predicate, called in a query as [(name ?v)]. db.registerAggregate(name, { init, step, finish }) adds an aggregate, used in :find as (name ?v) and as a window function with :over: init() returns a new accumulator (one per group or window partition), step(acc, value) returns the updated accumulator, and finish(acc, count) returns the result. count is the number of values passed to step. All are called as plain functions, with no this.

db.registerPredicate('adult?', (v) => v.type === 'integer' && v.value >= 18n)
db.registerAggregate('product', {
  init: () => 1n,
  step: (acc, v) => acc * v.value,
  finish: (acc) => acc,
})
await db.execute('(query [:find ?n :where [?e :age ?a] [(adult? ?a)] [?e :name ?n]])')
await db.execute('(query [:find (product ?a) :where [?e :age ?a]])')
  • Values. A function receives each value as a { type, value } object: type is 'string', 'integer' (value a bigint), 'float', 'boolean', 'ref' (an entity UUID string), 'keyword', 'null' (no value) or 'set' (value an array of these). A predicate returns a boolean. finish returns a value in any form a prepared query's bindings accept: a plain value or a typed { type, value } form.
  • Errors. A callback exception, a non-boolean predicate result, or an invalid finish result stops the query with [QRY-014]. An exception uses its message if available, otherwise String(e). Registration throws a TypeError when a function is missing, and [INT-040] when the name is taken.
  • Lifecycle. Registration is synchronous. A query that is already open (a BrowserCursor) does not see a function registered after it; every query opened afterwards does. The database keeps each function until it, and every cursor and prepared query opened from it, are freed. There is no unregister.
  • Cost. Each value is one call into JavaScript, so a function over many rows costs one call per value.
  • Calling the database from a function. A function runs synchronously inside the query that calls it. From there query, prepare (and the prepared query's execute/query), exportGraph, registerPredicate and registerAggregate run at once. execute, checkpoint and importGraph return a Promise that starts only after the outer query has returned, so the function cannot wait for it, and the outer query does not see its write.

Write transactions

db.beginWrite() opens a write transaction (minigraf#824; first in the release built on core v3.0.0, core commit 32d71ce0). Run transact, retract, and query statements in the transaction. Queries see the changes staged there. Commit to apply them together, or roll back to discard them:

const tx = db.beginWrite()
try {
  tx.execute('(transact [[:alice :balance 70] [:bob :balance 80]])')
  const [[balance]] = JSON.parse(tx.execute('(query [:find ?b :where [:alice :balance ?b]])')).results
  if (balance >= 0) await tx.commit()
} finally {
  tx.rollback() // does nothing once committed
}
  • beginWrite() takes no options. tx.execute(datalog) is synchronous and returns execute's JSON; a staged write returns {"ok":true}, and a statement that throws stages nothing and leaves the transaction open. No cursors or prepared queries inside a transaction.
  • await tx.commit() applies everything as one transaction at once (other code sees the facts as soon as commit() is called) and resolves after the IndexedDB write or OPFS flushes. There is no WAL. A failed storage operation rejects it, as a failed execute write does. tx.rollback() discards the transaction, and so does freeing it while open (tx.free()).
  • After a commit (successful or not) or a rollback the transaction is finished: execute, incomingRefs and commit throw or reject with [API-018]; rollback does nothing.
  • While it is open, every other call on its database that reads or writes (execute, query, prepare, checkpoint, importGraph, another beginWrite, a prepared query's execute/query) throws or rejects with [INT-001], including calls from a query callback run by the transaction. Previously opened cursors still return rows. Use finally to roll back any transaction that is still open; garbage collection may never free it.
  • Rules registered inside a transaction stay registered after a rollback.
  • Reentry from a registered user function running in the transaction's own statement into that same transaction's incomingRefs, execute, commit or rollback throws or rejects with [INT-001]. The transaction remains usable afterwards.

Incoming references

tx.incomingRefs(target: string, maxLinks: number, maxRecords: number): IncomingRefs is synchronous. Pass an entity UUID string and both limits as finite integers from 0 through 4,294,967,295 (0..=2^32-1). Zero is a cap, and -0 counts as zero. No value disables either limit. maxLinks caps live links. maxRecords caps examined records, including obsolete versions and retractions. recordsExamined never exceeds maxRecords.

The result is a plain object with this TypeScript discriminated union:

type IncomingRefs =
  | { status: 'complete'; links: Array<{ source: string; attribute: string }>; recordsExamined: number }
  | { status: 'exhausted'; budget: 'links' | 'records'; recordsExamined: number }

Only scalar Ref values count. Keywords (even aliases naming the target), UUID-looking strings and references inside sets are excluded. Valid time is ignored. The lookup sees committed data plus earlier statements in this transaction, including staged retractions. Sources are canonical lowercase UUID strings; link order is unspecified. An unknown target completes with an empty list, even with both budgets zero.

Look up references before staging deletions, and delete only if the result is complete. If it is exhausted, retry with higher limits or abandon the deletions. An exhausted result has no links property. Exhaustion does not undo earlier staged writes:

const tx = db.beginWrite()
try {
  const target = '3d0665da-b9c8-51cf-89e6-bef40ac4981c'
  let result = tx.incomingRefs(target, 100, 1000)
  if (result.status === 'exhausted') {
    result = tx.incomingRefs(target, 1000, 10000) // retry in the same transaction
  }
  if (result.status === 'complete') {
    for (const { source, attribute } of result.links) {
      // Retract ea
8000
ch exact Ref link only after complete discovery.
      tx.execute(`(retract [[#uuid "${source}" ${attribute} #uuid "${target}"]])`)
    }
    await tx.commit()
  } // still exhausted: abandon; finally rolls back
} finally {
  tx.rollback()
}

Invalid UUIDs or budgets throw [API-017]. A finished transaction (including an in-flight commit) or closed database throws [API-018] before argument validation. Reentry from the transaction's own user function throws [INT-001] before lifecycle or argument validation. Complete, exhausted and invalid-argument calls leave the transaction open and preserve its earlier writes. Other read/storage failures remain errors, never complete-empty or exhausted results.

This read stages nothing, consumes no transaction number and starts no flush. It works in memory, IndexedDB and OPFS. After an IndexedDB flush failure, a new transaction can still call incomingRefs over readable state, including applied but unconfirmed writes; commits remain refused with [STG-046] until close/reopen. Commit durability remains the commit() Promise.

Not available in the browser

BrowserDb.open() keeps its pages in memory and writes them to IndexedDB; OPFS mode uses a .graph file inside the origin. Neither mode exposes a native filesystem path or WAL. OPFS uses its exclusive sync handle as a browser lock. The file-backed options of the other bindings (read_only, allow_unlocked, page_cache_size, the WAL options) cannot be configured here. BrowserDb takes no open options at all: the override list (allow_overrides), the query limits and transaction_chunk_facts keep their defaults, and a prepared query's limits are set with its setters. The raw log writer (LogWriter) is not built for wasm32, and the fact log is not exposed in the browser. To move data between a browser and a native database, use exportGraph() / importGraph().

WASI (@minigraf/wasi)

The package is the Minigraf REPL compiled to wasm32-wasip1, not a library: it reads Datalog commands from stdin and prints the results to stdout, over an in-memory database. In repl.mjs:

import { WASI } from "node:wasi";
import { startMinigrafWasi } from "@minigraf/wasi";

const wasi = new WASI({ version: "preview1", args: ["minigraf"], env: process.env });
await startMinigrafWasi(wasi);
printf '%s\n' '(transact [[:alice :name "Alice"]])' '(query [:find ?n :where [?e :name ?n]])' | node repl.mjs

Every command the REPL reads commits on its own, as one transaction, and a command that fails leaves the ones before it committed. There are no explicit transactions (no begin, commit or rollback commands, minigraf#824); for those, use @minigraf/browser or another binding.

For the browser, or for a database that persists, use @minigraf/browser, or minigraf in Node.js.

Building from source

Requires Rust stable toolchain and wasm-pack.

# Browser target
wasm-pack build --target web --features browser

# WASI target
cargo build --target wasm32-wasip1 --release

Cascade release

Core sends core-release with client_payload.version set to the full tag, for example v3.0.0-alpha. After the #937 branch move, the default branch's release workflow builds 3.x from main and 2.x from v2.x, and updates only that source branch. Unsupported versions, missing branches and production runs dispatched from a non-default workflow fail.

The workflow commit supplies CI, packaging and verification for both source lines. The prepared source pins the exact crates.io version and keeps the browser feature. Before building, the workflow checks the locked dependencies and resolved features. WASI uses the exact commit of the matching core tag and records it as minigrafCoreSha in the npm package and build records. Core does not track a lockfile, so the WASI job resolves and checks one before building with --locked. It saves that file with the build and test results. Ordinary CI derives that commit from the source's registry pin or exact Git revision, never a moving core branch. The WASI package remains an in-memory REPL.

The source branch determines which browser tests run, not the package label. 3.x requires OPFS README example checks, TypeScript checks, and tests in Chromium and Firefox on Linux and in WebKit on Linux and macOS. 2.x tests Chromium and advertises IndexedDB only. Both lines run WASI consumer tests on Linux, macOS, and Windows. Browser test records name the actual engine. Linux WebKit tests for the known OPFS limitation; macOS WebKit must support OPFS.

Both @minigraf/browser and @minigraf/wasi keep the unprefixed SemVer version. A prerelease stamps both README installation commands with its exact version; a stable release restores the unqualified commands. Every npm publish supplies an explicit dist-tag. One decision covers both packages: prereleases use next, and stable releases use latest unless a higher stable major is already on latest for either package; then both packages use maintenance-v<major> (for example, maintenance-v2). A channel already pointing newer is preserved, and channel disagreements are reported. Publication and channel repair share a repository-wide concurrency group, with channels read after acquiring it.

A missing older package is published with the explicit holding tag release-<version> (for example, release-3.0.0-alpha) without moving its channel. Holding tags are retained. The maintenance and holding tags avoid npm's rejection of SemVer ranges such as v2; see npm's tag restrictions.

Publishing uses the existing npm environment and GitHub OIDC identity. The workflow installs npm 11.21.3 so npm dist-tag add can authenticate even when no package needs uploading. On both packages, the trusted publisher for this repository's release.yml must permit direct publishing and have Allow npm dist-tag enabled separately; publishing permission does not imply tag access. A failed repair stops the run with the package, tag and required permission in the error. See npm's trusted-publisher instructions. These package settings and an actual authenticated repair must be verified in a hosted production run; public registry reads cannot establish write permission.

Retry from the default workflow with the same full tag:

gh workflow run release.yml --ref main -f version=v3.0.0-alpha

The immutable annotated binding tag identifies the original tested commit and build records. A retry authenticates the original run, verifies the exact dependency, checks that the commit still belongs to its source branch, and compares npm digests. It uploads only missing original tarballs and repairs npm dist-tags even if nothing is uploaded. It then installs and tests the exact version from npm. Do not delete or move a tag, replace published bytes, or rebuild different bytes to get past a conflict. A legacy tag without evidence, expired artifacts or a digest mismatch stops recovery for investigation. A new release whose branch advanced before tagging must prepare and test again. Failed production releases or recoveries are marked release-broken.

The workflow requests 90 days of retention for the original tested artifacts and records. Repository settings must allow it. Losing these files prevents safe recovery. Same-tag runs are serialized without canceling the running release. GitHub's default concurrency queue has one pending slot, so another arrival can cancel a pending run, including one waiting for npm publication. Redispatch a canceled release if still needed; cancellation is not publication success.

To rehearse a release, manually run release.yml from main with rehearsal=true. Omit source_alias:

  • For 3.x, use version=v3.0.0-alpha and set candidate to the exact 40-character core commit SHA. The workflow tests main. Browser and WASI builds both use the same core commit; its crate version is recorded separately from the npm package version.
  • For 2.x, use version=v2.0.12 (or the 2.x version you want to test) and omit candidate. The workflow tests v2.x against the published core version.

Production does not accept aliases or candidates. A repository dispatch cannot start a rehearsal. In either mode, a Git bundle carries the prepared commit without a temporary remote branch. Rehearsals build and test from the selected branch head and show what a production retry would select. They do not push or delete refs, publish packages, change dist-tags, or update issues. The summary records the workflow, source and prepared commits, branch and alias, dependency and WASI versions and commits, artifact hashes, and consumer tests that ran.

See #960 for the rehearsal records, #937 for post-move checks, and #929 for publication and final dist-tag checks.

License

MIT OR Apache-2.0

About

Browser WASM and WASI bindings for Minigraf — bi-temporal graph database

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

0