@cossackframework/romedb 0.0.0 → 0.9.2
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/dev.js
ADDED
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
/**
|
|
3
|
+
* Local development on Node.js: when ROMEDB_URL is a loopback address, start `romedb serve`
|
|
4
|
+
* for it and hand its token to the dev server, so no token is copied into `.env`. Beside it,
|
|
5
|
+
* `romedb serve --directory` keeps the databases of a CMS network's added sites.
|
|
6
|
+
* Plain JavaScript: Vite configs and dev scripts import it from node_modules.
|
|
7
|
+
*/
|
|
8
|
+
import { spawn, spawnSync } from 'node:child_process';
|
|
9
|
+
import fs from 'node:fs/promises';
|
|
10
|
+
import path from 'node:path';
|
|
11
|
+
|
|
12
|
+
const LOOPBACK = new Set(['127.0.0.1', 'localhost', '[::1]']);
|
|
13
|
+
/** Ports {@link startLocalSites} tries, from the one it is given. */
|
|
14
|
+
const SITE_PORTS = 10;
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* The local single-database service a ROMEDB_URL names: a loopback `http://` URL with no path
|
|
18
|
+
* or `/v1/database`. Files, remote URLs and organization URLs return undefined.
|
|
19
|
+
* @param {string | undefined} url
|
|
20
|
+
* @returns {{ origin: string, port: number } | undefined}
|
|
21
|
+
*/
|
|
22
|
+
export function localService(url) {
|
|
23
|
+
if (!url || !/^http:\/\//i.test(url)) return undefined;
|
|
24
|
+
const parsed = new URL(url);
|
|
25
|
+
if (!LOOPBACK.has(parsed.hostname)) return undefined;
|
|
26
|
+
const pathname = parsed.pathname.replace(/\/$/, '');
|
|
27
|
+
if (pathname && pathname !== '/v1/database') return undefined;
|
|
28
|
+
return { origin: parsed.origin, port: Number(parsed.port || 80) };
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Start `romedb serve` for a loopback ROMEDB_URL unless a service already answers there. Its
|
|
33
|
+
* data stays in `storage/romedb/app.romedb` under `root`, created on the first start, and the
|
|
34
|
+
* token in `storage/romedb/token`.
|
|
35
|
+
* @param {{ url: string | undefined, root?: string, binary?: string, timeoutMs?: number, log?: (message: string) => void }} options
|
|
36
|
+
* @returns {Promise<{ token: string, started: boolean, stop(): Promise<void> } | undefined>} undefined when the URL is
|
|
37
|
+
* not a local service, or when another service answers there (its token is ROMEDB_TOKEN's).
|
|
38
|
+
*/
|
|
39
|
+
export async function startLocalRomeDB(options) {
|
|
40
|
+
const service = localService(options.url);
|
|
41
|
+
if (!service) return undefined;
|
|
42
|
+
const root = options.root ?? process.cwd();
|
|
43
|
+
const storage = path.join(root, 'storage/romedb');
|
|
44
|
+
const tokenFile = path.join(storage, 'token');
|
|
45
|
+
const log = options.log ?? (message => console.log(`[romedb] ${message}`));
|
|
46
|
+
if (await answers(service.origin)) {
|
|
47
|
+
// A service this app started earlier left its token file; any other uses ROMEDB_TOKEN.
|
|
48
|
+
const token = await readToken(tokenFile);
|
|
49
|
+
log(`using the service at ${service.origin}`);
|
|
50
|
+
return token ? { token, started: false, stop: async () => {} } : undefined;
|
|
51
|
+
}
|
|
52
|
+
const binary = options.binary ?? process.env.ROMEDB_BIN ?? 'romedb';
|
|
53
|
+
if (spawnSync(binary, ['--version'], { stdio: 'ignore' }).status !== 0) {
|
|
54
|
+
throw new Error(`ROMEDB_URL is ${options.url}, but no romedb executable was found. Install the RomeDB CLI, set ROMEDB_BIN, or set ROMEDB_URL to a file path such as storage/romedb/app.romedb.`);
|
|
55
|
+
}
|
|
56
|
+
await fs.mkdir(storage, { recursive: true, mode: 0o700 });
|
|
57
|
+
const file = path.join(storage, 'app.romedb');
|
|
58
|
+
const create = await fs.access(file).then(() => false, () => true);
|
|
59
|
+
const child = spawn(binary, ['serve', file, ...(create ? ['--create'] : []), '--port', String(service.port), '--token-file', tokenFile], { cwd: root, stdio: ['ignore', 'inherit', 'inherit'] });
|
|
60
|
+
const stop = stopper(child);
|
|
61
|
+
const token = await ready(child, service.origin, () => readToken(tokenFile), options.timeoutMs, stop);
|
|
62
|
+
log(`started romedb serve for ${path.relative(root, file)} at ${service.origin}`);
|
|
63
|
+
return { token, started: true, stop };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Start `romedb serve --directory` on `port` for the databases of a CMS network's added sites,
|
|
68
|
+
* unless a service already answers there, or on a later port when something else holds that one
|
|
69
|
+
* (nothing remembers the port, so it can change between runs). Its data stays in `storage/romedb/sites` under `root`,
|
|
70
|
+
* with the token in `storage/romedb/sites/romedb.token`.
|
|
71
|
+
* @param {{ port: number, root?: string, binary?: string, timeoutMs?: number, log?: (message: string) => void }} options
|
|
72
|
+
* @returns {Promise<{ url: string, token: string, started: boolean, stop(): Promise<void> } | undefined>} the organization
|
|
73
|
+
* URL and its token; undefined when the executable cannot serve a directory (before RomeDB 0.2.12) or another service answers there.
|
|
74
|
+
*/
|
|
75
|
+
export async function startLocalSites(options) {
|
|
76
|
+
const root = options.root ?? process.cwd();
|
|
77
|
+
const directory = path.join(root, 'storage/romedb/sites');
|
|
78
|
+
const tokenFile = path.join(directory, 'romedb.token');
|
|
79
|
+
const log = options.log ?? (message => console.log(`[romedb] ${message}`));
|
|
80
|
+
// The organization ID stays in the directory's manifest across restarts.
|
|
81
|
+
const organization = async () => {
|
|
82
|
+
try {
|
|
83
|
+
const manifest = JSON.parse(await fs.readFile(path.join(directory, 'romedb-directory.json'), 'utf8'));
|
|
84
|
+
return typeof manifest?.organizationId === 'string' ? manifest.organizationId : '';
|
|
85
|
+
} catch { return ''; }
|
|
86
|
+
};
|
|
87
|
+
/** @param {string} origin */
|
|
88
|
+
const credentials = async origin => {
|
|
89
|
+
const [token, id] = [await readToken(tokenFile), await organization()];
|
|
90
|
+
return token && id ? { url: `${origin}/v1/organizations/${id}`, token } : undefined;
|
|
91
|
+
};
|
|
92
|
+
const first = `http://127.0.0.1:${options.port}`;
|
|
93
|
+
if (await answers(first)) {
|
|
94
|
+
const found = await credentials(first);
|
|
95
|
+
if (!found) log(`another service answers at ${first}; set ROMEDB_SITES_URL and ROMEDB_SITES_TOKEN for added sites`);
|
|
96
|
+
return found ? { ...found, started: false, stop: async () => {} } : undefined;
|
|
97
|
+
}
|
|
98
|
+
const binary = options.binary ?? process.env.ROMEDB_BIN ?? 'romedb';
|
|
99
|
+
const help = spawnSync(binary, ['serve', '--help'], { encoding: 'utf8' });
|
|
100
|
+
if (help.status !== 0 || !`${help.stdout}${help.stderr}`.includes('--directory')) {
|
|
101
|
+
log('this romedb cannot serve a directory of databases (RomeDB 0.2.12 can), so the network cannot add sites');
|
|
102
|
+
return undefined;
|
|
103
|
+
}
|
|
104
|
+
await fs.mkdir(path.dirname(directory), { recursive: true, mode: 0o700 });
|
|
105
|
+
for (let attempt = 0; ; attempt++) {
|
|
106
|
+
const origin = `http://127.0.0.1:${options.port + attempt}`;
|
|
107
|
+
// Its startup lines name the organization URL and token file, which this reads itself.
|
|
108
|
+
const child = spawn(binary, ['serve', '--directory', directory, '--create', '--port', String(options.port + attempt)], { cwd: root, stdio: ['ignore', 'ignore', 'pipe'] });
|
|
109
|
+
let errors = '';
|
|
110
|
+
child.stderr.on('data', data => {
|
|
111
|
+
if (String(data).includes('AddrInUse')) errors += data;
|
|
112
|
+
else process.stderr.write(data);
|
|
113
|
+
});
|
|
114
|
+
const closed = new Promise(resolve => child.once('close', resolve));
|
|
115
|
+
const stop = stopper(child);
|
|
116
|
+
try {
|
|
117
|
+
const found = await ready(child, origin, () => credentials(origin), options.timeoutMs, stop);
|
|
118
|
+
log(`started romedb serve --directory ${path.relative(root, directory)} for added sites at ${origin}`);
|
|
119
|
+
return { ...found, started: true, stop };
|
|
120
|
+
} catch (error) {
|
|
121
|
+
await closed;
|
|
122
|
+
if (!errors || attempt + 1 === SITE_PORTS) throw error;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* SIGTERM lets serve finish active requests and close its databases. Sent synchronously, so it
|
|
129
|
+
* also works from a process 'exit' handler.
|
|
130
|
+
* @param {import('node:child_process').ChildProcess} child
|
|
131
|
+
* @returns {() => Promise<void>}
|
|
132
|
+
*/
|
|
133
|
+
function stopper(child) {
|
|
134
|
+
process.once('exit', () => { if (child.exitCode === null) child.kill('SIGTERM'); });
|
|
135
|
+
return () => new Promise(resolve => {
|
|
136
|
+
if (child.exitCode !== null || child.signalCode !== null) return resolve(undefined);
|
|
137
|
+
child.once('exit', () => resolve(undefined));
|
|
138
|
+
child.kill('SIGTERM');
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* Wait until the service answers and `read` finds its credentials; stop it after the deadline.
|
|
144
|
+
* @template T
|
|
145
|
+
* @param {import('node:child_process').ChildProcess} child
|
|
146
|
+
* @param {string} origin
|
|
147
|
+
* @param {() => Promise<T | undefined | ''>} read
|
|
148
|
+
* @param {number | undefined} timeoutMs
|
|
149
|
+
* @param {() => Promise<void>} stop
|
|
150
|
+
* @returns {Promise<T>}
|
|
151
|
+
*/
|
|
152
|
+
async function ready(child, origin, read, timeoutMs, stop) {
|
|
153
|
+
const deadline = Date.now() + (timeoutMs ?? 20_000);
|
|
154
|
+
while (Date.now() < deadline && child.exitCode === null) {
|
|
155
|
+
const found = await read();
|
|
156
|
+
if (found && await answers(origin)) return found;
|
|
157
|
+
await new Promise(resolve => setTimeout(resolve, 100));
|
|
158
|
+
}
|
|
159
|
+
await stop();
|
|
160
|
+
throw new Error(`romedb serve did not answer at ${origin}.`);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* Vite plugin for `vite dev`: starts `romedb serve` for a loopback ROMEDB_URL (read from the
|
|
165
|
+
* environment, `.dev.vars` or `.env`) and stops it with the dev server. The token lands in
|
|
166
|
+
* `process.env.ROMEDB_TOKEN`. Unless ROMEDB_SITES_URL is set, it also starts
|
|
167
|
+
* `romedb serve --directory` on the next free port for a CMS network's added sites, and sets
|
|
168
|
+
* ROMEDB_SITES_URL and ROMEDB_SITES_TOKEN. Workers apps pass these on with {@link romedbDevVars}.
|
|
169
|
+
* List it before the Cloudflare plugin.
|
|
170
|
+
* @param {{ url?: string, root?: string }} [options]
|
|
171
|
+
* @returns {import('vite').Plugin}
|
|
172
|
+
*/
|
|
173
|
+
export function romedbDev(options = {}) {
|
|
174
|
+
return {
|
|
175
|
+
name: 'cossack:romedb-dev',
|
|
176
|
+
apply: 'serve',
|
|
177
|
+
async config(config) {
|
|
178
|
+
const root = path.resolve(options.root ?? config.root ?? process.cwd());
|
|
179
|
+
const url = options.url ?? process.env.ROMEDB_URL ?? await readVar(root, 'ROMEDB_URL');
|
|
180
|
+
if (!localService(url)) return;
|
|
181
|
+
// One service per process: a config reload builds the new server before it closes
|
|
182
|
+
// the old one, so the service lives until the dev process exits.
|
|
183
|
+
const key = `${root}\n${url}`;
|
|
184
|
+
if (!running.has(key)) {
|
|
185
|
+
const starting = startLocalRomeDB({ url, root });
|
|
186
|
+
running.set(key, starting);
|
|
187
|
+
starting.catch(() => running.delete(key));
|
|
188
|
+
}
|
|
189
|
+
const service = await running.get(key);
|
|
190
|
+
if (!service) return;
|
|
191
|
+
process.env.ROMEDB_TOKEN = service.token;
|
|
192
|
+
if (process.env.ROMEDB_SITES_URL || await readVar(root, 'ROMEDB_SITES_URL')) return;
|
|
193
|
+
const sitesKey = `${key}\nsites`;
|
|
194
|
+
if (!running.has(sitesKey)) {
|
|
195
|
+
const starting = startLocalSites({ port: (localService(url)?.port ?? 4321) + 1, root });
|
|
196
|
+
running.set(sitesKey, starting);
|
|
197
|
+
starting.catch(() => running.delete(sitesKey));
|
|
198
|
+
}
|
|
199
|
+
const sites = await running.get(sitesKey);
|
|
200
|
+
if (sites && 'url' in sites) {
|
|
201
|
+
process.env.ROMEDB_SITES_URL = sites.url;
|
|
202
|
+
process.env.ROMEDB_SITES_TOKEN = sites.token;
|
|
203
|
+
}
|
|
204
|
+
},
|
|
205
|
+
};
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/** @type {Map<string, ReturnType<typeof startLocalRomeDB> | ReturnType<typeof startLocalSites>>} */
|
|
209
|
+
const running = new Map();
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* Cloudflare plugin `config` customizer: what {@link romedbDev} read (the token, and the added
|
|
213
|
+
* sites' organization URL and token), as local variables.
|
|
214
|
+
* @returns {{ vars?: { ROMEDB_TOKEN?: string, ROMEDB_SITES_URL?: string, ROMEDB_SITES_TOKEN?: string } }}
|
|
215
|
+
*/
|
|
216
|
+
export function romedbDevVars() {
|
|
217
|
+
const vars = Object.fromEntries(['ROMEDB_TOKEN', 'ROMEDB_SITES_URL', 'ROMEDB_SITES_TOKEN'].flatMap(name => process.env[name] ? [[name, process.env[name]]] : []));
|
|
218
|
+
return Object.keys(vars).length ? { vars } : {};
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/** @param {string} origin */
|
|
222
|
+
async function answers(origin) {
|
|
223
|
+
try {
|
|
224
|
+
const response = await fetch(`${origin}/v1/database`, { signal: AbortSignal.timeout(1000) });
|
|
225
|
+
await response.body?.cancel();
|
|
226
|
+
return true;
|
|
227
|
+
} catch { return false; }
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/** @param {string} file */
|
|
231
|
+
async function readToken(file) {
|
|
232
|
+
return (await fs.readFile(file, 'utf8').catch(() => '')).trim();
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* @param {string} root
|
|
237
|
+
* @param {string} name
|
|
238
|
+
*/
|
|
239
|
+
async function readVar(root, name) {
|
|
240
|
+
for (const file of ['.dev.vars', '.env']) {
|
|
241
|
+
const text = await fs.readFile(path.join(root, file), 'utf8').catch(() => '');
|
|
242
|
+
const line = text.split('\n').find(entry => entry.startsWith(`${name}=`));
|
|
243
|
+
if (line !== undefined) return line.slice(name.length + 1).trim().replace(/^(['"])(.*)\1$/, '$2');
|
|
244
|
+
}
|
|
245
|
+
return undefined;
|
|
246
|
+
}
|
package/src/directory.ts
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Databases created and deleted by name, for applications with one database per tenant: a
|
|
3
|
+
* RomeDB Cloud organization, or `romedb serve --directory`, which has the same routes. Web APIs
|
|
4
|
+
* only. `fileDatabases` in `@cossackframework/romedb/node` keeps them as files instead.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
export interface DatabaseDirectory {
|
|
8
|
+
/**
|
|
9
|
+
* Create an empty database and return its ID. A name already used returns that database, so
|
|
10
|
+
* an interrupted creation can run again. Names are 1 to 48 of `a-z`, `0-9` and `-`, from a letter.
|
|
11
|
+
*/
|
|
12
|
+
create(name: string): Promise<string>;
|
|
13
|
+
/** Delete the database and all of its data. An unknown ID is already deleted. */
|
|
14
|
+
delete(id: string): Promise<void>;
|
|
15
|
+
/** The database's URL, for `createRomeDB`. */
|
|
16
|
+
url(id: string): string;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
const NAME = /^[a-z][a-z0-9-]{0,47}$/;
|
|
20
|
+
const ID = /^[A-Za-z0-9_-]{1,80}$/;
|
|
21
|
+
|
|
22
|
+
/** A RomeDB Cloud organization URL, or the organization URL `romedb serve --directory` prints, with a key that may manage and query. */
|
|
23
|
+
export function organizationDatabases(options: { url: string; token: string; fetch?: typeof globalThis.fetch }): DatabaseDirectory {
|
|
24
|
+
const base = options.url.replace(/\/+$/, '');
|
|
25
|
+
if (!/^https?:\/\/[^/]+\/v1\/organizations\/[^/]+$/.test(base)) throw new TypeError('Use an organization URL: https://…/v1/organizations/<id>.');
|
|
26
|
+
if (!options.token) throw new TypeError('An organization URL needs a key with the manage and query scopes.');
|
|
27
|
+
const send = (path: string, init: RequestInit = {}) => (options.fetch ?? globalThis.fetch)(`${base}${path}`, {
|
|
28
|
+
...init, redirect: 'manual', headers: { authorization: `Bearer ${options.token}`, ...(init.body ? { 'content-type': 'application/json' } : {}) },
|
|
29
|
+
});
|
|
30
|
+
return {
|
|
31
|
+
async create(name) {
|
|
32
|
+
if (!NAME.test(name)) throw new TypeError('Database names are 1 to 48 of a-z, 0-9 and -, starting with a letter.');
|
|
33
|
+
const response = await send('/databases', { method: 'POST', body: JSON.stringify({ name }) });
|
|
34
|
+
const body = await response.json().catch(() => ({})) as { id?: unknown; error?: unknown };
|
|
35
|
+
if (!response.ok || typeof body.id !== 'string' || !ID.test(body.id)) throw new Error(`RomeDB could not create database ${name} (${response.status}${typeof body.error === 'string' ? `: ${body.error}` : ''}).`);
|
|
36
|
+
return body.id;
|
|
37
|
+
},
|
|
38
|
+
async delete(id) {
|
|
39
|
+
if (!ID.test(id)) throw new TypeError('Invalid database ID.');
|
|
40
|
+
const response = await send(`/databases/${id}`, { method: 'DELETE' });
|
|
41
|
+
await response.body?.cancel();
|
|
42
|
+
if (!response.ok && response.status !== 404) throw new Error(`RomeDB could not delete database ${id} (${response.status}).`);
|
|
43
|
+
},
|
|
44
|
+
url: id => `${base}/databases/${id}`,
|
|
45
|
+
};
|
|
46
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
// RomeDB's client and typed values (`@romedb/client`: Web APIs only, so it also runs on
|
|
2
|
+
// Workers). `RecordId` is RomeDB's `Record`, renamed so it does not hide TypeScript's `Record`.
|
|
3
|
+
export {
|
|
4
|
+
connect,
|
|
5
|
+
normalizeUrl,
|
|
6
|
+
validatePrepared,
|
|
7
|
+
ClientError,
|
|
8
|
+
RemoteDatabase,
|
|
9
|
+
Float64,
|
|
10
|
+
Record as RecordId,
|
|
11
|
+
Vector,
|
|
12
|
+
encodeValue,
|
|
13
|
+
decodeValue,
|
|
14
|
+
type RequestOptions,
|
|
15
|
+
type ReadOptions,
|
|
16
|
+
type WriteOptions,
|
|
17
|
+
type WorkLimits,
|
|
18
|
+
type PreparedWrite,
|
|
19
|
+
type QueryResult,
|
|
20
|
+
type BatchResult,
|
|
21
|
+
type Capabilities,
|
|
22
|
+
type DatabaseFile,
|
|
23
|
+
type DatabaseInfo,
|
|
24
|
+
type FileExportOptions,
|
|
25
|
+
type ConnectOptions,
|
|
26
|
+
type WarmResult,
|
|
27
|
+
type Outcome,
|
|
28
|
+
type Value,
|
|
29
|
+
type PortableValue,
|
|
30
|
+
} from '@romedb/client';
|
|
31
|
+
|
|
32
|
+
// JSON transport for SSR state, RPC and plugin boundaries, and row helpers
|
|
33
|
+
export { toTransport, fromTransport, TRANSPORT_VERSION, type TransportValue } from './transport';
|
|
34
|
+
export { objects, first, one, scalar, affected, DuplicateColumnError, CardinalityError, type Row } from './rows';
|
|
35
|
+
|
|
36
|
+
// Request bindings, engine preflight and exact recovery
|
|
37
|
+
export {
|
|
38
|
+
RomeDB,
|
|
39
|
+
createRomeDB,
|
|
40
|
+
compareVersions,
|
|
41
|
+
REQUIRED_ENGINE_VERSION,
|
|
42
|
+
EngineVersionError,
|
|
43
|
+
UncertainWriteError,
|
|
44
|
+
RequestTooLargeError,
|
|
45
|
+
MAX_STATEMENTS,
|
|
46
|
+
LOCAL_REQUEST_BYTES,
|
|
47
|
+
CLOUD_REQUEST_BYTES,
|
|
48
|
+
RESULT_BYTES,
|
|
49
|
+
MAX_ROWS,
|
|
50
|
+
statementBytes,
|
|
51
|
+
type DatabaseClient,
|
|
52
|
+
type Statement,
|
|
53
|
+
type RomeDBOptions,
|
|
54
|
+
type RomeDBWorkLimits,
|
|
55
|
+
type RomeDBRetryOptions,
|
|
56
|
+
type ReadCallOptions,
|
|
57
|
+
type WriteCallOptions,
|
|
58
|
+
type Reconciler,
|
|
59
|
+
type RecoveryReport,
|
|
60
|
+
} from './database';
|
|
61
|
+
export {
|
|
62
|
+
MemoryPendingWriteStore,
|
|
63
|
+
PendingWriteConflictError,
|
|
64
|
+
encodePendingWrite,
|
|
65
|
+
decodePendingWrite,
|
|
66
|
+
preparedRequestId,
|
|
67
|
+
pendingCursor,
|
|
68
|
+
pagePendingWrites,
|
|
69
|
+
type PendingWrite,
|
|
70
|
+
type PendingWriteStore,
|
|
71
|
+
type PendingListOptions,
|
|
72
|
+
type PendingCursor,
|
|
73
|
+
} from './pending';
|
|
74
|
+
|
|
75
|
+
// Databases created and deleted by name: a Cloud organization or romedb serve --directory
|
|
76
|
+
export { organizationDatabases, type DatabaseDirectory } from './directory';
|
|
77
|
+
|
|
78
|
+
// D1-shaped facade for portable SQL ledgers
|
|
79
|
+
export { rqlDatabase, numberPlaceholders, type RqlDatabase, type RqlStatement, type RqlBound, type RqlDatabaseOptions } from './rql';
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import type { DatabaseDirectory } from './directory';
|
|
4
|
+
|
|
5
|
+
const ID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Databases as files in one directory, `DIR/{id}.romedb` with a lowercase UUID v4 name: the
|
|
9
|
+
* layout `romedb serve --directory DIR` serves, so the same directory can move behind it later.
|
|
10
|
+
* `url(id)` is the file path; open it with `connectNode`. One process owns the files: delete a
|
|
11
|
+
* database only after closing its client.
|
|
12
|
+
*/
|
|
13
|
+
export function fileDatabases(directory: string): DatabaseDirectory {
|
|
14
|
+
const root = path.resolve(directory);
|
|
15
|
+
const file = (id: string) => {
|
|
16
|
+
if (!ID.test(id)) throw new TypeError('Database files are named by a lowercase UUID v4.');
|
|
17
|
+
return path.join(root, `${id}.romedb`);
|
|
18
|
+
};
|
|
19
|
+
return {
|
|
20
|
+
// The name is the caller's; the file is created when `connectNode` first opens it.
|
|
21
|
+
async create() {
|
|
22
|
+
await fs.mkdir(root, { recursive: true, mode: 0o700 });
|
|
23
|
+
return crypto.randomUUID();
|
|
24
|
+
},
|
|
25
|
+
async delete(id) {
|
|
26
|
+
const database = file(id);
|
|
27
|
+
await Promise.all([database, `${database}-wal`, path.join(root, `${id}.db-log`)].map(name => fs.rm(name, { force: true })));
|
|
28
|
+
},
|
|
29
|
+
url: file,
|
|
30
|
+
};
|
|
31
|
+
}
|
package/src/node.ts
ADDED
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
import { constants } from 'node:fs';
|
|
2
|
+
import { randomUUID } from 'node:crypto';
|
|
3
|
+
import fs from 'node:fs/promises';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
6
|
+
import { ClientError, connect } from '@romedb/client';
|
|
7
|
+
import type { DatabaseClient, EmbeddedClient } from './database';
|
|
8
|
+
import { decodePendingWrite, encodePendingWrite, pagePendingWrites, PendingWriteConflictError, samePendingWrite, type PendingListOptions, type PendingWrite, type PendingWriteStore } from './pending';
|
|
9
|
+
|
|
10
|
+
/** What this entry uses of `@romedb/node`, an optional peer: a Node app on a service does not install it. */
|
|
11
|
+
interface EmbeddedOpener {
|
|
12
|
+
openEmbedded(options: { path: string; create: boolean; timeoutMs?: number; maxOpen?: number }): Promise<EmbeddedClient>;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
const MAX_FILE = 2_359_296;
|
|
16
|
+
const ID = /^[A-Za-z0-9_-]{1,80}$/;
|
|
17
|
+
const TEMPORARY = '.tmp';
|
|
18
|
+
const CORRUPT = '.corrupt';
|
|
19
|
+
/** A temporary body older than this was left by a crash between its write and its link. */
|
|
20
|
+
const STALE_TEMPORARY_MS = 60 * 60_000;
|
|
21
|
+
/**
|
|
22
|
+
* A saved name that does not decode and is younger than this may be a body still being written
|
|
23
|
+
* (the no-hard-link fallback writes in place), so `list` leaves it for a later run.
|
|
24
|
+
*/
|
|
25
|
+
const FRESH_MS = 30_000;
|
|
26
|
+
/** Windows reports no POSIX permission bits (every file is 0o666, or 0o444) and cannot flush a folder. */
|
|
27
|
+
const windows = () => process.platform === 'win32';
|
|
28
|
+
/** `link` failures meaning the filesystem has no hard links (exFAT, some FUSE and SMB mounts). */
|
|
29
|
+
const NO_HARD_LINKS = new Set(['EPERM', 'ENOTSUP', 'EOPNOTSUPP', 'ENOSYS', 'EXDEV', 'EACCES']);
|
|
30
|
+
const FILE_FLAGS = constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | (constants.O_NOFOLLOW ?? 0);
|
|
31
|
+
|
|
32
|
+
/** A saved file that does not decode, such as one cut short by a crash from an older release. */
|
|
33
|
+
export class CorruptPendingWriteError extends Error {
|
|
34
|
+
constructor(readonly id: string, cause: unknown) {
|
|
35
|
+
super(`The pending write ${id} does not decode.`, { cause });
|
|
36
|
+
this.name = 'CorruptPendingWriteError';
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* One private file per pending write, mode 0600 (on Windows, where files carry no POSIX mode,
|
|
42
|
+
* the folder's access list protects them). The body is written and flushed under a temporary
|
|
43
|
+
* name and then hard-linked into place, so a saved name never holds a partial body and an existing
|
|
44
|
+
* one is never replaced. On a filesystem without hard links the body is written straight to its
|
|
45
|
+
* exclusive name instead. `list` sets aside files that do not decode, so one bad file cannot stop
|
|
46
|
+
* recovery of the rest, and reports files it cannot read through `unreadable`.
|
|
47
|
+
*/
|
|
48
|
+
export class FilePendingWriteStore implements PendingWriteStore {
|
|
49
|
+
readonly durability = 'durable' as const;
|
|
50
|
+
readonly #directory: string;
|
|
51
|
+
#ready: Promise<void> | undefined;
|
|
52
|
+
#unreadable: string[] = [];
|
|
53
|
+
|
|
54
|
+
constructor(directory: string) {
|
|
55
|
+
this.#directory = path.resolve(directory);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
async put(id: string, write: PendingWrite): Promise<void> {
|
|
59
|
+
const file = await this.#file(id);
|
|
60
|
+
const text = encodePendingWrite(write);
|
|
61
|
+
if (Buffer.byteLength(text) > MAX_FILE) throw new RangeError('pending write exceeds byte limit');
|
|
62
|
+
const temporary = path.join(this.#directory, `.${id}.${randomUUID()}${TEMPORARY}`);
|
|
63
|
+
await writePrivate(temporary, text);
|
|
64
|
+
try {
|
|
65
|
+
await fs.link(temporary, file);
|
|
66
|
+
} catch (error) {
|
|
67
|
+
await fs.unlink(temporary).catch(() => {});
|
|
68
|
+
const code = (error as NodeJS.ErrnoException).code;
|
|
69
|
+
if (code === 'EEXIST') return this.#alreadySaved(id, write);
|
|
70
|
+
if (!code || !NO_HARD_LINKS.has(code)) throw error;
|
|
71
|
+
// No hard links here: the exclusive create still never replaces a saved write.
|
|
72
|
+
try { await writePrivate(file, text); }
|
|
73
|
+
catch (fallback) {
|
|
74
|
+
if ((fallback as NodeJS.ErrnoException).code === 'EEXIST') return this.#alreadySaved(id, write);
|
|
75
|
+
throw fallback;
|
|
76
|
+
}
|
|
77
|
+
await this.#syncDirectory();
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
await fs.unlink(temporary);
|
|
81
|
+
await this.#syncDirectory();
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
async #alreadySaved(id: string, write: PendingWrite): Promise<void> {
|
|
85
|
+
const existing = await this.get(id);
|
|
86
|
+
if (existing && samePendingWrite(existing, write)) return;
|
|
87
|
+
throw new PendingWriteConflictError(id);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
async get(id: string): Promise<PendingWrite | undefined> {
|
|
91
|
+
const file = await this.#file(id);
|
|
92
|
+
let handle: fs.FileHandle;
|
|
93
|
+
try { handle = await fs.open(file, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0)); }
|
|
94
|
+
catch (error) {
|
|
95
|
+
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined;
|
|
96
|
+
throw error;
|
|
97
|
+
}
|
|
98
|
+
try {
|
|
99
|
+
const stat = await handle.stat();
|
|
100
|
+
// A second link is the temporary body of a put between its link and unlink, or of one
|
|
101
|
+
// that crashed there: the saved name is complete either way.
|
|
102
|
+
const linked = stat.nlink === 1 || (stat.nlink === 2 && await this.#linkedTemporary(id, stat));
|
|
103
|
+
if (!stat.isFile() || !linked || (!windows() && (stat.mode & 0o077) !== 0) || (typeof process.getuid === 'function' && stat.uid !== process.getuid()) || stat.size > MAX_FILE) {
|
|
104
|
+
throw new Error('pending write requires a private bounded regular file');
|
|
105
|
+
}
|
|
106
|
+
const text = await handle.readFile('utf8');
|
|
107
|
+
try { return decodePendingWrite(text); }
|
|
108
|
+
catch (error) { throw new CorruptPendingWriteError(id, error); }
|
|
109
|
+
} finally { await handle.close(); }
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** IDs the latest `list` could not read: torn files it set aside, and files failing the ownership checks. */
|
|
113
|
+
unreadable(): readonly string[] {
|
|
114
|
+
return this.#unreadable;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
async #linkedTemporary(id: string, saved: { ino: number; dev: number }): Promise<boolean> {
|
|
118
|
+
const names = await fs.readdir(this.#directory).catch(() => [] as string[]);
|
|
119
|
+
for (const name of names) {
|
|
120
|
+
if (!name.startsWith(`.${id}.`) || !name.endsWith(TEMPORARY)) continue;
|
|
121
|
+
const stat = await fs.lstat(path.join(this.#directory, name)).catch(() => undefined);
|
|
122
|
+
if (stat && stat.ino === saved.ino && stat.dev === saved.dev) return true;
|
|
123
|
+
}
|
|
124
|
+
return false;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
async delete(id: string): Promise<void> {
|
|
128
|
+
const file = await this.#file(id);
|
|
129
|
+
await fs.unlink(file).catch(error => { if (error.code !== 'ENOENT') throw error; });
|
|
130
|
+
await this.#syncDirectory();
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
async list(options: PendingListOptions = {}): Promise<readonly PendingWrite[]> {
|
|
134
|
+
await this.#prepare();
|
|
135
|
+
const names = await fs.readdir(this.#directory);
|
|
136
|
+
const writes: PendingWrite[] = [];
|
|
137
|
+
const unreadable: string[] = [];
|
|
138
|
+
for (const name of names) {
|
|
139
|
+
if (name.endsWith(TEMPORARY)) {
|
|
140
|
+
await this.#dropStaleTemporary(name);
|
|
141
|
+
continue;
|
|
142
|
+
}
|
|
143
|
+
if (!name.endsWith('.json') || !ID.test(name.slice(0, -5))) continue;
|
|
144
|
+
try {
|
|
145
|
+
const write = await this.get(name.slice(0, -5));
|
|
146
|
+
if (write) writes.push(write);
|
|
147
|
+
} catch (error) {
|
|
148
|
+
if (error instanceof CorruptPendingWriteError) {
|
|
149
|
+
const file = path.join(this.#directory, name);
|
|
150
|
+
const stat = await fs.lstat(file).catch(() => undefined);
|
|
151
|
+
// Possibly a body still being written: neither set aside nor reported yet.
|
|
152
|
+
if (!stat || Date.now() - stat.mtimeMs < FRESH_MS) continue;
|
|
153
|
+
// Kept beside the others under a name nothing reads, for an operator to inspect.
|
|
154
|
+
await fs.rename(file, `${file}${CORRUPT}`).catch(() => {});
|
|
155
|
+
}
|
|
156
|
+
// Either way it is reported: set aside, or (failing the ownership checks) left in place.
|
|
157
|
+
unreadable.push(name.slice(0, -5));
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
this.#unreadable = unreadable;
|
|
161
|
+
return pagePendingWrites(writes, options);
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
async #dropStaleTemporary(name: string): Promise<void> {
|
|
165
|
+
const file = path.join(this.#directory, name);
|
|
166
|
+
const stat = await fs.lstat(file).catch(() => undefined);
|
|
167
|
+
if (stat && Date.now() - stat.mtimeMs > STALE_TEMPORARY_MS) await fs.unlink(file).catch(() => {});
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
async #file(id: string): Promise<string> {
|
|
171
|
+
if (!ID.test(id)) throw new TypeError('pending write id requires 1..80 letters, digits, underscores or hyphens');
|
|
172
|
+
await this.#prepare();
|
|
173
|
+
return path.join(this.#directory, `${id}.json`);
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
#prepare(): Promise<void> {
|
|
177
|
+
this.#ready ??= fs.mkdir(this.#directory, { recursive: true, mode: 0o700 }).then(() => {});
|
|
178
|
+
return this.#ready;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
async #syncDirectory(): Promise<void> {
|
|
182
|
+
if (windows()) return;
|
|
183
|
+
const directory = await fs.open(this.#directory, constants.O_RDONLY | (constants.O_DIRECTORY ?? 0));
|
|
184
|
+
try { await directory.sync(); }
|
|
185
|
+
finally { await directory.close(); }
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** Create `file` exclusively, private, and write and flush `text` to it. */
|
|
190
|
+
async function writePrivate(file: string, text: string): Promise<void> {
|
|
191
|
+
const handle = await fs.open(file, FILE_FLAGS, 0o600);
|
|
192
|
+
try {
|
|
193
|
+
await handle.writeFile(text, 'utf8');
|
|
194
|
+
await handle.sync();
|
|
195
|
+
} catch (error) {
|
|
196
|
+
await handle.close();
|
|
197
|
+
await fs.unlink(file).catch(() => {});
|
|
198
|
+
throw error;
|
|
199
|
+
}
|
|
200
|
+
await handle.close();
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
export interface NodeConnectionOptions {
|
|
204
|
+
/**
|
|
205
|
+
* A file path (or `file:` URL) opens the database in this process and creates it when it is
|
|
206
|
+
* missing. An `http(s)://` URL connects to `romedb serve` or RomeDB Cloud.
|
|
207
|
+
*/
|
|
208
|
+
url: string;
|
|
209
|
+
/** Service or Cloud credential. Files need none. */
|
|
210
|
+
token?: string;
|
|
211
|
+
timeoutMs?: number;
|
|
212
|
+
/** Most files this process keeps open at once (`openEmbedded`'s `maxOpen`, default 16). */
|
|
213
|
+
maxOpen?: number;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** True when `ROMEDB_URL` names a service rather than a file. */
|
|
217
|
+
export function isServiceUrl(url: string): boolean {
|
|
218
|
+
return /^(?:https?|romedb):\/\//i.test(url);
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/**
|
|
222
|
+
* Open the database `url` names with `@romedb/node`: a file in this process (one process owns a
|
|
223
|
+
* file), or a connection to `romedb serve` or Cloud. Pass it to `createRomeDB` as `connect`.
|
|
224
|
+
*/
|
|
225
|
+
export async function connectNode(options: NodeConnectionOptions): Promise<DatabaseClient> {
|
|
226
|
+
const { url, token, timeoutMs, maxOpen } = options;
|
|
227
|
+
const timeout = timeoutMs === undefined ? {} : { timeoutMs };
|
|
228
|
+
if (isServiceUrl(url)) {
|
|
229
|
+
if (!token) throw new TypeError(`ROMEDB_TOKEN is required for ${url}`);
|
|
230
|
+
return connect({ url, token, warm: false, ...timeout });
|
|
231
|
+
}
|
|
232
|
+
const file = path.resolve(url.startsWith('file:') ? fileURLToPath(url) : url);
|
|
233
|
+
// The addon loads only when a file is opened, so service URLs work where it can't load.
|
|
234
|
+
// Published as source, so this also has to compile where the peer is not installed.
|
|
235
|
+
// @ts-ignore
|
|
236
|
+
const { openEmbedded } = await import('@romedb/node/embedded-client') as EmbeddedOpener;
|
|
237
|
+
const open = (create: boolean) => openEmbedded({ path: file, create, ...timeout, ...(maxOpen === undefined ? {} : { maxOpen }) });
|
|
238
|
+
if (await exists(file)) return open(false);
|
|
239
|
+
await fs.mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
240
|
+
// Another process may create it first; open that file then.
|
|
241
|
+
return open(true).catch(error => {
|
|
242
|
+
if (error instanceof ClientError && error.code === 'RDB_ALREADY_EXISTS') return open(false);
|
|
243
|
+
throw error;
|
|
244
|
+
});
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
async function exists(file: string): Promise<boolean> {
|
|
248
|
+
try { await fs.access(file, constants.F_OK); return true; }
|
|
249
|
+
catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false; throw error; }
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
export { fileDatabases } from './node-directory';
|