|
1 | 1 | import { inspect, promisify } from 'util';
|
| 2 | +import { isUint8Array } from 'util/types'; |
2 | 3 |
|
3 | 4 | import { type Document, EJSON, type EJSONOptions, type ObjectId } from './bson';
|
4 | 5 | import type { CommandStartedEvent } from './cmap/command_monitoring_events';
|
@@ -421,13 +422,44 @@ export function stringifyWithMaxLen(
|
421 | 422 | ): string {
|
422 | 423 | let strToTruncate = '';
|
423 | 424 |
|
| 425 | + let currentLength = 0; |
| 426 | + const maxDocumentLengthEnsurer = function maxDocumentLengthEnsurer(key: string, value: any) { |
| 427 | + if (currentLength >= maxDocumentLength) { |
| 428 | + return undefined; |
| 429 | + } |
| 430 | + |
| 431 | + currentLength += key.length + 4; |
| 432 | + |
| 433 | + if (typeof value === 'string') { |
| 434 | + currentLength += value.length; |
| 435 | + } else if (typeof value === 'number' || typeof value === 'bigint') { |
| 436 | + currentLength += 20; |
| 437 | + } else if (typeof value === 'boolean') { |
| 438 | + currentLength += value ? 4 : 5; |
| 439 | + } else if (value != null && typeof value === 'object' && '_bsontype' in value) { |
| 440 | + if (isUint8Array(value.buffer)) { |
| 441 | + currentLength += (value.buffer.byteLength + value.buffer.byteLength * 0.5) | 0; |
| 442 | + } else if (value._bsontype === 'Binary') { |
| 443 | + currentLength += (value.position + value.position * 0.3) | 0; |
| 444 | + } else if (value._bsontype === 'Code') { |
| 445 | + currentLength += value.code.length; |
| 446 | + } |
| 447 | + } |
| 448 | + |
| 449 | + return value; |
| 450 | + }; |
| 451 | + |
424 | 452 | if (typeof value === 'string') {
|
425 | 453 | strToTruncate = value;
|
426 | 454 | } else if (typeof value === 'function') {
|
427 | 455 | strToTruncate = value.name;
|
428 | 456 | } else {
|
429 | 457 | try {
|
430 |
| - strToTruncate = EJSON.stringify(value, options); |
| 458 | + if (maxDocumentLength !== 0) { |
| 459 | + strToTruncate = EJSON.stringify(value, maxDocumentLengthEnsurer, 0, options); |
| 460 | + } else { |
| 461 | + strToTruncate = EJSON.stringify(value, options); |
| 462 | + } |
431 | 463 | } catch (e) {
|
432 | 464 | strToTruncate = `Extended JSON serialization failed with: ${e.message}`;
|
433 | 465 | }
|
|
0 commit comments