All files / src/gridfs upload.ts

91.9% Statements 159/173
85.26% Branches 81/95
100% Functions 24/24
91.9% Lines 159/173

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560400x   400x   400x 400x           400x 400x   400x                                                                                     400x                                                                                                     8042x                     8042x   8042x 8042x 8042x 8042x 8042x 8042x 8042x   8042x   8042x   8042x 8042x 8042x 8042x 8042x 8042x             8042x 2865x                         8042x 7792x   7792x   6646x 6646x 6646x     1146x 1146x             250x                                 6268x         5577x     5577x 5577x               996x         996x   59x     937x 937x       937x         2101x       2101x 2101x       643301x                 6504x     6504x         6504x 6504x             2631x 2440x   191x       6313x 4463x 4463x 590x   3873x     6313x 5723x     5723x                   7187x       7187x   5195x   5195x                   5195x       5195x 5195x                   5195x       5004x 5004x     191x     5195x     1992x       7792x     7792x             7601x   524x     7077x     7077x     7077x       7077x 7077x   2822x 2440x   382x       6695x 4845x 4845x 590x   4255x     6695x 6105x       6105x     6504x                       5195x               5195x 229x     5195x       5195x 229x     5195x                 6268x 250x     6018x   6018x     6018x 3644x 3644x 3644x 3644x         2374x 2374x 2374x 2374x 2374x 640115x 640115x 640115x 640115x   640115x 639022x   639022x 639022x                   639022x 639022x   639022x       639022x       638640x 638640x   638640x 1992x       382x       639022x 639022x 639022x   640115x 640115x           5577x 1298x         4279x 4279x 4279x     4279x       4279x 4279x                 4279x 4279x       3897x 3897x     382x           654764x 250x 250x   654514x    
import { Writable } from 'stream';
 
import { type Document, ObjectId } from '../bson';
import type { Collection } from '../collection';
import { CursorTimeoutMode } from '../cursor/abstract_cursor';
import {
  MongoAPIError,
  MONGODB_ERROR_CODES,
  MongoError,
  MongoOperationTimeoutError
} from '../error';
import { CSOTTimeoutContext } from '../timeout';
import { type Callback, resolveTimeoutOptions, squashError } from '../utils';
import type { WriteConcernOptions } from '../write_concern';
import { WriteConcern } from './../write_concern';
import type { GridFSFile } from './download';
import type { GridFSBucket } from './index';
 
/** @public */
export interface GridFSChunk {
  _id: ObjectId;
  files_id: ObjectId;
  n: number;
  data: Buffer | Uint8Array;
}
 
/** @public */
export interface GridFSBucketWriteStreamOptions extends WriteConcernOptions {
  /** Overwrite this bucket's chunkSizeBytes for this file */
  chunkSizeBytes?: number;
  /** Custom file id for the GridFS file. */
  id?: ObjectId;
  /** Object to store in the file document's `metadata` field */
  metadata?: Document;
  /**
   * String to store in the file document's `contentType` field.
   * @deprecated Will be removed in the next major version. Add a contentType field to the metadata document instead.
   */
  contentType?: string;
  /**
   * Array of strings to store in the file document's `aliases` field.
   * @deprecated Will be removed in the next major version. Add an aliases field to the metadata document instead.
   */
  aliases?: string[];
  /**
   * @experimental
   * Specifies the time an operation will run until it throws a timeout error
   */
  timeoutMS?: number;
}
 
/**
 * A writable stream that enables you to write buffers to GridFS.
 *
 * Do not instantiate this class directly. Use `openUploadStream()` instead.
 * @public
 */
export class GridFSBucketWriteStream extends Writable {
  bucket: GridFSBucket;
  /** A Collection instance where the file's chunks are stored */
  chunks: Collection<GridFSChunk>;
  /** A Collection instance where the file's GridFSFile document is stored */
  files: Collection<GridFSFile>;
  /** The name of the file */
  filename: string;
  /** Options controlling the metadata inserted along with the file */
  options: GridFSBucketWriteStreamOptions;
  /** Indicates the stream is finished uploading */
  done: boolean;
  /** The ObjectId used for the `_id` field on the GridFSFile document */
  id: ObjectId;
  /** The number of bytes that each chunk will be limited to */
  chunkSizeBytes: number;
  /** Space used to store a chunk currently being inserted */
  bufToStore: Buffer;
  /** Accumulates the number of bytes inserted as the stream uploads chunks */
  length: number;
  /** Accumulates the number of chunks inserted as the stream uploads file contents */
  n: number;
  /** Tracks the current offset into the buffered bytes being uploaded */
  pos: number;
  /** Contains a number of properties indicating the current state of the stream */
  state: {
    /** If set the stream has ended */
    streamEnd: boolean;
    /** Indicates the number of chunks that still need to be inserted to exhaust the current buffered data */
    outstandingRequests: number;
    /** If set an error occurred during insertion */
    errored: boolean;
    /** If set the stream was intentionally aborted */
    aborted: boolean;
  };
  /** The write concern setting to be used with every insert operation */
  writeConcern?: WriteConcern;
  /**
   * The document containing information about the inserted file.
   * This property is defined _after_ the finish event has been emitted.
   * It will remain `null` if an error occurs.
   *
   * @example
   * ```ts
   * fs.createReadStream('file.txt')
   *   .pipe(bucket.openUploadStream('file.txt'))
   *   .on('finish', function () {
   *     console.log(this.gridFSFile)
   *   })
   * ```
   */
  gridFSFile: GridFSFile | null = null;
  /** @internal */
  timeoutContext?: CSOTTimeoutContext;
 
