@cossackframework/romedb 0.0.0 → 0.9.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +59 -2
- package/agent-docs.json +56 -0
- package/package.json +43 -2
- package/src/cloudflare.ts +159 -0
- package/src/database.ts +498 -0
- package/src/dev.d.ts +40 -0
- package/src/dev.js +246 -0
- package/src/directory.ts +46 -0
- package/src/index.ts +79 -0
- package/src/node-directory.ts +31 -0
- package/src/node.ts +252 -0
- package/src/pending.ts +114 -0
- package/src/rows.ts +55 -0
- package/src/rql.ts +91 -0
- package/src/testing.ts +159 -0
- package/src/transport.ts +133 -0
- package/src/values-entry.ts +3 -0
package/src/pending.ts
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { validatePrepared, type PreparedWrite } from '@romedb/client';
|
|
2
|
+
|
|
3
|
+
/** A saved write persisted before dispatch, so an uncertain outcome can be recovered by exact body. */
|
|
4
|
+
export interface PendingWrite {
|
|
5
|
+
readonly request: PreparedWrite;
|
|
6
|
+
/** Unix milliseconds when the write was saved. */
|
|
7
|
+
readonly savedAt: number;
|
|
8
|
+
/** Application label for reconciliation, such as `cms.resource.update`. */
|
|
9
|
+
readonly kind?: string;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Durable storage for writes that have been prepared but not confirmed.
|
|
14
|
+
* `put` must be durable when it resolves and must refuse to replace a different body.
|
|
15
|
+
*/
|
|
16
|
+
export interface PendingWriteStore {
|
|
17
|
+
readonly durability: 'process' | 'durable';
|
|
18
|
+
put(id: string, write: PendingWrite): Promise<void>;
|
|
19
|
+
get(id: string): Promise<PendingWrite | undefined>;
|
|
20
|
+
delete(id: string): Promise<void>;
|
|
21
|
+
/** Oldest first (by `savedAt`, then request ID), after `after` when it is given. */
|
|
22
|
+
list(options?: PendingListOptions): Promise<readonly PendingWrite[]>;
|
|
23
|
+
/** IDs of saved writes the latest `list` could not read and left out, for the recovery report. */
|
|
24
|
+
unreadable?(): readonly string[];
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface PendingListOptions {
|
|
28
|
+
limit?: number;
|
|
29
|
+
/** Continue after this write, as {@link pendingCursor} gives it, to page past the oldest. */
|
|
30
|
+
after?: PendingCursor;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** A position in the oldest-first order of saved writes. */
|
|
34
|
+
export interface PendingCursor {
|
|
35
|
+
readonly savedAt: number;
|
|
36
|
+
readonly id: string;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function pendingCursor(write: PendingWrite): PendingCursor {
|
|
40
|
+
return { savedAt: write.savedAt, id: preparedRequestId(write.request) };
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Sort saved writes oldest first, keep those after the cursor, and cut to the limit. */
|
|
44
|
+
export function pagePendingWrites(writes: readonly PendingWrite[], options: PendingListOptions = {}): PendingWrite[] {
|
|
45
|
+
const keyed = writes.map(write => ({ write, cursor: pendingCursor(write) }));
|
|
46
|
+
keyed.sort((a, b) => compareCursors(a.cursor, b.cursor));
|
|
47
|
+
const after = options.after;
|
|
48
|
+
const page = after ? keyed.filter(entry => compareCursors(entry.cursor, after) > 0) : keyed;
|
|
49
|
+
return page.slice(0, options.limit ?? page.length).map(entry => entry.write);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function compareCursors(a: PendingCursor, b: PendingCursor): number {
|
|
53
|
+
return a.savedAt - b.savedAt || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export class PendingWriteConflictError extends Error {
|
|
57
|
+
constructor(id: string) {
|
|
58
|
+
super(`A different pending write is already saved as ${id}.`);
|
|
59
|
+
this.name = 'PendingWriteConflictError';
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Serialize a pending write as stored text. */
|
|
64
|
+
export function encodePendingWrite(write: PendingWrite): string {
|
|
65
|
+
validatePrepared(write.request);
|
|
66
|
+
return JSON.stringify({ version: 1, savedAt: write.savedAt, ...(write.kind === undefined ? {} : { kind: write.kind }), request: write.request });
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Parse stored text, validating the saved request envelope. */
|
|
70
|
+
export function decodePendingWrite(stored: string): PendingWrite {
|
|
71
|
+
const value = JSON.parse(stored) as { version?: unknown; savedAt?: unknown; kind?: unknown; request?: unknown };
|
|
72
|
+
if (value.version !== 1 || !Number.isSafeInteger(value.savedAt) || (value.kind !== undefined && typeof value.kind !== 'string')) throw new TypeError('invalid pending write');
|
|
73
|
+
validatePrepared(value.request);
|
|
74
|
+
return Object.freeze({ request: Object.freeze(value.request as PreparedWrite), savedAt: value.savedAt as number, ...(value.kind === undefined ? {} : { kind: value.kind as string }) });
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export function samePendingWrite(a: PendingWrite, b: PendingWrite): boolean {
|
|
78
|
+
return a.request.body === b.request.body && a.request.url === b.request.url && a.request.databaseId === b.request.databaseId && a.request.version === b.request.version && queryVersion(a.request) === queryVersion(b.request);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** The request ID of a saved write. */
|
|
82
|
+
export function preparedRequestId(request: PreparedWrite): string {
|
|
83
|
+
return validatePrepared(request).requestId;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function queryVersion(request: PreparedWrite): number | undefined {
|
|
87
|
+
return request.version === 2 ? request.queryVersion : undefined;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Process memory. For tests and single-process development only. */
|
|
91
|
+
export class MemoryPendingWriteStore implements PendingWriteStore {
|
|
92
|
+
readonly durability = 'process' as const;
|
|
93
|
+
readonly #writes = new Map<string, string>();
|
|
94
|
+
|
|
95
|
+
async put(id: string, write: PendingWrite): Promise<void> {
|
|
96
|
+
const stored = encodePendingWrite(write);
|
|
97
|
+
const existing = this.#writes.get(id);
|
|
98
|
+
if (existing !== undefined && !samePendingWrite(decodePendingWrite(existing), write)) throw new PendingWriteConflictError(id);
|
|
99
|
+
this.#writes.set(id, stored);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
async get(id: string): Promise<PendingWrite | undefined> {
|
|
103
|
+
const stored = this.#writes.get(id);
|
|
104
|
+
return stored === undefined ? undefined : decodePendingWrite(stored);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
async delete(id: string): Promise<void> {
|
|
108
|
+
this.#writes.delete(id);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
async list(options: PendingListOptions = {}): Promise<readonly PendingWrite[]> {
|
|
112
|
+
return pagePendingWrites([...this.#writes.values()].map(decodePendingWrite), options);
|
|
113
|
+
}
|
|
114
|
+
}
|
package/src/rows.ts
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import type { BatchResult, QueryResult, Value } from '@romedb/client';
|
|
2
|
+
|
|
3
|
+
export type Row = { [column: string]: Value };
|
|
4
|
+
|
|
5
|
+
/** Columns repeat when a query projects the same name twice. Rows are positional; alias the duplicates. */
|
|
6
|
+
export class DuplicateColumnError extends Error {
|
|
7
|
+
readonly columns: string[];
|
|
8
|
+
constructor(columns: string[]) {
|
|
9
|
+
super(`Query result repeats column ${columns.map(name => JSON.stringify(name)).join(', ')}; alias the duplicates before mapping rows to objects.`);
|
|
10
|
+
this.name = 'DuplicateColumnError';
|
|
11
|
+
this.columns = columns;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export class CardinalityError extends Error {
|
|
16
|
+
constructor(expected: string, actual: number) {
|
|
17
|
+
super(`Expected ${expected} row, got ${actual}.`);
|
|
18
|
+
this.name = 'CardinalityError';
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Map positional rows to objects by column name. Duplicate names are an error, never collapsed. */
|
|
23
|
+
export function objects<T extends Row = Row>(result: QueryResult): T[] {
|
|
24
|
+
const seen = new Set<string>();
|
|
25
|
+
const duplicates = new Set<string>();
|
|
26
|
+
for (const name of result.columns) (seen.has(name) ? duplicates : seen).add(name);
|
|
27
|
+
if (duplicates.size) throw new DuplicateColumnError([...duplicates]);
|
|
28
|
+
return result.rows.map(row => {
|
|
29
|
+
const object: Row = {};
|
|
30
|
+
result.columns.forEach((name, index) => { object[name] = row[index]!; });
|
|
31
|
+
return object as T;
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function first<T extends Row = Row>(result: QueryResult): T | undefined {
|
|
36
|
+
return result.rows.length ? objects<T>({ ...result, rows: [result.rows[0]!] })[0] : undefined;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function one<T extends Row = Row>(result: QueryResult): T {
|
|
40
|
+
if (result.rows.length !== 1) throw new CardinalityError('exactly one', result.rows.length);
|
|
41
|
+
return objects<T>(result)[0]!;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** The single value of a one-row, one-column result. */
|
|
45
|
+
export function scalar(result: QueryResult): Value {
|
|
46
|
+
if (result.rows.length !== 1 || result.columns.length !== 1) throw new CardinalityError('exactly one single-column', result.rows.length);
|
|
47
|
+
return result.rows[0]![0]!;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Affected rows of one statement in a batch, as a number. */
|
|
51
|
+
export function affected(batch: BatchResult, statement: number): number {
|
|
52
|
+
const result = batch.results[statement];
|
|
53
|
+
if (!result) throw new RangeError(`batch has no statement ${statement}`);
|
|
54
|
+
return Number(result.affected);
|
|
55
|
+
}
|
package/src/rql.ts
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import type { RomeDB, WriteCallOptions } from './database';
|
|
2
|
+
import { Float64, Record, type Value } from '@romedb/client';
|
|
3
|
+
|
|
4
|
+
type Bindable = string | number | null | bigint | boolean;
|
|
5
|
+
|
|
6
|
+
export interface RqlStatement {
|
|
7
|
+
bind(...values: Bindable[]): RqlBound;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export interface RqlBound {
|
|
11
|
+
first<T>(): Promise<T | null>;
|
|
12
|
+
all<T>(): Promise<{ results: T[] }>;
|
|
13
|
+
run(): Promise<{ meta: { changes?: number } }>;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** D1's `prepare().bind()` shape, as used by the portable SQL ledgers in `@cossackframework/core`. */
|
|
17
|
+
export interface RqlDatabase {
|
|
18
|
+
prepare(sql: string): RqlStatement;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface RqlDatabaseOptions {
|
|
22
|
+
/** Pending-write label for reconciliation. Default `rql`. */
|
|
23
|
+
kind?: string;
|
|
24
|
+
signal?: AbortSignal;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* A D1-shaped facade over relational RomeDB tables. Each call is one request: SELECT and
|
|
29
|
+
* WITH statements read a fresh snapshot, everything else is one atomic write whose
|
|
30
|
+
* affected count is reported as `meta.changes`. Integer results that fit become numbers.
|
|
31
|
+
*/
|
|
32
|
+
export function rqlDatabase(db: RomeDB, options: RqlDatabaseOptions = {}): RqlDatabase {
|
|
33
|
+
return {
|
|
34
|
+
prepare(sql: string): RqlStatement {
|
|
35
|
+
const text = numberPlaceholders(sql);
|
|
36
|
+
const reading = /^\s*(?:SELECT|WITH)\b/i.test(sql) && !/\bRETURNING\b/i.test(sql);
|
|
37
|
+
return {
|
|
38
|
+
bind(...values: Bindable[]): RqlBound {
|
|
39
|
+
const params: { [key: string]: Value } = {};
|
|
40
|
+
values.forEach((value, index) => { params[`$p${index + 1}`] = value as Value; });
|
|
41
|
+
const statement = values.length ? { rql: text, params } : { rql: text };
|
|
42
|
+
// A rolled-back write conflict re-runs as if the writes were serial.
|
|
43
|
+
const call: WriteCallOptions = { kind: options.kind ?? 'rql', retryConflicts: 5, ...(options.signal ? { signal: options.signal } : {}) };
|
|
44
|
+
const execute = () => reading ? db.read([statement], call) : db.write([statement], call);
|
|
45
|
+
const rows = async () => {
|
|
46
|
+
const result = (await execute()).results[0]!;
|
|
47
|
+
return result.rows.map(row => Object.fromEntries(result.columns.map((name, index) => [name, plain(row[index]!)])));
|
|
48
|
+
};
|
|
49
|
+
return {
|
|
50
|
+
async first<T>() { return ((await rows())[0] ?? null) as T | null; },
|
|
51
|
+
async all<T>() { return { results: await rows() as T[] }; },
|
|
52
|
+
async run() { return { meta: { changes: Number((await execute()).results[0]!.affected) } }; },
|
|
53
|
+
};
|
|
54
|
+
},
|
|
55
|
+
};
|
|
56
|
+
},
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Rewrite positional `?` placeholders to `$p1..$pn`, leaving quoted text alone. */
|
|
61
|
+
export function numberPlaceholders(sql: string): string {
|
|
62
|
+
let out = '';
|
|
63
|
+
let index = 0;
|
|
64
|
+
for (let i = 0; i < sql.length; i++) {
|
|
65
|
+
const char = sql[i]!;
|
|
66
|
+
if (char === "'" || char === '"') {
|
|
67
|
+
const end = closing(sql, i, char);
|
|
68
|
+
out += sql.slice(i, end + 1);
|
|
69
|
+
i = end;
|
|
70
|
+
} else if (char === '?') out += `$p${++index}`;
|
|
71
|
+
else out += char;
|
|
72
|
+
}
|
|
73
|
+
return out;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function closing(sql: string, start: number, quote: string): number {
|
|
77
|
+
for (let i = start + 1; i < sql.length; i++) {
|
|
78
|
+
if (sql[i] === quote) {
|
|
79
|
+
if (sql[i + 1] === quote) { i++; continue; }
|
|
80
|
+
return i;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
return sql.length - 1;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function plain(value: Value): unknown {
|
|
87
|
+
if (typeof value === 'bigint') return value >= BigInt(Number.MIN_SAFE_INTEGER) && value <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(value) : value;
|
|
88
|
+
if (value instanceof Float64) return value.value;
|
|
89
|
+
if (value instanceof Record) return `${value.table}:${String(value.key)}`;
|
|
90
|
+
return value;
|
|
91
|
+
}
|
package/src/testing.ts
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import { spawn, spawnSync, type ChildProcess } from 'node:child_process';
|
|
2
|
+
import { mkdtemp, readFile, rm } from 'node:fs/promises';
|
|
3
|
+
import { createServer } from 'node:net';
|
|
4
|
+
import os from 'node:os';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
|
|
7
|
+
export interface RomeDBTestService {
|
|
8
|
+
readonly url: string;
|
|
9
|
+
readonly token: string;
|
|
10
|
+
readonly version: string;
|
|
11
|
+
stop(): Promise<void>;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Locate a RomeDB executable: `COSSACK_TEST_ROMEDB_BIN`, then `romedb` on PATH.
|
|
16
|
+
* Returns undefined when neither exists, so live suites can skip.
|
|
17
|
+
*/
|
|
18
|
+
export function findRomeDBBinary(): string | undefined {
|
|
19
|
+
const configured = process.env.COSSACK_TEST_ROMEDB_BIN;
|
|
20
|
+
if (configured) return configured;
|
|
21
|
+
const probe = spawnSync('romedb', ['--version'], { encoding: 'utf8' });
|
|
22
|
+
return probe.status === 0 ? 'romedb' : undefined;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* True when live RomeDB suites should run: an executable exists, or
|
|
27
|
+
* `COSSACK_TEST_REQUIRE_LIVE=1` demands them (they then fail instead of skipping).
|
|
28
|
+
*/
|
|
29
|
+
export function liveRomeDBTests(): boolean {
|
|
30
|
+
return findRomeDBBinary() !== undefined || process.env.COSSACK_TEST_REQUIRE_LIVE === '1';
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Run `start` on a free port. Another process can take the port before `romedb serve` binds it,
|
|
35
|
+
* above all with test files running in parallel, so that failure tries another port.
|
|
36
|
+
*/
|
|
37
|
+
export async function onFreePort<T>(start: (port: number) => Promise<T>, attempts = 5): Promise<T> {
|
|
38
|
+
for (let attempt = 1; ; attempt++) {
|
|
39
|
+
try { return await start(await freePort()); }
|
|
40
|
+
catch (error) {
|
|
41
|
+
if (attempt >= attempts || !/Address already in use|AddrInUse/.test(String(error))) throw error;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Start `romedb serve` on a free loopback port, on `file` or a new database in a temporary directory. */
|
|
47
|
+
export function startRomeDBService(options: { binary?: string; timeoutMs?: number; file?: string } = {}): Promise<RomeDBTestService> {
|
|
48
|
+
const binary = options.binary ?? findRomeDBBinary();
|
|
49
|
+
if (!binary) throw new Error('No RomeDB executable: set COSSACK_TEST_ROMEDB_BIN or put romedb on PATH.');
|
|
50
|
+
const version = spawnSync(binary, ['--version'], { encoding: 'utf8' }).stdout.trim().replace(/^romedb\s+/, '');
|
|
51
|
+
return onFreePort(port => serveDatabase(binary, version, port, options));
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
async function serveDatabase(binary: string, version: string, port: number, options: { timeoutMs?: number; file?: string }): Promise<RomeDBTestService> {
|
|
55
|
+
const directory = await mkdtemp(path.join(os.tmpdir(), 'cossack-romedb-'));
|
|
56
|
+
const tokenFile = path.join(directory, 'token');
|
|
57
|
+
const database = options.file ? [options.file] : [path.join(directory, 'test.romedb'), '--create'];
|
|
58
|
+
const child = spawn(binary, ['serve', ...database, '--port', String(port), '--token-file', tokenFile], { stdio: ['ignore', 'pipe', 'pipe'] });
|
|
59
|
+
let output = '';
|
|
60
|
+
child.stdout?.on('data', chunk => { output += chunk; });
|
|
61
|
+
child.stderr?.on('data', chunk => { output += chunk; });
|
|
62
|
+
const url = `http://127.0.0.1:${port}/v1/database`;
|
|
63
|
+
const deadline = Date.now() + (options.timeoutMs ?? 10_000);
|
|
64
|
+
let token = '';
|
|
65
|
+
while (Date.now() < deadline) {
|
|
66
|
+
if (child.exitCode !== null) break;
|
|
67
|
+
token = (await readFile(tokenFile, 'utf8').catch(() => '')).trim();
|
|
68
|
+
if (token && await reachable(url, token)) {
|
|
69
|
+
return { url, token, version, stop: () => stop(child, directory) };
|
|
70
|
+
}
|
|
71
|
+
await new Promise(resolve => setTimeout(resolve, 50));
|
|
72
|
+
}
|
|
73
|
+
await stop(child, directory);
|
|
74
|
+
throw new Error(`RomeDB service did not start: ${output.slice(0, 2000)}`);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export interface RomeDBTestDirectory {
|
|
78
|
+
/** The organization URL, `http://127.0.0.1:PORT/v1/organizations/{org}`. */
|
|
79
|
+
readonly url: string;
|
|
80
|
+
readonly token: string;
|
|
81
|
+
readonly directory: string;
|
|
82
|
+
/** Create a database (or return the one with this name) and return its URL. */
|
|
83
|
+
createDatabase(name: string): Promise<string>;
|
|
84
|
+
stop(): Promise<void>;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** True when the executable has `romedb serve --directory` (RomeDB 0.2.12 and later). */
|
|
88
|
+
export function servesDirectories(binary = findRomeDBBinary()): boolean {
|
|
89
|
+
if (!binary) return false;
|
|
90
|
+
const help = spawnSync(binary, ['serve', '--help'], { encoding: 'utf8' });
|
|
91
|
+
return `${help.stdout}${help.stderr}`.includes('--directory');
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Start `romedb serve --directory` on a free loopback port, over `directory` or a new temporary one. It is removed on stop. */
|
|
95
|
+
export function startRomeDBDirectory(options: { binary?: string; timeoutMs?: number; directory?: string } = {}): Promise<RomeDBTestDirectory> {
|
|
96
|
+
const binary = options.binary ?? findRomeDBBinary();
|
|
97
|
+
if (!binary) throw new Error('No RomeDB executable: set COSSACK_TEST_ROMEDB_BIN or put romedb on PATH.');
|
|
98
|
+
return onFreePort(port => serveDirectory(binary, port, options));
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
async function serveDirectory(binary: string, port: number, options: { timeoutMs?: number; directory?: string }): Promise<RomeDBTestDirectory> {
|
|
102
|
+
const directory = options.directory ?? await mkdtemp(path.join(os.tmpdir(), 'cossack-romedb-dir-'));
|
|
103
|
+
const tokenFile = path.join(directory, 'romedb.token');
|
|
104
|
+
const child = spawn(binary, ['serve', '--directory', directory, '--create', '--port', String(port), '--token-file', tokenFile], { stdio: ['ignore', 'pipe', 'pipe'] });
|
|
105
|
+
let output = '';
|
|
106
|
+
child.stdout?.on('data', chunk => { output += chunk; });
|
|
107
|
+
child.stderr?.on('data', chunk => { output += chunk; });
|
|
108
|
+
const deadline = Date.now() + (options.timeoutMs ?? 10_000);
|
|
109
|
+
while (Date.now() < deadline && child.exitCode === null) {
|
|
110
|
+
const url = /Organization URL: (\S+)/.exec(output)?.[1];
|
|
111
|
+
const token = (await readFile(tokenFile, 'utf8').catch(() => '')).trim();
|
|
112
|
+
if (url && token && await reachable(`${url}/databases`, token)) {
|
|
113
|
+
return {
|
|
114
|
+
url, token, directory,
|
|
115
|
+
async createDatabase(name) {
|
|
116
|
+
const response = await fetch(`${url}/databases`, { method: 'POST', headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' }, body: JSON.stringify({ name }) });
|
|
117
|
+
const body = await response.json() as { url?: string; error?: string };
|
|
118
|
+
if (!response.ok || !body.url) throw new Error(`create database ${name}: ${response.status} ${body.error ?? ''}`);
|
|
119
|
+
return body.url;
|
|
120
|
+
},
|
|
121
|
+
stop: () => stop(child, directory),
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
await new Promise(resolve => setTimeout(resolve, 50));
|
|
125
|
+
}
|
|
126
|
+
// A caller's folder stays for the next port; it goes on stop, once the service has started.
|
|
127
|
+
await stop(child, options.directory ? undefined : directory);
|
|
128
|
+
throw new Error(`RomeDB directory service did not start: ${output.slice(0, 2000)}`);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
async function reachable(url: string, token: string): Promise<boolean> {
|
|
132
|
+
try {
|
|
133
|
+
const response = await fetch(url, { headers: { authorization: `Bearer ${token}` } });
|
|
134
|
+
await response.body?.cancel();
|
|
135
|
+
return response.ok;
|
|
136
|
+
} catch { return false; }
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
async function stop(child: ChildProcess, directory: string | undefined): Promise<void> {
|
|
140
|
+
if (child.exitCode === null) {
|
|
141
|
+
const exited = new Promise(resolve => child.once('exit', resolve));
|
|
142
|
+
child.kill('SIGTERM');
|
|
143
|
+
const timer = setTimeout(() => child.kill('SIGKILL'), 5_000);
|
|
144
|
+
await exited;
|
|
145
|
+
clearTimeout(timer);
|
|
146
|
+
}
|
|
147
|
+
if (directory) await rm(directory, { recursive: true, force: true });
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function freePort(): Promise<number> {
|
|
151
|
+
return new Promise((resolve, reject) => {
|
|
152
|
+
const server = createServer();
|
|
153
|
+
server.once('error', reject);
|
|
154
|
+
server.listen(0, '127.0.0.1', () => {
|
|
155
|
+
const address = server.address();
|
|
156
|
+
server.close(() => typeof address === 'object' && address ? resolve(address.port) : reject(new Error('no port')));
|
|
157
|
+
});
|
|
158
|
+
});
|
|
159
|
+
}
|
package/src/transport.ts
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import { Float64, Record, Vector, type Value } from '@romedb/client/values';
|
|
2
|
+
|
|
3
|
+
/** Version of the JSON transport representation. */
|
|
4
|
+
export const TRANSPORT_VERSION = 1;
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* JSON-safe form of a RomeDB value for SSR state, hydration, RPC and plugin boundaries.
|
|
8
|
+
* JSON scalars and arrays pass through; other values become `{ $fdb: 1, t, v }` objects, and
|
|
9
|
+
* plain objects that contain a `$fdb` key are wrapped so they cannot be mistaken for a tag.
|
|
10
|
+
*/
|
|
11
|
+
export type TransportValue =
|
|
12
|
+
| null | boolean | string | number
|
|
13
|
+
| TransportValue[]
|
|
14
|
+
| { [key: string]: TransportValue };
|
|
15
|
+
|
|
16
|
+
type Tag = 'int' | 'f64' | 'rec' | 'bin' | 'vec' | 'obj';
|
|
17
|
+
|
|
18
|
+
export function toTransport(value: Value): TransportValue {
|
|
19
|
+
if (value === null || typeof value === 'boolean' || typeof value === 'string') return value;
|
|
20
|
+
if (typeof value === 'number') {
|
|
21
|
+
if (!Number.isFinite(value)) throw new TypeError('non-finite number');
|
|
22
|
+
// JSON drops the sign of negative zero.
|
|
23
|
+
return Object.is(value, -0) ? tag('f64', floatBits(value)) : value;
|
|
24
|
+
}
|
|
25
|
+
if (typeof value === 'bigint') return tag('int', value.toString());
|
|
26
|
+
if (value instanceof Float64) return tag('f64', floatBits(value.value));
|
|
27
|
+
if (value instanceof Record) return tag('rec', { table: value.table, [typeof value.key === 'bigint' ? 'int' : 'key']: String(value.key) });
|
|
28
|
+
if (value instanceof Vector) return tag('vec', toBase64(value.bytes));
|
|
29
|
+
if (value instanceof Uint8Array) return tag('bin', toBase64(value));
|
|
30
|
+
if (Array.isArray(value)) return value.map(toTransport);
|
|
31
|
+
if (plainObject(value)) {
|
|
32
|
+
const entries: { [key: string]: TransportValue } = {};
|
|
33
|
+
for (const [key, entry] of Object.entries(value)) setOwn(entries, key, toTransport(entry));
|
|
34
|
+
return Object.hasOwn(value, '$fdb') ? tag('obj', entries) : entries;
|
|
35
|
+
}
|
|
36
|
+
throw new TypeError('unsupported value');
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function fromTransport(value: unknown, depth = 0): Value {
|
|
40
|
+
if (depth > 64) throw new RangeError('value nesting exceeds 64');
|
|
41
|
+
if (value === null || typeof value === 'boolean' || typeof value === 'string') return value;
|
|
42
|
+
if (typeof value === 'number') {
|
|
43
|
+
if (!Number.isFinite(value)) throw new TypeError('non-finite number');
|
|
44
|
+
return value;
|
|
45
|
+
}
|
|
46
|
+
if (Array.isArray(value)) return value.map(entry => fromTransport(entry, depth + 1));
|
|
47
|
+
if (!plainObject(value)) throw new TypeError('invalid transport value');
|
|
48
|
+
if (!Object.hasOwn(value, '$fdb')) {
|
|
49
|
+
const entries: { [key: string]: Value } = {};
|
|
50
|
+
for (const [key, entry] of Object.entries(value)) setOwn(entries, key, fromTransport(entry, depth + 1));
|
|
51
|
+
return entries;
|
|
52
|
+
}
|
|
53
|
+
if (value.$fdb !== TRANSPORT_VERSION || Object.keys(value).sort().join() !== '$fdb,t,v') throw new TypeError('unsupported transport tag');
|
|
54
|
+
const payload = value.v;
|
|
55
|
+
switch (value.t as Tag) {
|
|
56
|
+
case 'int':
|
|
57
|
+
if (typeof payload !== 'string') throw new TypeError('invalid int64');
|
|
58
|
+
return int64(payload);
|
|
59
|
+
case 'f64': {
|
|
60
|
+
if (typeof payload !== 'string' || !/^[0-9a-f]{16}$/.test(payload)) throw new TypeError('invalid float64 bits');
|
|
61
|
+
const view = new DataView(new ArrayBuffer(8));
|
|
62
|
+
for (let i = 0; i < 8; i++) view.setUint8(i, parseInt(payload.slice(i * 2, i * 2 + 2), 16));
|
|
63
|
+
return new Float64(view.getFloat64(0, false));
|
|
64
|
+
}
|
|
65
|
+
case 'rec': {
|
|
66
|
+
if (!plainObject(payload) || typeof payload.table !== 'string') throw new TypeError('invalid record');
|
|
67
|
+
if (typeof payload.key === 'string' && Object.keys(payload).length === 2) return new Record(payload.table, payload.key);
|
|
68
|
+
if (typeof payload.int === 'string' && Object.keys(payload).length === 2) return new Record(payload.table, int64(payload.int));
|
|
69
|
+
throw new TypeError('invalid record');
|
|
70
|
+
}
|
|
71
|
+
case 'bin':
|
|
72
|
+
if (typeof payload !== 'string') throw new TypeError('invalid binary');
|
|
73
|
+
return fromBase64(payload);
|
|
74
|
+
case 'vec':
|
|
75
|
+
if (typeof payload !== 'string') throw new TypeError('invalid vector');
|
|
76
|
+
return new Vector(fromBase64(payload));
|
|
77
|
+
case 'obj': {
|
|
78
|
+
if (!plainObject(payload)) throw new TypeError('invalid object');
|
|
79
|
+
const entries: { [key: string]: Value } = {};
|
|
80
|
+
for (const [key, entry] of Object.entries(payload)) setOwn(entries, key, fromTransport(entry, depth + 1));
|
|
81
|
+
return entries;
|
|
82
|
+
}
|
|
83
|
+
default: throw new TypeError('unsupported transport tag');
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const INT64_MIN = -(2n ** 63n);
|
|
88
|
+
const INT64_MAX = 2n ** 63n - 1n;
|
|
89
|
+
|
|
90
|
+
function int64(text: string): bigint {
|
|
91
|
+
if (!/^(?:0|-?[1-9][0-9]{0,18})$/.test(text)) throw new TypeError('invalid int64');
|
|
92
|
+
const value = BigInt(text);
|
|
93
|
+
if (value < INT64_MIN || value > INT64_MAX) throw new TypeError('invalid int64');
|
|
94
|
+
return value;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** An own data property, so a `__proto__` key stays a field instead of replacing the prototype. */
|
|
98
|
+
function setOwn<T>(target: { [key: string]: T }, key: string, value: T): void {
|
|
99
|
+
Object.defineProperty(target, key, { value, enumerable: true, writable: true, configurable: true });
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function tag(t: Tag, v: TransportValue): TransportValue {
|
|
103
|
+
return { $fdb: TRANSPORT_VERSION, t, v };
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function floatBits(value: number): string {
|
|
107
|
+
const view = new DataView(new ArrayBuffer(8));
|
|
108
|
+
view.setFloat64(0, value, false);
|
|
109
|
+
let hex = '';
|
|
110
|
+
for (let i = 0; i < 8; i++) hex += view.getUint8(i).toString(16).padStart(2, '0');
|
|
111
|
+
return hex;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function plainObject(value: unknown): value is { [key: string]: unknown } {
|
|
115
|
+
if (value === null || typeof value !== 'object') return false;
|
|
116
|
+
const prototype = Object.getPrototypeOf(value);
|
|
117
|
+
return prototype === Object.prototype || prototype === null;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function toBase64(bytes: Uint8Array): string {
|
|
121
|
+
let binary = '';
|
|
122
|
+
for (let i = 0; i < bytes.length; i += 0x8000) binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
|
|
123
|
+
return btoa(binary);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function fromBase64(payload: string): Uint8Array {
|
|
127
|
+
if (payload.length > 1_048_576 || !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(payload)) throw new TypeError('invalid base64 bytes');
|
|
128
|
+
const binary = atob(payload);
|
|
129
|
+
const bytes = new Uint8Array(binary.length);
|
|
130
|
+
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
|
|
131
|
+
if (toBase64(bytes) !== payload) throw new TypeError('invalid base64 bytes');
|
|
132
|
+
return bytes;
|
|
133
|
+
}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// Client-safe typed values and the JSON transport codec. No client, credentials or Node APIs.
|
|
2
|
+
export { Float64, Record as RecordId, Vector, type Value } from '@romedb/client/values';
|
|
3
|
+
export { toTransport, fromTransport, TRANSPORT_VERSION, type TransportValue } from './transport';
|