@lossless.org/nosqldb 10.10.0 → 10.11.0

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.
Files changed (39) hide show
  1. package/dist_rust/rustdb_linux_amd64 +0 -0
  2. package/dist_rust/rustdb_linux_amd64.tsrust-build.json +5 -5
  3. package/dist_rust/rustdb_linux_amd64_musl +0 -0
  4. package/dist_rust/rustdb_linux_amd64_musl.tsrust-build.json +5 -5
  5. package/dist_rust/rustdb_linux_arm64 +0 -0
  6. package/dist_rust/rustdb_linux_arm64.tsrust-build.json +5 -5
  7. package/dist_rust/rustdb_linux_arm64_musl +0 -0
  8. package/dist_rust/rustdb_linux_arm64_musl.tsrust-build.json +5 -5
  9. package/dist_rust/rustdb_macos_amd64 +0 -0
  10. package/dist_rust/rustdb_macos_amd64.tsrust-build.json +5 -5
  11. package/dist_rust/rustdb_macos_arm64 +0 -0
  12. package/dist_rust/rustdb_macos_arm64.tsrust-build.json +5 -5
  13. package/dist_ts/00_commitinfo_data.js +1 -1
  14. package/dist_ts_debugserver/bundled.js +2 -6
  15. package/package.json +5 -14
  16. package/readme.md +64 -1
  17. package/third_party_licenses/inventory.json +1 -1
  18. package/.smartconfig.json +0 -115
  19. package/ts/00_commitinfo_data.ts +0 -8
  20. package/ts/index.ts +0 -85
  21. package/ts/ts_local/classes.localnosqldb.ts +0 -608
  22. package/ts/ts_local/index.ts +0 -19
  23. package/ts/ts_local/plugins.ts +0 -1
  24. package/ts/ts_nosqldb/classes.storagerehearsal.ts +0 -109
  25. package/ts/ts_nosqldb/committed-writes.ts +0 -38
  26. package/ts/ts_nosqldb/file-storage-options.ts +0 -33
  27. package/ts/ts_nosqldb/file-storage-startup.ts +0 -10
  28. package/ts/ts_nosqldb/index.ts +0 -127
  29. package/ts/ts_nosqldb/offline-inspection.ts +0 -375
  30. package/ts/ts_nosqldb/plugins.ts +0 -12
  31. package/ts/ts_nosqldb/resource-fencing.ts +0 -368
  32. package/ts/ts_nosqldb/rust-db-bridge.ts +0 -1066
  33. package/ts/ts_nosqldb/server/classes.nosqldbserver.ts +0 -738
  34. package/ts/ts_nosqldb/server/index.ts +0 -4
  35. package/ts/ts_nosqldb/service-types.ts +0 -499
  36. package/ts/ts_nosqldb/stopped-storage.ts +0 -108
  37. package/ts/ts_nosqldb/storage-rehearsal.ts +0 -215
  38. package/ts/ts_nosqldb/storage-root-alignment.ts +0 -176
  39. package/ts/ts_nosqldb/storage-root-relocation.ts +0 -279
