@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/database.ts
ADDED
|
@@ -0,0 +1,498 @@
|
|
|
1
|
+
import {
|
|
2
|
+
ClientError,
|
|
3
|
+
connect,
|
|
4
|
+
encodeValue,
|
|
5
|
+
validatePrepared,
|
|
6
|
+
type BatchResult,
|
|
7
|
+
type Client,
|
|
8
|
+
type DatabaseFile,
|
|
9
|
+
type DatabaseInfo,
|
|
10
|
+
type FileExportOptions,
|
|
11
|
+
type PreparedWrite,
|
|
12
|
+
type RemoteDatabase,
|
|
13
|
+
type RequestOptions,
|
|
14
|
+
type Statement as ClientStatement,
|
|
15
|
+
type Value,
|
|
16
|
+
type WarmResult,
|
|
17
|
+
type WorkLimits,
|
|
18
|
+
} from '@romedb/client';
|
|
19
|
+
import { pendingCursor, preparedRequestId, type PendingCursor, type PendingWrite, type PendingWriteStore } from './pending';
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* A file this process opened with `@romedb/node`, described here so that Workers, which never
|
|
23
|
+
* open files, need neither that package nor its native addon.
|
|
24
|
+
*/
|
|
25
|
+
export interface EmbeddedClient extends Client {
|
|
26
|
+
readonly url: string;
|
|
27
|
+
readonly sequenceKnown: boolean;
|
|
28
|
+
exportFile(options?: FileExportOptions): Promise<DatabaseFile>;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** A service or Cloud connection, or a file this process opened with `@romedb/node`. */
|
|
32
|
+
export type DatabaseClient = RemoteDatabase | EmbeddedClient;
|
|
33
|
+
|
|
34
|
+
/** One RomeQL statement. `@romedb/node` calls the text `sql`; the binding passes it on as that. */
|
|
35
|
+
export interface Statement { rql: string; params?: { [key: string]: Value } }
|
|
36
|
+
|
|
37
|
+
/** The RomeDB engine release this package targets. Older engines are refused at preflight. */
|
|
38
|
+
export const REQUIRED_ENGINE_VERSION = '0.2.21';
|
|
39
|
+
|
|
40
|
+
export interface RomeDBWorkLimits {
|
|
41
|
+
/** Default budget for each read batch. */
|
|
42
|
+
read: WorkLimits;
|
|
43
|
+
/** Default budget for each write batch. */
|
|
44
|
+
write: WorkLimits;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export interface RomeDBRetryOptions {
|
|
48
|
+
/** Attempts for one call, including the first. Default 3. */
|
|
49
|
+
attempts?: number;
|
|
50
|
+
/** Upper bound for one backpressure delay. Default 2000 ms. */
|
|
51
|
+
maxDelayMs?: number;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export interface RomeDBOptions {
|
|
55
|
+
url: string;
|
|
56
|
+
/** Service or Cloud credential. Not needed when `connect` opens the database. */
|
|
57
|
+
token?: string;
|
|
58
|
+
/**
|
|
59
|
+
* Opens the database instead of the service client built from `url` and `token`, for
|
|
60
|
+
* example `connectNode` from `@cossackframework/romedb/node` for files. Called again after a
|
|
61
|
+
* failed open.
|
|
62
|
+
*/
|
|
63
|
+
connect?: () => Promise<DatabaseClient>;
|
|
64
|
+
/** Writes are saved here before dispatch. Use a durable store in production. */
|
|
65
|
+
pending: PendingWriteStore;
|
|
66
|
+
/** Explicit default budgets. A call may lower or raise them within the service ceilings. */
|
|
67
|
+
workLimits?: Partial<RomeDBWorkLimits>;
|
|
68
|
+
/** Oldest acceptable engine release. Default {@link REQUIRED_ENGINE_VERSION}. */
|
|
69
|
+
engineVersion?: string;
|
|
70
|
+
timeoutMs?: number;
|
|
71
|
+
retry?: RomeDBRetryOptions;
|
|
72
|
+
fetch?: typeof globalThis.fetch;
|
|
73
|
+
now?: () => number;
|
|
74
|
+
/** Waits between retries; injectable for tests. */
|
|
75
|
+
sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
|
|
76
|
+
/** Reconcilers by pending write kind, used when a write left the 64-request receipt window. */
|
|
77
|
+
reconcilers?: { [kind: string]: Reconciler };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Decide whether an unconfirmed write committed, from current data.
|
|
82
|
+
* Return `committed` or `absent`; anything else keeps the write pending.
|
|
83
|
+
*/
|
|
84
|
+
export type Reconciler = (write: PendingWrite, db: RomeDB) => Promise<'committed' | 'absent' | 'unknown'>;
|
|
85
|
+
|
|
86
|
+
export interface ReadCallOptions extends RequestOptions {
|
|
87
|
+
afterSequence?: number;
|
|
88
|
+
workLimits?: WorkLimits;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export interface WriteCallOptions extends ReadCallOptions {
|
|
92
|
+
/** Allocated by the caller before dispatch; doubles as the operation ID. */
|
|
93
|
+
requestId?: string;
|
|
94
|
+
ifSequence?: number;
|
|
95
|
+
/** Reconciliation label stored with the pending write. */
|
|
96
|
+
kind?: string;
|
|
97
|
+
/**
|
|
98
|
+
* Re-run a batch the engine rolled back for a concurrent write to the same rows
|
|
99
|
+
* (`RDB_WRITE_CONFLICT`), up to this many times, as a new request. Use only when
|
|
100
|
+
* re-evaluating the statements against newer data is correct. Default 0.
|
|
101
|
+
*/
|
|
102
|
+
retryConflicts?: number;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export interface RecoveryReport {
|
|
106
|
+
confirmed: string[];
|
|
107
|
+
rolledBack: string[];
|
|
108
|
+
reconciled: string[];
|
|
109
|
+
pending: string[];
|
|
110
|
+
/** Saved writes the store could not read (torn, or wrong permissions, owner or mode): kept for an operator. */
|
|
111
|
+
unreadable: string[];
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** The engine is older than this package requires, or did not report its release. */
|
|
115
|
+
export class EngineVersionError extends Error {
|
|
116
|
+
readonly engineVersion: string | undefined;
|
|
117
|
+
readonly required: string;
|
|
118
|
+
constructor(engineVersion: string | undefined, required: string) {
|
|
119
|
+
super(engineVersion === undefined
|
|
120
|
+
? `The RomeDB engine did not report its release; RomeDB ${required} or later is required.`
|
|
121
|
+
: `RomeDB engine ${engineVersion} is older than the required ${required}.`);
|
|
122
|
+
this.name = 'EngineVersionError';
|
|
123
|
+
this.engineVersion = engineVersion;
|
|
124
|
+
this.required = required;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** Statements one request carries, locally and on Cloud. */
|
|
129
|
+
export const MAX_STATEMENTS = 32;
|
|
130
|
+
/** Request JSON an engine that reports no limits accepts; Cloud accepts `CLOUD_REQUEST_BYTES`. `maxRequestBytes()` gives a database's own. */
|
|
131
|
+
export const LOCAL_REQUEST_BYTES = 65_536;
|
|
132
|
+
export const CLOUD_REQUEST_BYTES = 1_048_576;
|
|
133
|
+
/** Result JSON one request may return in all from an engine that reports no limits. `maxResultBytes()` gives a database's own. */
|
|
134
|
+
export const RESULT_BYTES = 262_144;
|
|
135
|
+
/** Rows one statement may return. */
|
|
136
|
+
export const MAX_ROWS = 1_000;
|
|
137
|
+
|
|
138
|
+
/** A request over the database's size or statement limit. Nothing was sent. */
|
|
139
|
+
export class RequestTooLargeError extends Error {
|
|
140
|
+
readonly cause: unknown;
|
|
141
|
+
constructor(cause: unknown) {
|
|
142
|
+
super(`The database request is too large: ${(cause as Error)?.message ?? cause}`);
|
|
143
|
+
this.name = 'RequestTooLargeError';
|
|
144
|
+
this.cause = cause;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** About how many bytes these statements take in a request, as the client encodes them. */
|
|
149
|
+
export function statementBytes(statements: readonly Statement[]): number {
|
|
150
|
+
const encoded = statements.map(statement => ({ sql: statement.rql, ...(statement.params ? { params: Object.fromEntries(Object.entries(statement.params).map(([key, value]) => [key, encodeValue(value)])) } : {}) }));
|
|
151
|
+
return new TextEncoder().encode(JSON.stringify(encoded)).length;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** The client's refusal of a request over the size or statement limit, before sending it. */
|
|
155
|
+
function tooLarge(error: unknown): error is RangeError {
|
|
156
|
+
return error instanceof RangeError && /request exceeds|1\.\.32 statements/.test(error.message);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** A write was dispatched but its outcome is unknown. It stays saved for exact recovery. */
|
|
160
|
+
export class UncertainWriteError extends Error {
|
|
161
|
+
readonly requestId: string;
|
|
162
|
+
readonly request: PreparedWrite;
|
|
163
|
+
readonly cause: unknown;
|
|
164
|
+
constructor(request: PreparedWrite, cause: unknown) {
|
|
165
|
+
super('The database write was sent but not confirmed. It is saved and will be recovered with the same request.');
|
|
166
|
+
this.name = 'UncertainWriteError';
|
|
167
|
+
this.requestId = preparedRequestId(request);
|
|
168
|
+
this.request = request;
|
|
169
|
+
this.cause = cause;
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
const DEFAULT_LIMITS: RomeDBWorkLimits = {
|
|
174
|
+
read: { rowsRead: 50_000, vmSteps: 2_000_000 },
|
|
175
|
+
write: { rowsRead: 50_000, rowMutations: 1_000, vmSteps: 2_000_000 },
|
|
176
|
+
};
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* One database binding per isolate or process. Calls are request-scoped through their
|
|
180
|
+
* options: pass the request's AbortSignal and explicit budgets.
|
|
181
|
+
*/
|
|
182
|
+
export class RomeDB {
|
|
183
|
+
readonly url: string;
|
|
184
|
+
readonly pending: PendingWriteStore;
|
|
185
|
+
readonly #options: RomeDBOptions;
|
|
186
|
+
readonly #limits: RomeDBWorkLimits;
|
|
187
|
+
readonly #required: string;
|
|
188
|
+
readonly #attempts: number;
|
|
189
|
+
readonly #maxDelay: number;
|
|
190
|
+
readonly #sleep: NonNullable<RomeDBOptions['sleep']>;
|
|
191
|
+
readonly #now: () => number;
|
|
192
|
+
#client: Promise<DatabaseClient> | undefined;
|
|
193
|
+
#preflight: Promise<DatabaseInfo> | undefined;
|
|
194
|
+
|
|
195
|
+
constructor(options: RomeDBOptions) {
|
|
196
|
+
if (!options.pending) throw new TypeError('RomeDB requires a pending write store');
|
|
197
|
+
this.#options = options;
|
|
198
|
+
this.url = options.url;
|
|
199
|
+
this.pending = options.pending;
|
|
200
|
+
this.#limits = { read: { ...DEFAULT_LIMITS.read, ...options.workLimits?.read }, write: { ...DEFAULT_LIMITS.write, ...options.workLimits?.write } };
|
|
201
|
+
this.#required = options.engineVersion ?? REQUIRED_ENGINE_VERSION;
|
|
202
|
+
this.#attempts = options.retry?.attempts ?? 3;
|
|
203
|
+
if (!Number.isInteger(this.#attempts) || this.#attempts < 1 || this.#attempts > 10) throw new RangeError('retry.attempts must be 1..10');
|
|
204
|
+
this.#maxDelay = options.retry?.maxDelayMs ?? 2_000;
|
|
205
|
+
this.#sleep = options.sleep ?? sleep;
|
|
206
|
+
this.#now = options.now ?? Date.now;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* The most request JSON this database accepts, as it reports it: 8 MiB on a local service
|
|
211
|
+
* or a file since RomeDB 0.2.23, 1 MiB on Cloud. An engine that reports none takes 64 KiB.
|
|
212
|
+
*/
|
|
213
|
+
async maxRequestBytes(): Promise<number> {
|
|
214
|
+
return (await this.#connection()).limits.maxRequestBytes;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/** The most result JSON one request may return, all statements together, as the database reports it: 8 MiB since RomeDB 0.2.23, 256 KiB from an engine that reports none. */
|
|
218
|
+
async maxResultBytes(): Promise<number> {
|
|
219
|
+
return (await this.#connection()).limits.maxResultBytes;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/** Highest publication sequence this binding has confirmed. */
|
|
223
|
+
async sequence(): Promise<number> {
|
|
224
|
+
return (await this.#connection()).sequence;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** Read database details and refuse an older or missing engine release. Memoized on success. */
|
|
228
|
+
preflight(options: RequestOptions = {}): Promise<DatabaseInfo> {
|
|
229
|
+
this.#preflight ??= this.#connection().then(async client => {
|
|
230
|
+
const info = await client.info(options);
|
|
231
|
+
checkEngine(info.engineVersion, this.#required);
|
|
232
|
+
return info;
|
|
233
|
+
});
|
|
234
|
+
this.#preflight.catch(() => { this.#preflight = undefined; });
|
|
235
|
+
return this.#preflight;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/** Fresh snapshot read with bounded backpressure retries. Reads are always safe to retry. */
|
|
239
|
+
async read(statements: Statement[], options: ReadCallOptions = {}): Promise<BatchResult> {
|
|
240
|
+
const client = await this.#connection();
|
|
241
|
+
const call = { ...options, workLimits: options.workLimits ?? this.#limits.read };
|
|
242
|
+
for (let attempt = 1; ; attempt++) {
|
|
243
|
+
try {
|
|
244
|
+
return await client.read(clientStatements(statements), call);
|
|
245
|
+
} catch (error) {
|
|
246
|
+
if (tooLarge(error)) throw new RequestTooLargeError(error);
|
|
247
|
+
const delay = this.#retryDelay(error, attempt, options.signal);
|
|
248
|
+
if (delay === undefined) throw error;
|
|
249
|
+
await this.#sleep(delay, options.signal);
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/**
|
|
255
|
+
* One atomic batch. The exact request is saved before dispatch; an unknown outcome is
|
|
256
|
+
* recovered with the same request ID and body, never with a replacement write.
|
|
257
|
+
*/
|
|
258
|
+
async write(statements: Statement[], options: WriteCallOptions = {}): Promise<BatchResult> {
|
|
259
|
+
const retries = options.retryConflicts ?? 0;
|
|
260
|
+
for (let attempt = 0; ; attempt++) {
|
|
261
|
+
try {
|
|
262
|
+
return await this.#writeOnce(statements, attempt === 0 ? options : { ...options, requestId: undefined });
|
|
263
|
+
} catch (error) {
|
|
264
|
+
if (attempt >= retries || !(error instanceof ClientError) || error.outcome !== 'rolled-back' || error.code !== 'RDB_WRITE_CONFLICT') throw error;
|
|
265
|
+
await this.#sleep(Math.floor(Math.random() * 10 * (attempt + 1)), options.signal).catch(() => {});
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
async #writeOnce(statements: Statement[], options: WriteCallOptions): Promise<BatchResult> {
|
|
271
|
+
const client = await this.#connection();
|
|
272
|
+
if (options.afterSequence === undefined && !client.sequenceKnown) await this.preflight(options);
|
|
273
|
+
let request: PreparedWrite;
|
|
274
|
+
try {
|
|
275
|
+
request = client.prepareWrite(clientStatements(statements), { ...options, workLimits: options.workLimits ?? this.#limits.write });
|
|
276
|
+
} catch (error) {
|
|
277
|
+
if (tooLarge(error)) throw new RequestTooLargeError(error);
|
|
278
|
+
throw error;
|
|
279
|
+
}
|
|
280
|
+
const id = preparedRequestId(request);
|
|
281
|
+
await this.pending.put(id, { request, savedAt: this.#now(), ...(options.kind === undefined ? {} : { kind: options.kind }) });
|
|
282
|
+
let lastError: unknown;
|
|
283
|
+
for (let attempt = 1; ; attempt++) {
|
|
284
|
+
try {
|
|
285
|
+
const result = attempt === 1 ? await client.submit(request, options) : await client.recover(request, options);
|
|
286
|
+
await this.#forget(id);
|
|
287
|
+
return result;
|
|
288
|
+
} catch (error) {
|
|
289
|
+
lastError = error;
|
|
290
|
+
if (!(error instanceof ClientError)) throw new UncertainWriteError(request, error);
|
|
291
|
+
if (error.outcome === 'rolled-back' || (error.outcome === 'not-sent' && attempt === 1)) {
|
|
292
|
+
await this.#forget(id);
|
|
293
|
+
throw error;
|
|
294
|
+
}
|
|
295
|
+
if (options.signal?.aborted) break;
|
|
296
|
+
const delay = this.#retryDelay(error, attempt, options.signal, true);
|
|
297
|
+
if (delay === undefined) break;
|
|
298
|
+
await this.#sleep(delay, options.signal).catch(() => {});
|
|
299
|
+
if (options.signal?.aborted) break;
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
throw new UncertainWriteError(request, lastError);
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/**
|
|
306
|
+
* Drop a saved write whose outcome is known. A failed delete never changes that outcome: the
|
|
307
|
+
* write stays saved and a later `recoverPending` confirms or rolls it back again.
|
|
308
|
+
*/
|
|
309
|
+
async #forget(id: string): Promise<void> {
|
|
310
|
+
await this.pending.delete(id).catch(() => {});
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/** Recover one saved write by its request ID. */
|
|
314
|
+
async recover(id: string, options: RequestOptions = {}): Promise<'confirmed' | 'rolled-back' | 'reconciled' | 'pending' | 'missing'> {
|
|
315
|
+
const write = await this.pending.get(id);
|
|
316
|
+
if (!write) return 'missing';
|
|
317
|
+
const client = await this.#connection();
|
|
318
|
+
if (client.databaseId === undefined) await this.preflight(options);
|
|
319
|
+
if (write.request.url !== client.url) return 'pending';
|
|
320
|
+
// An embedded file gets a new identity each time it opens, and a restored database a new
|
|
321
|
+
// one too: no receipt can confirm a write from an earlier identity, so reconcile it.
|
|
322
|
+
if (write.request.databaseId === client.databaseId) {
|
|
323
|
+
try {
|
|
324
|
+
await client.recover(write.request, options);
|
|
325
|
+
await this.pending.delete(id);
|
|
326
|
+
return 'confirmed';
|
|
327
|
+
} catch (error) {
|
|
328
|
+
if (error instanceof ClientError && error.outcome === 'rolled-back') {
|
|
329
|
+
await this.pending.delete(id);
|
|
330
|
+
return 'rolled-back';
|
|
331
|
+
}
|
|
332
|
+
if (!this.#outsideReceiptWindow(write, client.sequence)) return 'pending';
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
const reconcile = write.kind === undefined ? undefined : this.#options.reconcilers?.[write.kind];
|
|
336
|
+
if (!reconcile) return 'pending';
|
|
337
|
+
const decision = await reconcile(write, this);
|
|
338
|
+
if (decision === 'committed' || decision === 'absent') {
|
|
339
|
+
await this.pending.delete(id);
|
|
340
|
+
return 'reconciled';
|
|
341
|
+
}
|
|
342
|
+
return 'pending';
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
/**
|
|
346
|
+
* Recover saved writes, oldest first. Run from a scheduled path. `limit` bounds the recovery
|
|
347
|
+
* attempts; writes nothing here can resolve (another URL, or an earlier database identity
|
|
348
|
+
* with no reconciler for their kind) are passed over without counting, so they cannot hold
|
|
349
|
+
* back newer writes, and stay saved for an operator. At most `limit * 20` writes are read.
|
|
350
|
+
*/
|
|
351
|
+
async recoverPending(options: RequestOptions & { limit?: number } = {}): Promise<RecoveryReport> {
|
|
352
|
+
const report: RecoveryReport = { confirmed: [], rolledBack: [], reconciled: [], pending: [], unreadable: [] };
|
|
353
|
+
const limit = Math.max(1, options.limit ?? 100);
|
|
354
|
+
let attempts = 0;
|
|
355
|
+
let scanned = 0;
|
|
356
|
+
let after: PendingCursor | undefined;
|
|
357
|
+
// Each list reports what it could not read; a write set aside on one page is gone from the next.
|
|
358
|
+
const unreadable = new Set<string>();
|
|
359
|
+
while (attempts < limit && scanned < limit * 20) {
|
|
360
|
+
const page = await this.pending.list({ limit, ...(after ? { after } : {}) });
|
|
361
|
+
for (const id of this.pending.unreadable?.() ?? []) unreadable.add(id);
|
|
362
|
+
if (!page.length) break;
|
|
363
|
+
for (const write of page) {
|
|
364
|
+
scanned++;
|
|
365
|
+
after = pendingCursor(write);
|
|
366
|
+
const id = after.id;
|
|
367
|
+
if (await this.#unresolvable(write, options)) {
|
|
368
|
+
report.pending.push(id);
|
|
369
|
+
continue;
|
|
370
|
+
}
|
|
371
|
+
if (attempts >= limit) break;
|
|
372
|
+
attempts++;
|
|
373
|
+
const status = await this.recover(id, options).catch(() => 'pending' as const);
|
|
374
|
+
if (status === 'confirmed') report.confirmed.push(id);
|
|
375
|
+
else if (status === 'rolled-back') report.rolledBack.push(id);
|
|
376
|
+
else if (status === 'reconciled') report.reconciled.push(id);
|
|
377
|
+
else if (status === 'pending') report.pending.push(id);
|
|
378
|
+
}
|
|
379
|
+
if (page.length < limit) break;
|
|
380
|
+
}
|
|
381
|
+
report.unreadable.push(...unreadable);
|
|
382
|
+
return report;
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
/** Whether `recover` could only answer `pending` for this write, without asking the database. */
|
|
386
|
+
async #unresolvable(write: PendingWrite, options: RequestOptions): Promise<boolean> {
|
|
387
|
+
const client = await this.#connection();
|
|
388
|
+
if (client.databaseId === undefined) await this.preflight(options);
|
|
389
|
+
if (write.request.url !== client.url) return true;
|
|
390
|
+
if (write.request.databaseId === client.databaseId) return false;
|
|
391
|
+
return write.kind === undefined || !this.#options.reconcilers?.[write.kind];
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
/**
|
|
395
|
+
* The database as a `.romedb` file: one snapshot, while reads and writes continue, on every
|
|
396
|
+
* form of RomeDB. It is the whole database, sessions and credentials included, unless
|
|
397
|
+
* `emptyTables` names tables to leave out: their rows reach no part of the file, and the file
|
|
398
|
+
* is then a new database. Read `body` to the end or cancel it.
|
|
399
|
+
*/
|
|
400
|
+
async exportFile(options: FileExportOptions = {}): Promise<DatabaseFile> {
|
|
401
|
+
// Older engines cannot leave tables out, and Cloud connections have not checked yet.
|
|
402
|
+
await this.preflight(options.signal ? { signal: options.signal } : {});
|
|
403
|
+
return (await this.#connection()).exportFile(options);
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
/** Cloud only: start the database runtime. Request paths never warm; call this from a scheduled path. */
|
|
407
|
+
async warm(options: RequestOptions = {}): Promise<WarmResult | undefined> {
|
|
408
|
+
const client = await this.#connection();
|
|
409
|
+
return cloud(client) ? client.warm(options) : undefined;
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
async close(): Promise<void> {
|
|
413
|
+
const client = this.#client;
|
|
414
|
+
this.#client = undefined;
|
|
415
|
+
this.#preflight = undefined;
|
|
416
|
+
if (client) await (await client.catch(() => undefined))?.close();
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
#connection(): Promise<DatabaseClient> {
|
|
420
|
+
if (!this.#client) {
|
|
421
|
+
const { url, token, timeoutMs, fetch } = this.#options;
|
|
422
|
+
// Request scopes never warm; Cloud URLs defer details until a write needs a sequence.
|
|
423
|
+
const open = this.#options.connect ?? (() => connect({
|
|
424
|
+
url, token: token ?? '', warm: false,
|
|
425
|
+
...(timeoutMs === undefined ? {} : { timeoutMs }),
|
|
426
|
+
...(fetch === undefined ? {} : { fetch }),
|
|
427
|
+
}));
|
|
428
|
+
this.#client = open().then(async client => {
|
|
429
|
+
if (cloud(client)) return client;
|
|
430
|
+
// Files and local services answer details at once; check the engine right away.
|
|
431
|
+
try {
|
|
432
|
+
const info = await client.info();
|
|
433
|
+
checkEngine(info.engineVersion, this.#required);
|
|
434
|
+
this.#preflight = Promise.resolve(info);
|
|
435
|
+
} catch (error) { await client.close(); throw error; }
|
|
436
|
+
return client;
|
|
437
|
+
});
|
|
438
|
+
this.#client.catch(() => { this.#client = undefined; this.#preflight = undefined; });
|
|
439
|
+
}
|
|
440
|
+
return this.#client;
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
#retryDelay(error: unknown, attempt: number, signal: AbortSignal | undefined, writing = false): number | undefined {
|
|
444
|
+
if (attempt >= this.#attempts || signal?.aborted || !(error instanceof ClientError)) return undefined;
|
|
445
|
+
if (error.code === 'RDB_CANCELLED' || error.code === 'RDB_AUTH' || error.code === 'RDB_FORBIDDEN' || error.code === 'RDB_CLOSED') return undefined;
|
|
446
|
+
const backpressure = error.status === 503 || error.status === 429;
|
|
447
|
+
if (!backpressure && !(writing && error.outcome === 'unknown') && !(error.outcome === 'read-failed' && (error.code === 'RDB_TRANSPORT' || error.status === undefined))) return undefined;
|
|
448
|
+
const base = error.retryAfterMs ?? 50 * 2 ** (attempt - 1);
|
|
449
|
+
return Math.min(this.#maxDelay, base) + Math.floor(Math.random() * 25);
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
#outsideReceiptWindow(write: PendingWrite, current: number): boolean {
|
|
453
|
+
const { afterSequence } = validatePrepared(write.request);
|
|
454
|
+
return current - afterSequence >= 64;
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
export function createRomeDB(options: RomeDBOptions): RomeDB {
|
|
459
|
+
return new RomeDB(options);
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
/** Compare dotted numeric releases such as `0.2.9`. */
|
|
463
|
+
export function compareVersions(a: string, b: string): number {
|
|
464
|
+
const pa = a.split('-')[0]!.split('.').map(Number);
|
|
465
|
+
const pb = b.split('-')[0]!.split('.').map(Number);
|
|
466
|
+
for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
|
|
467
|
+
const diff = (pa[i] ?? 0) - (pb[i] ?? 0);
|
|
468
|
+
if (diff !== 0) return Math.sign(diff);
|
|
469
|
+
}
|
|
470
|
+
return 0;
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
function clientStatements(statements: Statement[]): ClientStatement[] {
|
|
474
|
+
if (!Array.isArray(statements)) throw new TypeError('statements require an array');
|
|
475
|
+
return statements.map(statement => {
|
|
476
|
+
if (statement === null || typeof statement !== 'object' || typeof statement.rql !== 'string' || Object.keys(statement).some(key => key !== 'rql' && key !== 'params')) {
|
|
477
|
+
throw new TypeError('statement requires RomeQL text in `rql` and optional params');
|
|
478
|
+
}
|
|
479
|
+
return statement.params === undefined ? { sql: statement.rql } : { sql: statement.rql, params: statement.params };
|
|
480
|
+
});
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
function cloud(client: DatabaseClient): client is RemoteDatabase {
|
|
484
|
+
return 'cloud' in client && client.cloud;
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
function checkEngine(version: string | undefined, required: string): void {
|
|
488
|
+
if (typeof version !== 'string' || !/^\d+\.\d+\.\d+/.test(version) || compareVersions(version, required) < 0) throw new EngineVersionError(version, required);
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
function sleep(ms: number, signal?: AbortSignal): Promise<void> {
|
|
492
|
+
return new Promise((resolve, reject) => {
|
|
493
|
+
if (signal?.aborted) return reject(signal.reason);
|
|
494
|
+
const timer = setTimeout(() => { signal?.removeEventListener('abort', abort); resolve(); }, ms);
|
|
495
|
+
const abort = () => { clearTimeout(timer); reject(signal!.reason); };
|
|
496
|
+
signal?.addEventListener('abort', abort, { once: true });
|
|
497
|
+
});
|
|
498
|
+
}
|
package/src/dev.d.ts
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import type { Plugin } from 'vite';
|
|
2
|
+
|
|
3
|
+
/** The local single-database service a ROMEDB_URL names, or undefined for files and remote URLs. */
|
|
4
|
+
export function localService(url: string | undefined): { origin: string; port: number } | undefined;
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Start `romedb serve` for a loopback ROMEDB_URL unless a service already answers there.
|
|
8
|
+
* Data stays in `storage/romedb/app.romedb` under `root`; the token in `storage/romedb/token`.
|
|
9
|
+
* Undefined for files and remote URLs, and for a service this app did not start.
|
|
10
|
+
*/
|
|
11
|
+
export function startLocalRomeDB(options: {
|
|
12
|
+
url: string | undefined;
|
|
13
|
+
root?: string;
|
|
14
|
+
binary?: string;
|
|
15
|
+
timeoutMs?: number;
|
|
16
|
+
log?: (message: string) => void;
|
|
17
|
+
}): Promise<{ token: string; started: boolean; stop(): Promise<void> } | undefined>;
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Start `romedb serve --directory` on `port` for a CMS network's added sites, unless a service
|
|
21
|
+
* answers there. Data stays in `storage/romedb/sites` under `root`. Undefined when the executable
|
|
22
|
+
* cannot serve a directory (before RomeDB 0.2.12), or another service answers there.
|
|
23
|
+
*/
|
|
24
|
+
export function startLocalSites(options: {
|
|
25
|
+
port: number;
|
|
26
|
+
root?: string;
|
|
27
|
+
binary?: string;
|
|
28
|
+
timeoutMs?: number;
|
|
29
|
+
log?: (message: string) => void;
|
|
30
|
+
}): Promise<{ url: string; token: string; started: boolean; stop(): Promise<void> } | undefined>;
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Vite plugin: starts `romedb serve` for a loopback ROMEDB_URL and sets `process.env.ROMEDB_TOKEN`;
|
|
34
|
+
* unless ROMEDB_SITES_URL is set, also a directory service for added sites on the next free port, setting
|
|
35
|
+
* ROMEDB_SITES_URL and ROMEDB_SITES_TOKEN.
|
|
36
|
+
*/
|
|
37
|
+
export function romedbDev(options?: { url?: string; root?: string }): Plugin;
|
|
38
|
+
|
|
39
|
+
/** Cloudflare plugin `config` customizer that passes on what {@link romedbDev} read. */
|
|
40
|
+
export function romedbDevVars(): { vars?: { ROMEDB_TOKEN?: string; ROMEDB_SITES_URL?: string; ROMEDB_SITES_TOKEN?: string } };
|