  /**
   * @param bucket - Handle for this stream's corresponding bucket
   * @param filename - The value of the 'filename' key in the files doc
   * @param options - Optional settings.
   * @internal
   */
  constructor(bucket: GridFSBucket, filename: string, options?: GridFSBucketWriteStreamOptions) {
    super();
 
    options = options ?? {};
    this.bucket = bucket;
    this.chunks = bucket.s._chunksCollection;
    this.filename = filename;
    this.files = bucket.s._filesCollection;
    this.options = options;
    this.writeConcern = WriteConcern.fromOptions(options) || bucket.s.options.writeConcern;
    // Signals the write is all done
    this.done = false;
 
    this.id = options.id ? options.id : new ObjectId();
    // properly inherit the default chunksize from parent
    this.chunkSizeBytes = options.chunkSizeBytes || this.bucket.s.options.chunkSizeBytes;
    this.bufToStore = Buffer.alloc(this.chunkSizeBytes);
    this.length = 0;
    this.n = 0;
    this.pos = 0;
    this.state = {
      streamEnd: false,
      outstandingRequests: 0,
      errored: false,
      aborted: false
    };
 
    if (options.timeoutMS != null)
      this.timeoutContext = new CSOTTimeoutContext({
        timeoutMS: options.timeoutMS,
        serverSelectionTimeoutMS: resolveTimeoutOptions(this.bucket.s.db.client, {})
          .serverSelectionTimeoutMS
      });
  }
 
  /**
   * @internal
   *
   * The stream is considered constructed when the indexes are done being created
   */
  override _construct(callback: (error?: Error | null) => void): void {
    if (!this.bucket.s.calledOpenUploadStream) {
      this.bucket.s.calledOpenUploadStream = true;
 
      checkIndexes(this).then(
        () => {
          this.bucket.s.checkedIndexes = true;
          this.bucket.emit('index');
          callback();
        },
        error => {
          Eif (error instanceof MongoOperationTimeoutError) {
            return handleError(this, error, callback);
          }
          squashError(error);
          callback();
        }
      );
    } else {
      return process.nextTick(callback);
    }
  }
 
  /**
   * @internal
   * Write a buffer to the stream.
   *
   * @param chunk - Buffer to write
   * @param encoding - Optional encoding for the buffer
   * @param callback - Function to call when the chunk was added to the buffer, or if the entire chunk was persisted to MongoDB if this chunk caused a flush.
   */
  override _write(
    chunk: Buffer | string,
    encoding: BufferEncoding,
    callback: Callback<void>
  ): void {
    doWrite(this, chunk, encoding, callback);
  }
 
  /** @internal */
  override _final(callback: (error?: Error | null) => void): void {
    Iif (this.state.streamEnd) {
      return process.nextTick(callback);
    }
    this.state.streamEnd = true;
    writeRemnant(this, callback);
  }
 
  /**
   * Places this write stream into an aborted state (all future writes fail)
   * and deletes all chunks that have already been written.
   */
  async abort(): Promise<void> {
    Iif (this.state.streamEnd) {
      // TODO(NODE-3485): Replace with MongoGridFSStreamClosed
      throw new MongoAPIError('Cannot abort a stream that has already completed');
    }
 
    if (this.state.aborted) {
      // TODO(NODE-3485): Replace with MongoGridFSStreamClosed
      throw new MongoAPIError('Cannot call abort() on a stream twice');
    }
 
    this.state.aborted = true;
    const remainingTimeMS = this.timeoutContext?.getRemainingTimeMSOrThrow(
      `Upload timed out after ${this.timeoutContext?.timeoutMS}ms`
    );
 
    await this.chunks.deleteMany({ files_id: this.id }, { timeoutMS: remainingTimeMS });
  }
}
 
function handleError(stream: GridFSBucketWriteStream, error: Error, callback: Callback): void {
  Iif (stream.state.errored) {
    process.nextTick(callback);
    return;
  }
  stream.state.errored = true;
  process.nextTick(callback, error);
}
 
