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