/
error.ts
491 lines (424 loc) · 13.5 KB
/
error.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
import type { TopologyVersion } from './sdam/server_description';
import type { Document } from './bson';
import type { TopologyDescription } from './sdam/topology_description';
/** @public */
export type AnyError = MongoError | Error;
/** @internal */
const kErrorLabels = Symbol('errorLabels');
/** @internal MongoDB Error Codes */
export const MONGODB_ERROR_CODES = Object.freeze({
HostUnreachable: 6,
HostNotFound: 7,
NetworkTimeout: 89,
ShutdownInProgress: 91,
PrimarySteppedDown: 189,
ExceededTimeLimit: 262,
SocketException: 9001,
NotMaster: 10107,
InterruptedAtShutdown: 11600,
InterruptedDueToReplStateChange: 11602,
NotMasterNoSlaveOk: 13435,
NotMasterOrSecondary: 13436,
StaleShardVersion: 63,
StaleEpoch: 150,
StaleConfig: 13388,
RetryChangeStream: 234,
FailedToSatisfyReadPreference: 133,
CursorNotFound: 43,
LegacyNotPrimary: 10058,
WriteConcernFailed: 64,
NamespaceNotFound: 26,
IllegalOperation: 20,
MaxTimeMSExpired: 50,
UnknownReplWriteConcern: 79,
UnsatisfiableWriteConcern: 100
} as const);
// From spec@https://github.com/mongodb/specifications/blob/f93d78191f3db2898a59013a7ed5650352ef6da8/source/change-streams/change-streams.rst#resumable-error
export const GET_MORE_RESUMABLE_CODES = new Set<number>([
MONGODB_ERROR_CODES.HostUnreachable,
MONGODB_ERROR_CODES.HostNotFound,
MONGODB_ERROR_CODES.NetworkTimeout,
MONGODB_ERROR_CODES.ShutdownInProgress,
MONGODB_ERROR_CODES.PrimarySteppedDown,
MONGODB_ERROR_CODES.ExceededTimeLimit,
MONGODB_ERROR_CODES.SocketException,
MONGODB_ERROR_CODES.NotMaster,
MONGODB_ERROR_CODES.InterruptedAtShutdown,
MONGODB_ERROR_CODES.InterruptedDueToReplStateChange,
MONGODB_ERROR_CODES.NotMasterNoSlaveOk,
MONGODB_ERROR_CODES.NotMasterOrSecondary,
MONGODB_ERROR_CODES.StaleShardVersion,
MONGODB_ERROR_CODES.StaleEpoch,
MONGODB_ERROR_CODES.StaleConfig,
MONGODB_ERROR_CODES.RetryChangeStream,
MONGODB_ERROR_CODES.FailedToSatisfyReadPreference,
MONGODB_ERROR_CODES.CursorNotFound
]);
/** @public */
export interface ErrorDescription {
message?: string;
errmsg?: string;
$err?: string;
errorLabels?: string[];
[key: string]: any;
}
/**
* @public
* @category Error
*
* @privateRemarks
* CSFLE has a dependency on this error, it uses the constructor with a string argument
*/
export class MongoError extends Error {
/** @internal */
[kErrorLabels]: Set<string>;
code?: number | string;
topologyVersion?: TopologyVersion;
constructor(message: string | Error) {
if (message instanceof Error) {
super(message.message);
this.stack = message.stack;
} else {
super(message);
}
}
get name(): string {
return 'MongoError';
}
/** Legacy name for server error responses */
get errmsg(): string {
return this.message;
}
/**
* Checks the error to see if it has an error label
*
* @param label - The error label to check for
* @returns returns true if the error has the provided error label
*/
hasErrorLabel(label: string): boolean {
if (this[kErrorLabels] == null) {
return false;
}
return this[kErrorLabels].has(label);
}
addErrorLabel(label: string): void {
if (this[kErrorLabels] == null) {
this[kErrorLabels] = new Set();
}
this[kErrorLabels].add(label);
}
get errorLabels(): string[] {
return this[kErrorLabels] ? Array.from(this[kErrorLabels]) : [];
}
}
/**
* An error coming from the mongo server
*
* @public
* @category Error
*/
export class MongoServerError extends MongoError {
code?: number;
codeName?: string;
writeConcernError?: Document;
constructor(message: Error | ErrorDescription) {
if (message instanceof Error) {
super(message);
} else {
super(message.message || message.errmsg || message.$err || 'n/a');
if (message.errorLabels) {
this[kErrorLabels] = new Set(message.errorLabels);
}
for (const name in message) {
if (name === 'errorLabels' || name === 'errmsg' || name === 'message') {
continue;
}
(this as any)[name] = message[name];
}
}
}
get name(): string {
return 'MongoServerError';
}
}
/**
* An error generated by the driver
*
* @public
* @category Error
*/
export class MongoDriverError extends MongoError {
code?: string;
constructor(message: string) {
super(message);
}
get name(): string {
return 'MongoDriverError';
}
}
/**
* An error generated when the driver encounters unexpected input
* or reaches an unexpected/invalid internal state
*
* @privateRemarks
* Should **never** be directly instantiated.
*
* @public
* @category Error
*/
export class MongoRuntimeError extends MongoDriverError {
protected constructor(message: string) {
super(message);
}
get name(): string {
return 'MongoRuntimeError';
}
}
/** @internal */
const kBeforeHandshake = Symbol('beforeHandshake');
export function isNetworkErrorBeforeHandshake(err: MongoNetworkError): boolean {
return err[kBeforeHandshake] === true;
}
/**
* An error indicating an issue with the network, including TCP errors and timeouts.
* @public
* @category Error
*/
export class MongoNetworkError extends MongoError {
/** @internal */
[kBeforeHandshake]?: boolean;
constructor(message: string | Error, options?: { beforeHandshake?: boolean }) {
super(message);
if (options && typeof options.beforeHandshake === 'boolean') {
this[kBeforeHandshake] = options.beforeHandshake;
}
}
get name(): string {
return 'MongoNetworkError';
}
}
/** @public */
export interface MongoNetworkTimeoutErrorOptions {
/** Indicates the timeout happened before a connection handshake completed */
beforeHandshake: boolean;
}
/**
* An error indicating a network timeout occurred
* @public
* @category Error
*
* @privateRemarks
* CSFLE has a dependency on this error with an instanceof check
*/
export class MongoNetworkTimeoutError extends MongoNetworkError {
constructor(message: string, options?: MongoNetworkTimeoutErrorOptions) {
super(message, options);
}
get name(): string {
return 'MongoNetworkTimeoutError';
}
}
/**
* An error used when attempting to parse a value (like a connection string)
* @public
* @category Error
*/
export class MongoParseError extends MongoDriverError {
constructor(message: string) {
super(message);
}
get name(): string {
return 'MongoParseError';
}
}
/**
* An error signifying a general system issue
* @public
* @category Error
*/
export class MongoSystemError extends MongoError {
/** An optional reason context, such as an error saved during flow of monitoring and selecting servers */
reason?: TopologyDescription;
constructor(message: string, reason: TopologyDescription) {
if (reason && reason.error) {
super(reason.error.message || reason.error);
} else {
super(message);
}
if (reason) {
this.reason = reason;
}
}
get name(): string {
return 'MongoSystemError';
}
}
/**
* An error signifying a client-side server selection error
* @public
* @category Error
*/
export class MongoServerSelectionError extends MongoSystemError {
constructor(message: string, reason: TopologyDescription) {
super(message, reason);
}
get name(): string {
return 'MongoServerSelectionError';
}
}
function makeWriteConcernResultObject(input: any) {
const output = Object.assign({}, input);
if (output.ok === 0) {
output.ok = 1;
delete output.errmsg;
delete output.code;
delete output.codeName;
}
return output;
}
/**
* An error thrown when the server reports a writeConcernError
* @public
* @category Error
*/
export class MongoWriteConcernError extends MongoServerError {
/** The result document (provided if ok: 1) */
result?: Document;
constructor(message: ErrorDescription, result: Document) {
if (result && Array.isArray(result.errorLabels)) {
message.errorLabels = result.errorLabels;
}
super(message);
if (result != null) {
this.result = makeWriteConcernResultObject(result);
}
}
get name(): string {
return 'MongoWriteConcernError';
}
}
// see: https://github.com/mongodb/specifications/blob/master/source/retryable-writes/retryable-writes.rst#terms
const RETRYABLE_ERROR_CODES = new Set<number>([
MONGODB_ERROR_CODES.HostUnreachable,
MONGODB_ERROR_CODES.HostNotFound,
MONGODB_ERROR_CODES.NetworkTimeout,
MONGODB_ERROR_CODES.ShutdownInProgress,
MONGODB_ERROR_CODES.PrimarySteppedDown,
MONGODB_ERROR_CODES.SocketException,
MONGODB_ERROR_CODES.NotMaster,
MONGODB_ERROR_CODES.InterruptedAtShutdown,
MONGODB_ERROR_CODES.InterruptedDueToReplStateChange,
MONGODB_ERROR_CODES.NotMasterNoSlaveOk,
MONGODB_ERROR_CODES.NotMasterOrSecondary
]);
const RETRYABLE_WRITE_ERROR_CODES = new Set<number>([
MONGODB_ERROR_CODES.InterruptedAtShutdown,
MONGODB_ERROR_CODES.InterruptedDueToReplStateChange,
MONGODB_ERROR_CODES.NotMaster,
MONGODB_ERROR_CODES.NotMasterNoSlaveOk,
MONGODB_ERROR_CODES.NotMasterOrSecondary,
MONGODB_ERROR_CODES.PrimarySteppedDown,
MONGODB_ERROR_CODES.ShutdownInProgress,
MONGODB_ERROR_CODES.HostNotFound,
MONGODB_ERROR_CODES.HostUnreachable,
MONGODB_ERROR_CODES.NetworkTimeout,
MONGODB_ERROR_CODES.SocketException,
MONGODB_ERROR_CODES.ExceededTimeLimit
]);
export function isRetryableWriteError(error: MongoError): boolean {
if (error instanceof MongoWriteConcernError) {
return RETRYABLE_WRITE_ERROR_CODES.has(error.result?.code ?? error.code ?? 0);
}
return typeof error.code === 'number' && RETRYABLE_WRITE_ERROR_CODES.has(error.code);
}
/** Determines whether an error is something the driver should attempt to retry */
export function isRetryableError(error: MongoError): boolean {
return (
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
(typeof error.code === 'number' && RETRYABLE_ERROR_CODES.has(error.code!)) ||
error instanceof MongoNetworkError ||
!!error.message.match(/not master/) ||
!!error.message.match(/node is recovering/)
);
}
const SDAM_RECOVERING_CODES = new Set<number>([
MONGODB_ERROR_CODES.ShutdownInProgress,
MONGODB_ERROR_CODES.PrimarySteppedDown,
MONGODB_ERROR_CODES.InterruptedAtShutdown,
MONGODB_ERROR_CODES.InterruptedDueToReplStateChange,
MONGODB_ERROR_CODES.NotMasterOrSecondary
]);
const SDAM_NOTMASTER_CODES = new Set<number>([
MONGODB_ERROR_CODES.NotMaster,
MONGODB_ERROR_CODES.NotMasterNoSlaveOk,
MONGODB_ERROR_CODES.LegacyNotPrimary
]);
const SDAM_NODE_SHUTTING_DOWN_ERROR_CODES = new Set<number>([
MONGODB_ERROR_CODES.InterruptedAtShutdown,
MONGODB_ERROR_CODES.ShutdownInProgress
]);
function isRecoveringError(err: MongoError) {
if (typeof err.code === 'number') {
// If any error code exists, we ignore the error.message
return SDAM_RECOVERING_CODES.has(err.code);
}
return /not master or secondary/.test(err.message) || /node is recovering/.test(err.message);
}
function isNotMasterError(err: MongoError) {
if (typeof err.code === 'number') {
// If any error code exists, we ignore the error.message
return SDAM_NOTMASTER_CODES.has(err.code);
}
if (isRecoveringError(err)) {
return false;
}
return /not master/.test(err.message);
}
export function isNodeShuttingDownError(err: MongoError): boolean {
return !!(typeof err.code === 'number' && SDAM_NODE_SHUTTING_DOWN_ERROR_CODES.has(err.code));
}
/**
* Determines whether SDAM can recover from a given error. If it cannot
* then the pool will be cleared, and server state will completely reset
* locally.
*
* @see https://github.com/mongodb/specifications/blob/master/source/server-discovery-and-monitoring/server-discovery-and-monitoring.rst#not-master-and-node-is-recovering
*/
export function isSDAMUnrecoverableError(error: MongoError): boolean {
// NOTE: null check is here for a strictly pre-CMAP world, a timeout or
// close event are considered unrecoverable
if (error instanceof MongoParseError || error == null) {
return true;
}
return isRecoveringError(error) || isNotMasterError(error);
}
export function isNetworkTimeoutError(err: MongoError): err is MongoNetworkError {
return !!(err instanceof MongoNetworkError && err.message.match(/timed out/));
}
// From spec@https://github.com/mongodb/specifications/blob/7a2e93d85935ee4b1046a8d2ad3514c657dc74fa/source/change-streams/change-streams.rst#resumable-error:
//
// An error is considered resumable if it meets any of the following criteria:
// - any error encountered which is not a server error (e.g. a timeout error or network error)
// - any server error response from a getMore command excluding those containing the error label
// NonRetryableChangeStreamError and those containing the following error codes:
// - Interrupted: 11601
// - CappedPositionLost: 136
// - CursorKilled: 237
//
// An error on an aggregate command is not a resumable error. Only errors on a getMore command may be considered resumable errors.
export function isResumableError(error?: MongoError, wireVersion?: number): boolean {
if (error instanceof MongoNetworkError) {
return true;
}
if (typeof wireVersion !== 'undefined' && wireVersion >= 9) {
// DRIVERS-1308: For 4.4 drivers running against 4.4 servers, drivers will add a special case to treat the CursorNotFound error code as resumable
if (error && error instanceof MongoError && error.code === 43) {
return true;
}
return error instanceof MongoError && error.hasErrorLabel('ResumableChangeStreamError');
}
if (error && typeof error.code === 'number') {
return GET_MORE_RESUMABLE_CODES.has(error.code);
}
return false;
}