function createChunkDoc(filesId: ObjectId, n: number, data: Buffer): GridFSChunk {
  return {
    _id: new ObjectId(),
    files_id: filesId,
    n,
    data
  };
}
 
async function checkChunksIndex(stream: GridFSBucketWriteStream): Promise<void> {
  const index = { files_id: 1, n: 1 };
 
  let remainingTimeMS;
  remainingTimeMS = stream.timeoutContext?.getRemainingTimeMSOrThrow(
    `Upload timed out after ${stream.timeoutContext?.timeoutMS}ms`
  );
 
  let indexes;
  try {
    indexes = await stream.chunks
      .listIndexes({
        timeoutMode: remainingTimeMS != null ? CursorTimeoutMode.LIFETIME : undefined,
        timeoutMS: remainingTimeMS
      })
      .toArray();
  } catch (error) {
    if (error instanceof MongoError && error.code === MONGODB_ERROR_CODES.NamespaceNotFound) {
      indexes = [];
    } else {
      throw error;
    }
  }
 
  const hasChunksIndex = !!indexes.find(index => {
    const keys = Object.keys(index.key);
    if (keys.length === 2 && index.key.files_id === 1 && index.key.n === 1) {
      return true;
    }
    return false;
  });
 
  if (!hasChunksIndex) {
    remainingTimeMS = stream.timeoutContext?.getRemainingTimeMSOrThrow(
      `Upload timed out after ${stream.timeoutContext?.timeoutMS}ms`
    );
    await stream.chunks.createIndex(index, {
      ...stream.writeConcern,
      background: true,
      unique: true,
      timeoutMS: remainingTimeMS
    });
  }
}
 
function checkDone(stream: GridFSBucketWriteStream, callback: Callback): void {
  Iif (stream.done) {
    return process.nextTick(callback);
  }
 
  if (stream.state.streamEnd && stream.state.outstandingRequests === 0 && !stream.state.errored) {
    // Set done so we do not trigger duplicate createFilesDoc
    stream.done = true;
    // Create a new files doc
    const gridFSFile = createFilesDoc(
      stream.id,
      stream.length,
      stream.chunkSizeBytes,
      stream.filename,
      stream.options.contentType,
      stream.options.aliases,
      stream.options.metadata
    );
 
    Iif (isAborted(stream, callback)) {
      return;
    }
 
    const remainingTimeMS = stream.timeoutContext?.remainingTimeMS;
    Iif (remainingTimeMS != null && remainingTimeMS <= 0) {
      return handleError(
        stream,
        new MongoOperationTimeoutError(
          `Upload timed out after ${stream.timeoutContext?.timeoutMS}ms`
        ),
        callback
      );
    }
 
    stream.files
      .insertOne(gridFSFile, { writeConcern: stream.writeConcern, timeoutMS: remainingTimeMS })
      .then(
        () => {
          stream.gridFSFile = gridFSFile;
          callback();
        },
        error => {
          return handleError(stream, error, callback);
        }
      );
    return;
  }
 
  process.nextTick(callback);
}
 
async function checkIndexes(stream: GridFSBucketWriteStream): Promise<void> {
  let remainingTimeMS = stream.timeoutContext?.getRemainingTimeMSOrThrow(
    `Upload timed out after ${stream.timeoutContext?.timeoutMS}ms`
  );
  const doc = await stream.files.findOne(
    {},
    {
      projection: { _id: 1 },
      timeoutMS: remainingTimeMS
    }
  );
  if (doc != null) {
    // If at least one document exists assume the collection has the required index
    return;
  }
 
  const index = { filename: 1, uploadDate: 1 };
 
  let indexes;
  remainingTimeMS = stream.timeoutContext?.getRemainingTimeMSOrThrow(
    `Upload timed out after ${stream.timeoutContext?.timeoutMS}ms`
  );
  const listIndexesOptions = {
    timeoutMode: remainingTimeMS != null ? CursorTimeoutMode.LIFETIME : undefined,
    timeoutMS: remainingTimeMS
  };
  try {
    indexes = await stream.files.listIndexes(listIndexesOptions).toArray();
  } catch (error) {
    if (error instanceof MongoError && error.code === MONGODB_ERROR_CODES.NamespaceNotFound) {
      indexes = [];
    } else {
      throw error;
    }
  }
 
  const hasFileIndex = !!indexes.find(index => {
    const keys = Object.keys(index.key);
    if (keys.length === 2 && index.key.filename === 1 && index.key.uploadDate === 1) {
      return true;
    }
    return false;
  });
 
  if (!hasFileIndex) {
    remainingTimeMS = stream.timeoutContext?.getRemainingTimeMSOrThrow(
      `Upload timed out after ${stream.timeoutContext?.timeoutMS}ms`
    );
 
    await stream.files.createIndex(index, { background: false, timeoutMS: remainingTimeMS });
  }
 
  await checkChunksIndex(stream);
}
 