@@ -1,738 +0,0 @@
1
- import {
2
- RustDbBridge,
3
- NoSqlDbManagementOperationTerminationError,
4
- } from '../rust-db-bridge.js';
5
- import { validateNoSqlDbManagementOperationOptions } from '../offline-inspection.js';
6
- import type { INoSqlDbGetCommittedWritesInput, INoSqlDbCommittedWritesPage } from '../committed-writes.js';
7
- import { validateNoSqlDbStorageRehearsalStartup } from '../storage-rehearsal.js';
8
- import { assertNoLocalNoSqlDbStorageRootRelocationWorkspace } from '../storage-root-relocation.js';
9
- import {
10
- type TNoSqlDbFileStorageStartup,
11
- } from '../file-storage-startup.js';
12
- import {
13
- normalizeNoSqlDbFileStorageOptions,
14
- } from '../file-storage-options.js';
15
- import type {
16
- IOpLogEntry,
17
- IOpLogResult,
18
- IOpLogStats,
19
- IRevertResult,
20
- ICollectionInfo,
21
- IDocumentsResult,
22
- INoSqlDbMetrics,
23
- INoSqlDbQueryOptions,
24
- INoSqlDbInboundOptions,
25
- } from '../rust-db-bridge.js';
26
- import type {
27
- INoSqlDbHealth,
28
- INoSqlDbDatabaseTenantInput,
29
- INoSqlDbAttestDatabaseTenantInput,
30
- INoSqlDbAttestDatabaseTenantResult,
31
- INoSqlDbEnsureDatabaseTenantInput,
32
- INoSqlDbEnsureDatabaseTenantResult,
33
- INoSqlDbAllocateDatabaseTenantInput,
34
- INoSqlDbAllocateDatabaseTenantResult,
35
- INoSqlDbDeleteDatabaseTenantInput,
36
- INoSqlDbRotateDatabaseTenantPasswordInput,
37
- INoSqlDbDatabaseTenantDescriptor,
38
- INoSqlDbDeleteDatabaseTenantResult,
39
- INoSqlDbIssueDatabaseAllocationReadAccessGrantInput,
40
- INoSqlDbIssueDatabaseAllocationReadAccessGrantResult,
41
- INoSqlDbRevokeDatabaseAllocationReadAccessGrantInput,
42
- INoSqlDbRevokeDatabaseAllocationReadAccessGrantResult,
43
- INoSqlDbDatabaseExport,
44
- INoSqlDbExportDatabaseInput,
45
- INoSqlDbExportHeldDatabaseInput,
46
- INoSqlDbDatabaseContentDigest,
47
- INoSqlDbGetDatabaseContentDigestInput,
48
- INoSqlDbImportDatabaseInput,
49
- INoSqlDbImportDatabaseResult,
50
- INoSqlDbCommitDatabasePublicationInput,
51
- INoSqlDbManagementOperationOptions,
52
- INoSqlDbDatabaseResourceFenceState,
53
- TNoSqlDbCommitDatabasePublicationResult,
54
- } from '../service-types.js';
55
-
56
- /**
57
- * Server configuration options
58
- */
59
- export interface INoSqlDbServerOptions {
60
- /** Exact engine executable. Invalid explicit paths reject without chmod or discovery fallback. Omit for normal discovery. */
61
- binaryPath?: string;
62
- /** Exact rehearsal operation ID. Requires authenticated current-format-only file storage and an explicit private Unix socket. Never promotes a rehearsal. */
63
- storageRehearsalId?: string;
64
- /** Default: current-format-only. existing-only also requires initialized storage and refuses fresh creation. */
65
- fileStorageStartup?: TNoSqlDbFileStorageStartup;
66
- /** Port to listen on (default: 27017, 0 requests an OS-assigned port) - ignored if socketPath is set */
67
- port?: number;
68
- /** Host to bind to (default: 127.0.0.1) - ignored if socketPath is set */
69
- host?: string;
70
- /** Unix socket path - if set, server listens on socket instead of TCP */
71
- socketPath?: string;
72
- /** Storage type: 'memory' or 'file' (default: 'memory') */
73
- storage?: 'memory' | 'file';
74
- /** Path for file storage (required if storage is 'file') */
75
- storagePath?: string;
76
- /** Authentication configuration. Disabled by default. */
77
- auth?: INoSqlDbAuthOptions;
78
- /** TLS transport configuration for TCP listeners. Disabled by default. */
79
- tls?: INoSqlDbTlsOptions;
80
- /** In-memory oplog: whether it is kept, and its retention limits (defaults: enabled, 10000 entries / 8 MiB). */
81
- oplog?: INoSqlDbOplogOptions;
82
- /** Memory, temporary storage, and concurrency admission for large sorts. */
83
- query?: INoSqlDbQueryOptions;
84
- /** Memory budgets for received requests (default: sized from the memory limit). */
85
- inbound?: INoSqlDbInboundOptions;
86
- }
87
-
88
- export interface INoSqlDbOplogOptions {
89
- /** Keep the oplog (default: true). When false, writes prepare no history, and getOpLog, getOpLogStats and revertToSeq reject with "oplog is disabled". */
90
- enabled?: boolean;
91
- /** Maximum number of retained oplog entries (default: 10000). */
92
- maxEntries?: number;
93
- /** Maximum approximate retained bytes, the entry table included (default: 8 MiB). Oldest entries are evicted first; reverts cannot reach past evicted entries. */
94
- maxBytes?: number;
95
- }
96
-
97
- export interface INoSqlDbAuthOptions {
98
- enabled?: boolean;
99
- users?: INoSqlDbAuthUser[];
100
- scramIterations?: number;
101
- }
102
-
103
- export interface INoSqlDbAuthUser {
104
- username: string;
105
- password: string;
106
- database?: string;
107
- roles?: string[];
108
- }
109
-
110
- export interface INoSqlDbTlsOptions {
111
- enabled?: boolean;
112
- certPath?: string;
113
- keyPath?: string;
114
- caPath?: string;
115
- requireClientCert?: boolean;
116
- }
117
-
118
- /**
119
- * NoSqlDbServer - Wire protocol compatible database server backed by Rust
120
- *
121
- * This server implements the wire protocol to allow official drivers to
122
- * connect and perform operations. The core engine runs as a Rust sidecar
123
- * binary managed via @push.rocks/smartrust IPC.
124
- *
125
- * @example
126
- * ```typescript
127
- * import { NoSqlDbServer } from '@lossless.org/nosqldb';
128
- * import { MongoClient } from 'mongodb';
129
- *
130
- * const server = new NoSqlDbServer({ port: 27017 });
131
- * await server.start();
132
- *
133
- * const client = new MongoClient(server.getConnectionUri());
134
- * await client.connect();
135
- * ```
136
- */
137
- export class NoSqlDbServer {
138
- private options: INoSqlDbServerOptions;
139
- private bridge: RustDbBridge;
140
- private bridgeOwned = false;
141
- private startInProgress = false;
142
- private startCompletionPromise: Promise<void> | null = null;
143
- private stopCompletionPromise: Promise<void> | null = null;
144
- private isRunning = false;
145
- private resolvedConnectionUri = '';
146
- private resolvedPort: number | undefined;
147
-
148
- constructor(options: INoSqlDbServerOptions = {}) {
149
- validateNoSqlDbStorageRehearsalStartup(options);
150
- const fileStorage = normalizeNoSqlDbFileStorageOptions(options);
151
- this.options = {
152
- binaryPath: options.binaryPath,
153
- storageRehearsalId: options.storageRehearsalId,
154
- ...fileStorage,
155
- port: options.port ?? 27017,
156
- host: options.host ?? '127.0.0.1',
157
- socketPath: options.socketPath,
158
- storage: options.storage ?? 'memory',
159
- storagePath: options.storagePath ?? './data',
160
- auth: options.auth,
161
- tls: options.tls,
162
- oplog: options.oplog,
163
- query: options.query,
164
- inbound: options.inbound,
165
- };
166
- this.bridge = new RustDbBridge({ binaryPath: this.options.binaryPath });
167
- this.bridge.on('exit', (code: number | null, signal: string | null) => {
168
- const exitedUnexpectedly = this.isRunning
169
- && !this.stopCompletionPromise
170
- && (code !== 0 || signal !== null);
171
- this.isRunning = false;
172
- this.resolvedConnectionUri = '';
173
- this.resolvedPort = undefined;
174
- if (exitedUnexpectedly) {
175
- console.error(`nosqldb Rust process exited unexpectedly (code=${code}, signal=${signal})`);
176
- }
177
- });
178
- }
179
-
180
- /**
181
- * Start the server
182
- */
183
- async start(optionsArg?: INoSqlDbManagementOperationOptions): Promise<void> {
184
- validateNoSqlDbManagementOperationOptions(optionsArg);
185
- optionsArg?.signal?.throwIfAborted();
186
- if (this.isRunning || this.startInProgress || this.bridgeOwned || this.stopCompletionPromise) {
187
- throw new Error('Server is already running or still owns a Rust bridge');
188
- }
189
-
190
- const startupStartedAt = Date.now();
191
- const startupDeadline = optionsArg?.timeoutMs === undefined
192
- ? undefined
193
- : startupStartedAt + optionsArg.timeoutMs;
194
- const timeoutError = new DOMException(
195
- optionsArg?.timeoutMs === undefined
196
- ? 'NoSQLDB startup timed out'
197
- : `NoSQLDB startup timed out after ${optionsArg.timeoutMs}ms`,
198
- 'TimeoutError',
199
- );
200
- const startupAbortController = new AbortController();
201
- let startupTimeout: ReturnType<typeof setTimeout> | undefined;
202
- let externalAbortHandler: (() => void) | undefined;
203
- if (optionsArg?.signal) {
204
- externalAbortHandler = () => {
205
- startupAbortController.abort(optionsArg.signal!.reason);
206
- };
207
- optionsArg.signal.addEventListener('abort', externalAbortHandler, { once: true });
208
- }
209
- if (optionsArg?.timeoutMs !== undefined) {
210
- startupTimeout = setTimeout(() => {
211
- startupAbortController.abort(timeoutError);
212
- }, optionsArg.timeoutMs);
213
- }
214
- const checkpoint = () => {
215
- if (
216
- startupDeadline !== undefined
217
- && Date.now() >= startupDeadline
218
- && !startupAbortController.signal.aborted
219
- ) {
220
- startupAbortController.abort(timeoutError);
221
- }
222
- startupAbortController.signal.throwIfAborted();
223
- };
224
- const getBridgeOperationOptions = (): INoSqlDbManagementOperationOptions | undefined => {
225
- checkpoint();
226
- const remainingTimeoutMs = startupDeadline === undefined
227
- ? undefined
228
- : startupDeadline - Date.now();
229
- if (remainingTimeoutMs !== undefined && remainingTimeoutMs <= 0) {
230
- startupAbortController.abort(timeoutError);
231
- checkpoint();
232
- }
233
- if (!optionsArg?.signal && remainingTimeoutMs === undefined) return undefined;
234
- return {
235
- ...(optionsArg?.signal ? { signal: optionsArg.signal } : {}),
236
- ...(remainingTimeoutMs === undefined ? {} : { timeoutMs: remainingTimeoutMs }),
237
- };
238
- };
239
-
240
- this.startInProgress = true;
241
- let resolveStartCompletion!: () => void;
242
- const startCompletionPromise = new Promise<void>((resolveArg) => {
243
- resolveStartCompletion = resolveArg;
244
- });
245
- this.startCompletionPromise = startCompletionPromise;
246
- try {
247
- checkpoint();
248
- // Relocation workspace admission is read-only; the native owner alone
249
- // classifies and initializes storage after acquiring its root lease.
250
- if (this.options.storage === 'file' && this.options.storagePath) {
251
- await assertNoLocalNoSqlDbStorageRootRelocationWorkspace(this.options.storagePath);
252
- checkpoint();
253
- }
254
-
255
- // Ownership starts before spawn because a rejected spawn can still have
256
- // created a child whose termination must be confirmed.
257
- this.bridgeOwned = true;
258
- const spawned = await this.bridge.spawn(getBridgeOperationOptions());
259
- checkpoint();
260
- if (!spawned) {
261
- throw new Error(
262
- 'nosqldb Rust binary not found. Set NOSQLDB_RUST_BINARY env var, ' +
263
- 'install the platform package, or build locally with `tsrust`.'
264
- );
265
- }
266
-
267
- // Send config, get back connectionUri
268
- const result = await this.bridge.startDb({
269
- port: this.options.port,
270
- host: this.options.host,
271
- socketPath: this.options.socketPath,
272
- storage: this.options.storage ?? 'memory',
273
- storagePath: this.options.storagePath,
274
- ...(this.options.fileStorageStartup === 'existing-only' ? { fileStorageStartup: 'existing-only' as const } : {}),
275
- storageRehearsalId: this.options.storageRehearsalId,
276
- auth: this.options.auth,
277
- tls: this.options.tls,
278
- oplog: this.options.oplog,
279
- query: this.options.query,
280
- inbound: this.options.inbound,
281
- }, getBridgeOperationOptions());
282
- checkpoint();
283
- if (!this.bridgeOwned || !this.bridge.running) {
284
- throw new Error('nosqldb Rust process exited during startup');
285
- }
286
-
287
- if (!this.options.socketPath) {
288
- const connectionUrl = new URL(result.connectionUri);
289
- const resolvedPort = Number(connectionUrl.port);
290
- if (
291
- connectionUrl.protocol !== 'mongodb:'
292
- || !connectionUrl.hostname
293
- || !Number.isInteger(resolvedPort)
294
- || resolvedPort < 1
295
- || resolvedPort > 65_535
296
- ) {
297
- throw new Error(`nosqldb returned an invalid TCP connection URI: ${result.connectionUri}`);
298
- }
299
- this.resolvedPort = resolvedPort;
300
- }
301
- this.resolvedConnectionUri = result.connectionUri;
302
- checkpoint();
303
- this.isRunning = true;
304
- } catch (error) {
305
- const startupError = error instanceof NoSqlDbManagementOperationTerminationError
306
- ? error
307
- : optionsArg?.signal?.aborted
308
- ? optionsArg.signal.reason
309
- : startupAbortController.signal.aborted || (
310
- startupDeadline !== undefined && Date.now() >= startupDeadline
311
- )
312
- ? timeoutError
313
- : error;
314
- this.isRunning = false;
315
- this.resolvedConnectionUri = '';
316
- this.resolvedPort = undefined;
317
- if (this.bridgeOwned) {
318
- try {
319
- await this.bridge.terminate();
320
- this.bridgeOwned = false;
321
- } catch (cleanupError) {
322
- throw new AggregateError(
323
- [startupError, cleanupError],
324
- 'NoSQLDB startup failed and Rust bridge cleanup was incomplete',
325
- { cause: startupError },
326
- );
327
- }
328
- }
329
- throw startupError;
330
- } finally {
331
- if (startupTimeout) clearTimeout(startupTimeout);
332
- if (externalAbortHandler && optionsArg?.signal) {
333
- optionsArg.signal.removeEventListener('abort', externalAbortHandler);
334
- }
335
- this.startInProgress = false;
336
- resolveStartCompletion();
337
- if (this.startCompletionPromise === startCompletionPromise) {
338
- this.startCompletionPromise = null;
339
- }
340
- }
341
- }
342
-
343
- /**
344
- * Stop the server
345
- */
346
- stop(): Promise<void> {
347
- if (this.stopCompletionPromise) {
348
- return this.stopCompletionPromise;
349
- }
350
-
351
- const stopCompletionPromise = this.stopInternal();
352
- this.stopCompletionPromise = stopCompletionPromise;
353
- const releaseStopCompletion = () => {
354
- if (this.stopCompletionPromise === stopCompletionPromise) {
355
- this.stopCompletionPromise = null;
356
- }
357
- };
358
- void stopCompletionPromise.then(releaseStopCompletion, releaseStopCompletion);
359
- return stopCompletionPromise;
360
- }
361
-
362
- private async stopInternal(): Promise<void> {
363
- const startCompletionPromise = this.startCompletionPromise;
364
- if (startCompletionPromise) {
365
- await startCompletionPromise;
366
- }
367
-
368
- if (!this.isRunning && !this.bridgeOwned) {
369
- return;
370
- }
371
-
372
- const requestGracefulStop = this.isRunning && this.bridge.running;
373
- if (requestGracefulStop) {
374
- try {
375
- await this.bridge.stopDb();
376
- } catch {
377
- // Confirmed bridge termination below still releases the owned process.
378
- }
379
- }
380
-
381
- await this.bridge.terminate();
382
- this.bridgeOwned = false;
383
- this.isRunning = false;
384
- this.resolvedConnectionUri = '';
385
- this.resolvedPort = undefined;
386
- }
387
-
388
- /**
389
- * Get the connection URI for this server
390
- */
391
- getConnectionUri(): string {
392
- if (this.resolvedConnectionUri) {
393
- return this.resolvedConnectionUri;
394
- }
395
- // Fallback: compute from options
396
- if (this.options.socketPath) {
397
- const encodedPath = encodeURIComponent(this.options.socketPath);
398
- return `mongodb://${encodedPath}`;
399
- }
400
- const baseUri = `mongodb://${this.options.host ?? '127.0.0.1'}:${this.options.port ?? 27017}`;
401
- return this.options.tls?.enabled ? `${baseUri}/?tls=true` : baseUri;
402
- }
403
-
404
- /**
405
- * Get the socket path (if using Unix socket mode)
406
- */
407
- get socketPath(): string | undefined {
408
- return this.options.socketPath;
409
- }
410
-
411
- /**
412
- * Check if the server is running
413
- */
414
- /** Process id of the spawned Rust engine, when it runs as a child process. */
415
- get processId(): number | undefined {
416
- return this.bridge.processId;
417
- }
418
-
419
- get running(): boolean {
420
- return this.isRunning;
421
- }
422
-
423
- private async runDatabaseManagementOperation<TResult>(
424
- operationArg: () => Promise<TResult>,
425
- ): Promise<TResult> {
426
- try {
427
- return await operationArg();
428
- } catch (error) {
429
- if (
430
- !this.bridge.running
431
- || error instanceof NoSqlDbManagementOperationTerminationError
432
- ) {
433
- this.isRunning = false;
434
- this.resolvedConnectionUri = '';
435
- this.resolvedPort = undefined;
436
- if (this.bridge.ownershipReleased) {
437
- this.bridgeOwned = false;
438
- }
439
- }
440
- throw error;
441
- }
442
- }
443
-
444
- /**
445
- * Get the port the server is listening on
446
- */
447
- get port(): number {
448
- return this.resolvedPort ?? this.options.port ?? 27017;
449
- }
450
-
451
- /**
452
- * Get the host the server is bound to
453
- */
454
- get host(): string {
455
- return this.options.host ?? '127.0.0.1';
456
- }
457
-
458
- /**
459
- * Create an isolated database/user pair for an application tenant.
460
- */
461
- async createDatabaseTenant(
462
- params: INoSqlDbDatabaseTenantInput,
463
- ): Promise<INoSqlDbDatabaseTenantDescriptor> {
464
- const descriptor = await this.bridge.createDatabaseTenant(params);
465
- return this.withTenantMongoUri(descriptor, params.password);
466
- }
467
-
468
- /** Authoritatively allocate an absent, fenced database tenant. */
469
- async allocateDatabaseTenant(
470
- params: INoSqlDbAllocateDatabaseTenantInput,
471
- optionsArg?: INoSqlDbManagementOperationOptions,
472
- ): Promise<INoSqlDbAllocateDatabaseTenantResult> {
473
- const descriptor = await this.runDatabaseManagementOperation(
474
- () => this.bridge.allocateDatabaseTenant(params, optionsArg),
475
- );
476
- return this.withTenantMongoUri(descriptor, params.password);
477
- }
478
-
479
- /**
480
- * Idempotently provision or rotate one exclusively owned database tenant.
481
- */
482
- async ensureDatabaseTenant(
483
- params: INoSqlDbEnsureDatabaseTenantInput,
484
- optionsArg?: INoSqlDbManagementOperationOptions,
485
- ): Promise<INoSqlDbEnsureDatabaseTenantResult> {
486
- const descriptor = await this.runDatabaseManagementOperation(
487
- () => this.bridge.ensureDatabaseTenant(params, optionsArg),
488
- );
489
- return this.withTenantMongoUri(descriptor, params.password);
490
- }
491
-
492
- /** Verify an exact tenant credential without changing provider state. */
493
- async attestDatabaseTenant(
494
- params: INoSqlDbAttestDatabaseTenantInput,
495
- optionsArg?: INoSqlDbManagementOperationOptions,
496
- ): Promise<INoSqlDbAttestDatabaseTenantResult> {
497
- return this.runDatabaseManagementOperation(
498
- () => this.bridge.attestDatabaseTenant(params, optionsArg),
499
- );
500
- }
501
-
502
- /**
503
- * Delete a tenant database and its tenant user(s).
504
- */
505
- async deleteDatabaseTenant(
506
- params: INoSqlDbDeleteDatabaseTenantInput,
507
- optionsArg?: INoSqlDbManagementOperationOptions,
508
- ): Promise<INoSqlDbDeleteDatabaseTenantResult> {
509
- return this.runDatabaseManagementOperation(
510
- () => this.bridge.deleteDatabaseTenant(params, optionsArg),
511
- );
512
- }
513
-
514
- /** Issue one fixed-expiry read grant bound to an exact active allocation. */
515
- async issueDatabaseAllocationReadAccessGrant(
516
- params: INoSqlDbIssueDatabaseAllocationReadAccessGrantInput,
517
- optionsArg?: INoSqlDbManagementOperationOptions,
518
- ): Promise<INoSqlDbIssueDatabaseAllocationReadAccessGrantResult> {
519
- const descriptor = await this.runDatabaseManagementOperation(
520
- () => this.bridge.issueDatabaseAllocationReadAccessGrant(params, optionsArg),
521
- );
522
- return this.withTenantMongoUri(descriptor, params.password);
523
- }
524
-
525
- /** Idempotently revoke one allocation read grant without returning a secret. */
526
- async revokeDatabaseAllocationReadAccessGrant(
527
- params: INoSqlDbRevokeDatabaseAllocationReadAccessGrantInput,
528
- optionsArg?: INoSqlDbManagementOperationOptions,
529
- ): Promise<INoSqlDbRevokeDatabaseAllocationReadAccessGrantResult> {
530
- return this.runDatabaseManagementOperation(
531
- () => this.bridge.revokeDatabaseAllocationReadAccessGrant(params, optionsArg),
532
- );
533
- }
534
-
535
- /**
536
- * Rotate a tenant user's password without restarting the server.
537
- */
538
- async rotateDatabaseTenantPassword(
539
- params: INoSqlDbRotateDatabaseTenantPasswordInput,
540
- ): Promise<INoSqlDbDatabaseTenantDescriptor> {
541
- const descriptor = await this.bridge.rotateDatabaseTenantPassword(params);
542
- return this.withTenantMongoUri(descriptor, params.password);
543
- }
544
-
545
- /**
546
- * List known database tenants.
547
- */
548
- async listDatabaseTenants(): Promise<INoSqlDbDatabaseTenantDescriptor[]> {
549
- return this.bridge.listDatabaseTenants();
550
- }
551
-
552
- /**
553
- * Get a tenant descriptor without exposing a password.
554
- */
555
- async getDatabaseTenantDescriptor(params: {
556
- databaseName: string;
557
- username: string;
558
- }): Promise<INoSqlDbDatabaseTenantDescriptor> {
559
- return this.bridge.getDatabaseTenantDescriptor(params);
560
- }
561
-
562
- /** Inspect the durable high-water mark without exposing mutation receipts. */
563
- async getDatabaseResourceFenceState(
564
- params: { databaseName: string },
565
- optionsArg?: INoSqlDbManagementOperationOptions,
566
- ): Promise<INoSqlDbDatabaseResourceFenceState | null> {
567
- return this.runDatabaseManagementOperation(
568
- () => this.bridge.getDatabaseResourceFenceState(params, optionsArg),
569
- );
570
- }
571
-
572
- /**
573
- * Export one database as an Extended JSON snapshot.
574
- */
575
- async exportDatabase(
576
- params: INoSqlDbExportDatabaseInput,
577
- optionsArg?: INoSqlDbManagementOperationOptions,
578
- ): Promise<INoSqlDbDatabaseExport> {
579
- return this.runDatabaseManagementOperation(
580
- () => this.bridge.exportDatabase(params, optionsArg),
581
- );
582
- }
583
-
584
- /** Read an exact held publication without opening its serving data plane. */
585
- async exportHeldDatabase(
586
- params: INoSqlDbExportHeldDatabaseInput,
587
- optionsArg?: INoSqlDbManagementOperationOptions,
588
- ): Promise<INoSqlDbDatabaseExport> {
589
- return this.runDatabaseManagementOperation(
590
- () => this.bridge.exportHeldDatabase(params, optionsArg),
591
- );
592
- }
593
-
594
- /** Compute a bounded, database-name-independent digest of logical database content. */
595
- async getDatabaseContentDigest(
596
- params: INoSqlDbGetDatabaseContentDigestInput,
597
- optionsArg?: INoSqlDbManagementOperationOptions,
598
- ): Promise<INoSqlDbDatabaseContentDigest> {
599
- return this.runDatabaseManagementOperation(
600
- () => this.bridge.getDatabaseContentDigest(params, optionsArg),
601
- );
602
- }
603
-
604
- /**
605
- * Replace one database with a previously exported snapshot.
606
- */
607
- async importDatabase(
608
- params: INoSqlDbImportDatabaseInput,
609
- optionsArg?: INoSqlDbManagementOperationOptions,
610
- ): Promise<INoSqlDbImportDatabaseResult> {
611
- return this.runDatabaseManagementOperation(
612
- () => this.bridge.importDatabase(params, optionsArg),
613
- );
614
- }
615
-
616
- /** Release an exact held database publication after downstream fsync. */
617
- async commitDatabasePublication(
618
- params: INoSqlDbCommitDatabasePublicationInput,
619
- optionsArg?: INoSqlDbManagementOperationOptions,
620
- ): Promise<TNoSqlDbCommitDatabasePublicationResult> {
621
- return this.runDatabaseManagementOperation(
622
- () => this.bridge.commitDatabasePublication(params, optionsArg),
623
- );
624
- }
625
-
626
- /**
627
- * Get readiness/health details for long-running service use.
628
- */
629
- async getHealth(
630
- optionsArg?: INoSqlDbManagementOperationOptions,
631
- ): Promise<INoSqlDbHealth> {
632
- if (!this.isRunning) {
633
- return {
634
- running: false,
635
- storage: this.options.storage,
636
- storagePath: this.options.storage === 'file' ? this.options.storagePath : undefined,
637
- resourceFencingVersion: this.options.storage === 'file' ? 1 : undefined,
638
- resourceFencingSupported: this.options.storage === 'file' ? false : undefined,
639
- resourceFencingRequiresDrain: this.options.storage === 'file' ? true : undefined,
640
- allocationFencingVersion: this.options.storage === 'file' ? 1 : undefined,
641
- allocationFencingSupported: this.options.storage === 'file' ? false : undefined,
642
- allocationFencingRequiresDrain: this.options.storage === 'file' ? true : undefined,
643
- publicationHoldVersion: 1,
644
- publicationHoldSupported: false,
645
- publicationHoldRequiresExternalDrain: false,
646
- authEnabled: Boolean(this.options.auth?.enabled),
647
- authUsers: this.options.auth?.users?.length ?? 0,
648
- usersPathConfigured: false,
649
- databaseCount: 0,
650
- collectionCount: 0,
651
- };
652
- }
653
- return this.runDatabaseManagementOperation(
654
- () => this.bridge.getHealth(optionsArg),
655
- );
656
- }
657
-
658
- // --- OpLog / Debug API ---
659
-
660
- async getCommittedWrites(params: INoSqlDbGetCommittedWritesInput): Promise<INoSqlDbCommittedWritesPage> {
661
- return this.runDatabaseManagementOperation(() => this.bridge.getCommittedWrites(params));
662
- }
663
-
664
- /**
665
- * Get oplog entries, optionally filtered.
666
- */
667
- async getOpLog(params: {
668
- sinceSeq?: number;
669
- limit?: number;
670
- db?: string;
671
- collection?: string;
672
- } = {}): Promise<IOpLogResult> {
673
- return this.bridge.getOpLog(params);
674
- }
675
-
676
- /**
677
- * Get aggregate oplog statistics.
678
- */
679
- async getOpLogStats(): Promise<IOpLogStats> {
680
- return this.bridge.getOpLogStats();
681
- }
682
-
683
- /**
684
- * Revert database state to a specific oplog sequence number.
685
- * Use dryRun=true to preview which entries would be reverted.
686
- */
687
- async revertToSeq(seq: number, dryRun = false): Promise<IRevertResult> {
688
- return this.bridge.revertToSeq(seq, dryRun);
689
- }
690
-
691
- /**
692
- * List all collections across all databases, with document counts.
693
- */
694
- async getCollections(db?: string): Promise<ICollectionInfo[]> {
695
- return this.bridge.getCollections(db);
696
- }
697
-
698
- /**
699
- * Get documents from a collection with pagination.
700
- */
701
- async getDocuments(
702
- db: string,
703
- collection: string,
704
- limit = 50,
705
- skip = 0,
706
- ): Promise<IDocumentsResult> {
707
- return this.bridge.getDocuments(db, collection, limit, skip);
708
- }
709
-
710
- /**
711
- * Get server metrics including database/collection counts and oplog info.
712
- */
713
- async getMetrics(): Promise<INoSqlDbMetrics> {
714
- return this.bridge.getMetrics();
715
- }
716
-
717
- private withTenantMongoUri<TDescriptor extends INoSqlDbDatabaseTenantDescriptor>(
718
- descriptor: TDescriptor,
719
- password: string,
720
- ): TDescriptor & { mongodbUri: string } {
721
- return {
722
- ...descriptor,
723
- mongodbUri: this.buildTenantMongoUri(descriptor.databaseName, descriptor.username, password),
724
- };
725
- }
726
-
727
- private buildTenantMongoUri(databaseName: string, username: string, password: string): string {
728
- const host = this.options.socketPath
729
- ? encodeURIComponent(this.options.socketPath)
730
- : `${this.options.host ?? '127.0.0.1'}:${this.port}`;
731
- const auth = `${encodeURIComponent(username)}:${encodeURIComponent(password)}@`;
732
- const query = new URLSearchParams({ authSource: databaseName });
733
- if (this.options.tls?.enabled) {
734
- query.set('tls', 'true');
735
- }
736
- return `mongodb://${auth}${host}/${encodeURIComponent(databaseName)}?${query.toString()}`;
737
- }
738
- }