@serve.zone/dcrouter 34.0.0 → 34.2.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.
@@ -0,0 +1,198 @@
1
+ import * as plugins from './plugins.js';
2
+ import { createDowngradeMigrationRunner, DcRouterMigrationError } from '../ts_migrations/index.js';
3
+ import type { IDowngradeMigrationRunResult } from '../ts_migrations/index.js';
4
+
5
+ /** The prefix of the one line `dcrouter migrate` ends with: the outcome as JSON. */
6
+ export const migrateResultLinePrefix = 'DCROUTER_MIGRATE_RESULT:';
7
+
8
+ export const migrateCommandUsage = `Usage:
9
+ dcrouter migrate --storage-path <absolute path> --to <version> [--db-name <name>] [--plan]
10
+
11
+ Walks the data of a stopped dcrouter back to an earlier data version, running each
12
+ step's down handler. Forward migrations happen when dcrouter starts.
13
+
14
+ --storage-path <path> The embedded database's storage root (absolute; no default)
15
+ --to <version> The data version to walk back to, a step boundary
16
+ --db-name <name> The database inside the root (default: dcrouter)
17
+ --plan Report the steps the downgrade would run, change nothing
18
+
19
+ The root must not be in use: the command refuses a root a running dcrouter owns.
20
+ The last line of the output is ${migrateResultLinePrefix}{json}.
21
+ `;
22
+
23
+ /** A command line `dcrouter migrate` refuses before it opens anything. */
24
+ export class MigrateCommandUsageError extends Error {
25
+ constructor(messageArg: string) {
26
+ super(messageArg);
27
+ this.name = 'MigrateCommandUsageError';
28
+ }
29
+ }
30
+
31
+ export interface IMigrateCommandOptions {
32
+ storagePath: string;
33
+ targetVersion: string;
34
+ dbName: string;
35
+ planOnly: boolean;
36
+ }
37
+
38
+ export type TMigrateCommandResult =
39
+ | ({ ok: true; plan: boolean; storagePath: string; dbName: string } & IDowngradeMigrationRunResult)
40
+ | { ok: false; error: { name: string; code?: string; message: string } };
41
+
42
+ /**
43
+ * The stopped-root check's bounds: the largest every input admits (smartdb readme, "Offline
44
+ * Physical Namespace Inspection"). A root over any of them is refused, never partly inspected: a
45
+ * data file over `maximumDataFileBytes` fails the whole inspection with `ERESOURCE_LIMIT`
46
+ * (nosqldb 5.7.1 `rustdb-storage/src/offline_inspection/physical_namespace_inspection.rs:760`).
47
+ */
48
+ export const offlineInspectionLimits: plugins.smartdb.ILocalSmartDbOfflinePhysicalNamespaceInspectionLimits = {
49
+ maximumEntries: 100_000,
50
+ maximumDatabases: 4_096,
51
+ maximumCollections: 10_000,
52
+ maximumIndexes: 100_000,
53
+ maximumDataFileBytes: 268_435_456,
54
+ maximumWalFileBytes: 67_108_864,
55
+ maximumIndexFileBytes: 16_777_216,
56
+ maximumTotalFileBytes: 1_099_511_627_776,
57
+ maximumRecordsPerCollection: 1_000_000,
58
+ maximumRecordBytes: 17_825_792,
59
+ maximumResultBytes: 16_777_216,
60
+ };
61
+ const offlineInspectionTimeoutMs = 10 * 60_000;
62
+
63
+ export function parseMigrateArguments(argsArg: string[]): IMigrateCommandOptions {
64
+ let storagePath: string | undefined;
65
+ let targetVersion: string | undefined;
66
+ let dbName = 'dcrouter';
67
+ let planOnly = false;
68
+ const valueOf = (indexArg: number, flagArg: string) => {
69
+ const value = argsArg[indexArg + 1];
70
+ if (value === undefined || value.startsWith('--')) {
71
+ throw new MigrateCommandUsageError(`${flagArg} needs a value.`);
72
+ }
73
+ return value;
74
+ };
75
+ for (let index = 0; index < argsArg.length; index++) {
76
+ const arg = argsArg[index];
77
+ switch (arg) {
78
+ case '--storage-path':
79
+ storagePath = valueOf(index++, arg);
80
+ break;
81
+ case '--to':
82
+ targetVersion = valueOf(index++, arg);
83
+ break;
84
+ case '--db-name':
85
+ dbName = valueOf(index++, arg);
86
+ break;
87
+ case '--plan':
88
+ planOnly = true;
89
+ break;
90
+ default:
91
+ throw new MigrateCommandUsageError(`Unknown argument "${arg}".`);
92
+ }
93
+ }
94
+ if (!storagePath) throw new MigrateCommandUsageError('--storage-path is required.');
95
+ if (!plugins.path.isAbsolute(storagePath)) {
96
+ throw new MigrateCommandUsageError(`--storage-path must be an absolute path, not "${storagePath}".`);
97
+ }
98
+ if (!targetVersion) throw new MigrateCommandUsageError('--to is required.');
99
+ return { storagePath: plugins.path.resolve(storagePath), targetVersion, dbName, planOnly };
100
+ }
101
+
102
+ /**
103
+ * Runs the downgrade offline: a stopped-root check first, then the engine, whose owner lock refuses
104
+ * a root a running dcrouter holds, then the reverse migration. Both handles are released before it
105
+ * returns, whatever happened.
106
+ */
107
+ export async function runMigrateCommandOptions(optionsArg: IMigrateCommandOptions): Promise<TMigrateCommandResult> {
108
+ // Refuses a root an engine holds (the sidecar takes the shared owner lock), a root that is not a
109
+ // current SmartDB root, and any file that does not validate, before the engine is started.
110
+ const inspection = await plugins.smartdb.LocalSmartDb.inspectOfflinePhysicalNamespaces(
111
+ { folderPath: optionsArg.storagePath, limits: offlineInspectionLimits },
112
+ { timeoutMs: offlineInspectionTimeoutMs },
113
+ );
114
+ const databaseNames = inspection.databases.map((databaseArg) => databaseArg.name);
115
+ if (!databaseNames.includes(optionsArg.dbName)) {
116
+ throw new DcRouterMigrationError(
117
+ `The storage root holds no database "${optionsArg.dbName}" (it holds ${databaseNames.length > 0
118
+ ? databaseNames.map((nameArg) => `"${nameArg}"`).join(', ')
119
+ : 'none'}). Nothing was changed.`,
120
+ );
121
+ }
122
+
123
+ const localSmartDb = new plugins.smartdb.LocalSmartDb({ folderPath: optionsArg.storagePath });
124
+ let db: plugins.smartdata.SmartdataDb | undefined;
125
+ let failure: { error: unknown } | undefined;
126
+ try {
127
+ const { connectionUri } = await localSmartDb.start();
128
+ db = new plugins.smartdata.SmartdataDb({ mongoDbUrl: connectionUri, mongoDbName: optionsArg.dbName });
129
+ await db.init();
130
+ const runner = await createDowngradeMigrationRunner(db, optionsArg.targetVersion);
131
+ const result = optionsArg.planOnly ? await runner.plan() : await runner.run();
132
+ return {
133
+ ok: true,
134
+ plan: optionsArg.planOnly,
135
+ storagePath: optionsArg.storagePath,
136
+ dbName: optionsArg.dbName,
137
+ currentVersionBefore: result.currentVersionBefore,
138
+ currentVersionAfter: result.currentVersionAfter,
139
+ targetVersion: result.targetVersion,
140
+ wasUpToDate: result.wasUpToDate,
141
+ wasFreshInstall: result.wasFreshInstall,
142
+ totalDurationMs: result.totalDurationMs,
143
+ stepsApplied: result.stepsApplied.map(({ id, fromVersion, toVersion, status }) => ({ id, fromVersion, toVersion, status })),
144
+ stepsSkipped: result.stepsSkipped.map(({ id, fromVersion, toVersion, status }) => ({ id, fromVersion, toVersion, status })),
145
+ };
146
+ } catch (error: unknown) {
147
+ failure = { error };
148
+ throw error;
149
+ } finally {
150
+ // Both handles are released whatever happened. A cleanup failure after a failed migration is
151
+ // reported beside it, and the migration's own error stays the one the command answers with.
152
+ const cleanupErrors: unknown[] = [];
153
+ for (const release of [() => db?.close(), () => localSmartDb.stop()]) {
154
+ try {
155
+ await release();
156
+ } catch (cleanupError: unknown) {
157
+ cleanupErrors.push(cleanupError);
158
+ }
159
+ }
160
+ if (cleanupErrors.length > 0 && !failure) {
161
+ throw new AggregateError(cleanupErrors, 'dcrouter migrate could not release the database');
162
+ }
163
+ for (const cleanupError of failure ? cleanupErrors : []) {
164
+ console.error(`dcrouter migrate: releasing the database also failed: ${describeMigrateError(cleanupError).message}`);
165
+ }
166
+ }
167
+ }
168
+
169
+ const describeMigrateError = (errorArg: unknown): { name: string; code?: string; message: string } => {
170
+ if (!(errorArg instanceof Error)) return { name: 'Error', message: String(errorArg) };
171
+ const code = (errorArg as Error & { code?: unknown }).code;
172
+ return {
173
+ name: errorArg.name,
174
+ ...(typeof code === 'string' ? { code } : {}),
175
+ message: errorArg.message,
176
+ };
177
+ };
178
+
179
+ /** `dcrouter migrate …`; resolves to the process exit code and prints the result line last. */
180
+ export async function runMigrateCommand(argsArg: string[]): Promise<number> {
181
+ if (argsArg.includes('--help') || argsArg.includes('-h')) {
182
+ console.log(migrateCommandUsage);
183
+ return 0;
184
+ }
185
+ let result: TMigrateCommandResult;
186
+ let exitCode: number;
187
+ try {
188
+ result = await runMigrateCommandOptions(parseMigrateArguments(argsArg));
189
+ exitCode = 0;
190
+ } catch (error: unknown) {
191
+ result = { ok: false, error: describeMigrateError(error) };
192
+ exitCode = error instanceof MigrateCommandUsageError ? 2 : 1;
193
+ console.error(`dcrouter migrate: ${result.error.message}`);
194
+ if (error instanceof MigrateCommandUsageError) console.error(migrateCommandUsage);
195
+ }
196
+ console.log(`${migrateResultLinePrefix}${JSON.stringify(result)}`);
197
+ return exitCode;
198
+ }
package/ts/plugins.ts CHANGED
@@ -115,6 +115,7 @@ export {
115
115
 
116
116
  // third party
117
117
  import * as argon2 from 'argon2';
118
+ import * as bson from 'bson';
118
119
  import * as lruCache from 'lru-cache';
119
120
  import ipaddr from 'ipaddr.js';
120
121
  import * as uuid from 'uuid';
@@ -122,6 +123,7 @@ import webpush from 'web-push';
122
123
 
123
124
  export {
124
125
  argon2,
126
+ bson,
125
127
  lruCache,
126
128
  ipaddr,
127
129
  uuid,
@@ -3,6 +3,6 @@
3
3
  */
4
4
  export const commitinfo = {
5
5
  name: '@serve.zone/dcrouter',
6
- version: '34.0.0',
6
+ version: '34.2.0',
7
7
  description: 'A multifaceted routing service handling mail and SMS delivery functions.'
8
8
  }