function createFilesDoc(
  _id: ObjectId,
  length: number,
  chunkSize: number,
  filename: string,
  contentType?: string,
  aliases?: string[],
  metadata?: Document
): GridFSFile {
  const ret: GridFSFile = {
    _id,
    length,
    chunkSize,
    uploadDate: new Date(),
    filename
  };
 
  if (contentType) {
    ret.contentType = contentType;
  }
 
  Iif (aliases) {
    ret.aliases = aliases;
  }
 
  if (metadata) {
    ret.metadata = metadata;
  }
 
  return ret;
}
 
function doWrite(
  stream: GridFSBucketWriteStream,
  chunk: Buffer | string,
  encoding: BufferEncoding,
  callback: Callback<void>
): void {
  if (isAborted(stream, callback)) {
    return;
  }
 
  const inputBuf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding);
 
  stream.length += inputBuf.length;
 
  // Input is small enough to fit in our buffer
  if (stream.pos + inputBuf.length < stream.chunkSizeBytes) {
    inputBuf.copy(stream.bufToStore, stream.pos);
    stream.pos += inputBuf.length;
    process.nextTick(callback);
    return;
  }
 
  // Otherwise, buffer is too big for current chunk, so we need to flush
  // to MongoDB.
  let inputBufRemaining = inputBuf.length;
  let spaceRemaining: number = stream.chunkSizeBytes - stream.pos;
  let numToCopy = Math.min(spaceRemaining, inputBuf.length);
  let outstandingRequests = 0;
  while (inputBufRemaining > 0) {
    const inputBufPos = inputBuf.length - inputBufRemaining;
    inputBuf.copy(stream.bufToStore, stream.pos, inputBufPos, inputBufPos + numToCopy);
    stream.pos += numToCopy;
    spaceRemaining -= numToCopy;
    let doc: GridFSChunk;
    if (spaceRemaining === 0) {
      doc = createChunkDoc(stream.id, stream.n, Buffer.from(stream.bufToStore));
 
      const remainingTimeMS = stream.timeoutContext?.remainingTimeMS;
      Iif (remainingTimeMS != null && remainingTimeMS <= 0) {
        return handleError(
          stream,
          new MongoOperationTimeoutError(
            `Upload timed out after ${stream.timeoutContext?.timeoutMS}ms`
          ),
          callback
        );
      }
 
      ++stream.state.outstandingRequests;
      ++outstandingRequests;
 
      Iif (isAborted(stream, callback)) {
        return;
      }
 
      stream.chunks
        .insertOne(doc, { writeConcern: stream.writeConcern, timeoutMS: remainingTimeMS })
        .then(
          () => {
            --stream.state.outstandingRequests;
            --outstandingRequests;
 
            if (!outstandingRequests) {
              checkDone(stream, callback);
            }
          },
          error => {
            return handleError(stream, error, callback);
          }
        );
 
      spaceRemaining = stream.chunkSizeBytes;
      stream.pos = 0;
      ++stream.n;
    }
    inputBufRemaining -= numToCopy;
    numToCopy = Math.min(spaceRemaining, inputBufRemaining);
  }
}
 
function writeRemnant(stream: GridFSBucketWriteStream, callback: Callback): void {
  // Buffer is empty, so don't bother to insert
  if (stream.pos === 0) {
    return checkDone(stream, callback);
  }
 
  // Create a new buffer to make sure the buffer isn't bigger than it needs
  // to be.
  const remnant = Buffer.alloc(stream.pos);
  stream.bufToStore.copy(remnant, 0, 0, stream.pos);
  const doc = createChunkDoc(stream.id, stream.n, remnant);
 
  // If the stream was aborted, do not write remnant
  Iif (isAborted(stream, callback)) {
    return;
  }
 
  const remainingTimeMS = stream.timeoutContext?.remainingTimeMS;
  Iif (remainingTimeMS != null && remainingTimeMS <= 0) {
    return handleError(
      stream,
      new MongoOperationTimeoutError(
        `Upload timed out after ${stream.timeoutContext?.timeoutMS}ms`
      ),
      callback
    );
  }
  ++stream.state.outstandingRequests;
  stream.chunks
    .insertOne(doc, { writeConcern: stream.writeConcern, timeoutMS: remainingTimeMS })
    .then(
      () => {
        --stream.state.outstandingRequests;
        checkDone(stream, callback);
      },
      error => {
        return handleError(stream, error, callback);
      }
    );
}
 
function isAborted(stream: GridFSBucketWriteStream, callback: Callback<void>): boolean {
  if (stream.state.aborted) {
    process.nextTick(callback, new MongoAPIError('Stream has been aborted'));
    return true;
  }
  return false;
}