@google-cloud/spanner 9.0.0 → 9.1.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 (40) hide show
  1. package/README.md +1 -16
  2. package/build/src/batch-transaction.js +15 -12
  3. package/build/src/codec.d.ts +6 -0
  4. package/build/src/codec.js +99 -34
  5. package/build/src/common.d.ts +14 -0
  6. package/build/src/common.js +27 -1
  7. package/build/src/database.d.ts +31 -41
  8. package/build/src/database.js +122 -313
  9. package/build/src/helper.d.ts +12 -0
  10. package/build/src/helper.js +44 -0
  11. package/build/src/index.d.ts +16 -8
  12. package/build/src/index.js +210 -90
  13. package/build/src/instance.d.ts +15 -2
  14. package/build/src/instance.js +11 -2
  15. package/build/src/instrument.d.ts +12 -1
  16. package/build/src/instrument.js +13 -0
  17. package/build/src/metrics/constants.d.ts +6 -0
  18. package/build/src/metrics/constants.js +6 -1
  19. package/build/src/metrics/interceptor.js +32 -28
  20. package/build/src/metrics/metrics-tracer-factory.d.ts +6 -11
  21. package/build/src/metrics/metrics-tracer-factory.js +62 -64
  22. package/build/src/metrics/metrics-tracer.d.ts +19 -6
  23. package/build/src/metrics/metrics-tracer.js +147 -55
  24. package/build/src/multiplexed-session.d.ts +13 -2
  25. package/build/src/multiplexed-session.js +20 -4
  26. package/build/src/partial-result-stream.d.ts +26 -33
  27. package/build/src/partial-result-stream.js +263 -283
  28. package/build/src/request-stream-coordinator.d.ts +88 -0
  29. package/build/src/request-stream-coordinator.js +229 -0
  30. package/build/src/request_id_header.d.ts +6 -4
  31. package/build/src/request_id_header.js +24 -24
  32. package/build/src/session-factory.d.ts +52 -63
  33. package/build/src/session-factory.js +41 -92
  34. package/build/src/session-pool.d.ts +97 -227
  35. package/build/src/session-pool.js +74 -547
  36. package/build/src/session.js +1 -1
  37. package/build/src/transaction-runner.js +1 -12
  38. package/build/src/transaction.d.ts +5 -5
  39. package/build/src/transaction.js +72 -112
  40. package/package.json +9 -10
@@ -169,20 +169,18 @@ function decodeRowsDirect(chunk, options, existingFields, existingDecoders) {
169
169
  * @param {RowOptions} [options] The row options.
170
170
  */
171
171
  class PartialResultStream extends stream_1.Transform {
172
- _destroyed;
173
172
  _fields;
174
173
  _decoders;
175
174
  _options;
176
175
  _pendingValue;
177
- _pendingValueForResume;
178
- _values;
179
- _numPushFailed = 0;
176
+ _rowValues;
177
+ _valueIndex;
178
+ _resumeCallback;
180
179
  _isFirstChunk = true;
181
180
  constructor(options = {}) {
182
181
  super({ objectMode: true });
183
- this._destroyed = false;
184
- this._options = Object.assign({ maxResumeRetries: 20 }, options);
185
- this._values = [];
182
+ this._options = Object.assign({}, options);
183
+ this._valueIndex = 0;
186
184
  this._isFirstChunk = true;
187
185
  }
188
186
  /**
@@ -191,17 +189,12 @@ class PartialResultStream extends stream_1.Transform {
191
189
  * @param {Error} [err] Optional error to destroy stream with.
192
190
  */
193
191
  destroy(err) {
194
- if (this._destroyed) {
192
+ if (this.destroyed) {
195
193
  return this;
196
194
  }
197
- this._destroyed = true;
198
- process.nextTick(() => {
199
- if (err) {
200
- this.emit('error', err);
201
- }
202
- this.emit('close');
203
- });
204
- return this;
195
+ this._rowValues = undefined;
196
+ this._resumeCallback = undefined;
197
+ return super.destroy(err);
205
198
  }
206
199
  /**
207
200
  * Processes each chunk.
@@ -213,6 +206,9 @@ class PartialResultStream extends stream_1.Transform {
213
206
  * @param {function} next Function to be called upon completion.
214
207
  */
215
208
  _transform(chunk, enc, next) {
209
+ if (this.destroyed) {
210
+ return;
211
+ }
216
212
  this.emit('response', chunk);
217
213
  if (chunk.stats) {
218
214
  this.emit('stats', chunk.stats);
@@ -222,10 +218,10 @@ class PartialResultStream extends stream_1.Transform {
222
218
  .fields;
223
219
  this._decoders = createFieldDecoders(this._fields, this._options);
224
220
  }
225
- let res = true;
221
+ let canAcceptMore = true;
226
222
  if (!(0, helper_1.isEmpty)(chunk.values)) {
227
223
  try {
228
- res = this._addChunk(chunk);
224
+ canAcceptMore = this._addChunk(chunk);
229
225
  }
230
226
  catch (err) {
231
227
  next(err);
@@ -233,7 +229,14 @@ class PartialResultStream extends stream_1.Transform {
233
229
  }
234
230
  }
235
231
  if (chunk.last) {
232
+ if (this._valueIndex !== 0 || this._pendingValue !== undefined) {
233
+ next(new Error('Stream received chunk.last=true before row or chunked value was complete.'));
234
+ return;
235
+ }
236
236
  this.push(null);
237
+ if (!canAcceptMore) {
238
+ this.emit('paused');
239
+ }
237
240
  // Calling next() notifies Node's stream machinery that processing of this
238
241
  // chunk is complete on the Writable side of this Transform stream.
239
242
  // This is a local, synchronous callback to Node's internal buffer; it does
@@ -241,99 +244,111 @@ class PartialResultStream extends stream_1.Transform {
241
244
  next();
242
245
  return;
243
246
  }
244
- if (res) {
247
+ if (canAcceptMore) {
245
248
  next();
246
249
  }
247
250
  else {
248
- // Wait a little before we push any more data into the pipeline as a
249
- // component downstream has indicated that a break is needed. Pause the
250
- // request stream to prevent it from filling up the buffer while we are
251
- // waiting.
252
- // The stream will initially pause for 2ms, and then double the pause time
253
- // for each new pause.
254
- const initialPauseMs = 2;
255
- setTimeout(() => {
256
- this._tryResume(next, 2 * initialPauseMs);
257
- }, initialPauseMs);
251
+ // Downstream buffer has reached highWaterMark and cannot accept more data
252
+ // at the moment. Hold the completion callback until the downstream consumer
253
+ // drains and Node invokes _read(), resuming the upstream request stream.
254
+ this._resumeCallback = next;
255
+ this.emit('paused');
258
256
  }
259
257
  }
260
- _tryResume(next, timeout) {
261
- // Try to push an empty chunk to check whether more data can be accepted.
262
- if (this.push(undefined)) {
263
- this._numPushFailed = 0;
264
- this.emit('resumed');
265
- next();
266
- }
267
- else {
268
- // Downstream returned false indicating that it is still not ready for
269
- // more data.
270
- this._numPushFailed++;
271
- if (this._numPushFailed === this._options.maxResumeRetries) {
272
- this.destroy(new Error(`Stream is still not ready to receive data after ${this._numPushFailed} attempts to resume.`));
273
- return;
274
- }
275
- setTimeout(() => {
276
- const nextTimeout = Math.min(timeout * 2, 1024);
277
- this._tryResume(next, nextTimeout);
278
- }, timeout);
258
+ _flush(callback) {
259
+ if (this._valueIndex !== 0 || this._pendingValue !== undefined) {
260
+ callback(new Error('Stream ended prematurely before row or chunked value was complete.'));
261
+ return;
279
262
  }
263
+ callback();
280
264
  }
281
- _resetPendingValues() {
282
- if (this._pendingValueForResume) {
283
- this._pendingValue = this._pendingValueForResume;
284
- }
285
- else {
286
- delete this._pendingValue;
265
+ _read(size) {
266
+ if (this._resumeCallback) {
267
+ const callback = this._resumeCallback;
268
+ this._resumeCallback = undefined;
269
+ this.emit('resumed');
270
+ callback();
287
271
  }
272
+ super._read(size);
288
273
  }
289
274
  /**
290
- * Manages any chunked values.
275
+ * Manages stream chunks, chunked value merging across chunk boundaries,
276
+ * row assembly, and resume token checkpoints.
291
277
  *
292
- * @private
278
+ * Processing follows 4 distinct stages:
279
+ * 1. Single-chunk fast path: If the entire stream response is in this first chunk,
280
+ * decode rows directly and bypass incremental chunk buffering.
281
+ * 2. Pending value merge: If the previous chunk ended with an incomplete chunked
282
+ * value, merge it with the incoming continuation value at chunkValues[0].
283
+ * 3. Chunked value hold: If this chunk ends with a chunked value, hold the tail
284
+ * value (chunkValues[numValues - 1]) in `this._pendingValue` for the next chunk.
285
+ * 4. Complete value decoding: Iterate from `startIndex` to `endIndex`, decoding
286
+ * and adding values into row buffers via `_addValue`.
293
287
  *
294
- * @param {object} chunk The partial result set.
288
+ * @private
289
+ * @param {google.spanner.v1.PartialResultSet} chunk The partial result set.
290
+ * @returns {boolean} Whether downstream can accept more data.
295
291
  */
296
292
  _addChunk(chunk) {
297
293
  const isFirstChunk = this._isFirstChunk;
298
294
  this._isFirstChunk = false;
299
- // Fast path for single-chunk stream responses:
295
+ // Stage 1: Fast path for single-chunk stream responses:
300
296
  if (isFirstChunk && chunk.last && !chunk.chunkedValue) {
301
297
  return this._addSingleChunk(chunk);
302
298
  }
303
299
  const chunkValues = chunk.values;
304
300
  const numValues = chunkValues.length;
305
- const values = new Array(numValues);
306
- for (let i = 0; i < numValues; i++) {
307
- values[i] = service_1.GrpcService.decodeValue_(chunkValues[i]);
308
- }
309
- // If we have a chunk to merge, merge the values now.
310
- if (this._pendingValue) {
311
- const currentField = this._values.length % this._fields.length;
301
+ let startIndex = 0;
302
+ let endIndex = numValues;
303
+ let canAcceptMore = true;
304
+ // Stage 2: Merge pending chunked value from the previous chunk with the
305
+ // incoming continuation value at chunkValues[0].
306
+ if (this._pendingValue !== undefined && numValues > 0) {
307
+ const currentField = this._valueIndex;
312
308
  const field = this._fields[currentField];
313
- const merged = PartialResultStream.merge(field.type, this._pendingValue, values.shift());
314
- values.unshift(...merged);
315
- delete this._pendingValue;
316
- }
317
- // If the chunk is chunked, store the last value for merging with the next
318
- // chunk to be processed.
319
- if (chunk.chunkedValue) {
320
- this._pendingValue = values.pop();
321
- if (_hasResumeToken(chunk)) {
322
- this._pendingValueForResume = this._pendingValue;
309
+ const headValue = this._pendingValue;
310
+ const continuationValue = service_1.GrpcService.decodeValue_(chunkValues[0]);
311
+ const merged = PartialResultStream.merge(field.type, headValue, continuationValue);
312
+ // We consumed chunkValues[0] as the continuation of the pending value.
313
+ startIndex = 1;
314
+ // If this chunk only had 1 value and is still chunked, the last element
315
+ // of merged remains pending for the next chunk.
316
+ let mergedCount = merged.length;
317
+ if (numValues === 1 && chunk.chunkedValue) {
318
+ mergedCount--;
319
+ this._pendingValue = merged[mergedCount];
320
+ }
321
+ else {
322
+ this._pendingValue = undefined;
323
+ }
324
+ for (let i = 0; i < mergedCount; i++) {
325
+ if (this.destroyed) {
326
+ return false;
327
+ }
328
+ if (!this._addValue(merged[i]) && canAcceptMore) {
329
+ canAcceptMore = false;
330
+ }
323
331
  }
324
332
  }
325
- else if (_hasResumeToken(chunk)) {
326
- delete this._pendingValueForResume;
333
+ // Stage 3: If this chunk ends with a chunked value, hold the tail value for
334
+ // merging with the next chunk instead of decoding it into the current row now.
335
+ if (chunk.chunkedValue && numValues > 0) {
336
+ if (numValues > 1 || !startIndex) {
337
+ endIndex = numValues - 1;
338
+ this._pendingValue = service_1.GrpcService.decodeValue_(chunkValues[numValues - 1]);
339
+ }
327
340
  }
328
- let res = true;
329
- const len = values.length;
330
- for (let i = 0; i < len; i++) {
331
- res = this._addValue(values[i]) && res;
332
- if (!res) {
333
- this.emit('paused');
341
+ // Stage 4: Decode in-place and push complete values into row buffers.
342
+ for (let i = startIndex; i < endIndex; i++) {
343
+ if (this.destroyed) {
344
+ return false;
345
+ }
346
+ const value = service_1.GrpcService.decodeValue_(chunkValues[i]);
347
+ if (!this._addValue(value) && canAcceptMore) {
348
+ canAcceptMore = false;
334
349
  }
335
350
  }
336
- return res;
351
+ return canAcceptMore;
337
352
  }
338
353
  /**
339
354
  * Fast-path handler for single-chunk stream responses. Decodes rows directly
@@ -344,13 +359,19 @@ class PartialResultStream extends stream_1.Transform {
344
359
  * @returns {boolean} Whether the stream can accept more data.
345
360
  */
346
361
  _addSingleChunk(chunk) {
362
+ const chunkValues = chunk.values || [];
363
+ if (chunkValues.length % this._fields.length !== 0) {
364
+ throw new Error('Stream received chunk.last=true before row or chunked value was complete.');
365
+ }
347
366
  const rows = decodeRowsDirect(chunk, this._options, this._fields, this._decoders);
348
367
  let canAcceptMore = true;
349
368
  for (let i = 0; i < rows.length; i++) {
369
+ if (this.destroyed) {
370
+ return false;
371
+ }
350
372
  const accepted = this.push(rows[i]);
351
373
  if (!accepted && canAcceptMore) {
352
374
  canAcceptMore = false;
353
- this.emit('paused');
354
375
  }
355
376
  }
356
377
  return canAcceptMore;
@@ -364,36 +385,18 @@ class PartialResultStream extends stream_1.Transform {
364
385
  * @param {*} value The complete value.
365
386
  */
366
387
  _addValue(value) {
367
- const values = this._values;
368
- values.push(value);
369
- if (values.length !== this._fields.length) {
388
+ if (this.destroyed) {
389
+ return false;
390
+ }
391
+ if (!this._rowValues) {
392
+ this._rowValues = new Array(this._fields.length);
393
+ }
394
+ this._rowValues[this._valueIndex++] = value;
395
+ if (this._valueIndex !== this._fields.length) {
370
396
  return true;
371
397
  }
372
- this._values = [];
373
- return this.push(formatRow(this._fields, this._decoders, values, this._options));
374
- }
375
- /**
376
- * Directly creates a plain JSON object from row cell values, bypassing
377
- * Struct, Row, and WrappedNumber class wrappers when possible.
378
- *
379
- * @private
380
- *
381
- * @param {Value[]} values The raw cell values for the current row.
382
- * @returns {Json} The plain JavaScript object representing the row.
383
- */
384
- _createJsonRow(values) {
385
- return createJsonRow(this._fields, this._decoders, values, Boolean(this._options.jsonOptions?.includeNameless));
386
- }
387
- /**
388
- * Converts an array of values into a row.
389
- *
390
- * @private
391
- *
392
- * @param {Array.<*>} values The row values.
393
- * @returns {Row}
394
- */
395
- _createRow(values) {
396
- return createRow(this._fields, this._decoders, values);
398
+ this._valueIndex = 0;
399
+ return this.push(formatRow(this._fields, this._decoders, this._rowValues, this._options));
397
400
  }
398
401
  /**
399
402
  * Attempts to merge chunked values together.
@@ -434,6 +437,12 @@ class PartialResultStream extends stream_1.Transform {
434
437
  * @returns {Array.<*>}
435
438
  */
436
439
  static mergeLists(type, head, tail) {
440
+ if (head.length === 0) {
441
+ return tail;
442
+ }
443
+ if (tail.length === 0) {
444
+ return head;
445
+ }
437
446
  let listType;
438
447
  if (type.code === 'ARRAY' ||
439
448
  type.code === google.spanner.v1.TypeCode.ARRAY) {
@@ -448,83 +457,6 @@ class PartialResultStream extends stream_1.Transform {
448
457
  }
449
458
  }
450
459
  exports.PartialResultStream = PartialResultStream;
451
- /**
452
- * A custom Transform stream that buffers PartialResultSet chunks and flushes them
453
- * asynchronously to prevent blocking the event loop.
454
- *
455
- * It holds chunks in a queue until a "checkpoint" is reached (as determined by
456
- * `isCheckpointFn`) or until the queue exceeds `maxQueued` items.
457
- *
458
- * @private
459
- */
460
- class CheckpointStream extends stream_1.Transform {
461
- queue = [];
462
- maxQueued;
463
- isCheckpointFn;
464
- constructor(options) {
465
- super({ objectMode: true });
466
- this.maxQueued = options.maxQueued ?? 10;
467
- this.isCheckpointFn = options.isCheckpointFn;
468
- }
469
- /**
470
- * Buffers chunks and flushes queue synchronously on checkpoints or when max limit is reached.
471
- *
472
- * @param {google.spanner.v1.PartialResultSet} chunk The chunk to transform.
473
- * @param {string} enc Encoding (unused).
474
- * @param {Function} callback Callback to signal completion of transformation.
475
- */
476
- _transform(chunk, enc, callback) {
477
- this.queue.push(chunk);
478
- const isCheckpoint = this.isCheckpointFn(chunk);
479
- let shouldFlush = false;
480
- if (isCheckpoint) {
481
- this.emit('checkpoint', chunk);
482
- shouldFlush = true;
483
- }
484
- else if (this.queue.length > this.maxQueued) {
485
- shouldFlush = true;
486
- }
487
- if (!shouldFlush) {
488
- return callback();
489
- }
490
- this._flushQueue();
491
- callback();
492
- }
493
- /**
494
- * Flushes queued chunks synchronously to prevent state races on retry/reset.
495
- *
496
- * @private
497
- */
498
- _flushQueue() {
499
- while (this.queue.length > 0 && !this.destroyed) {
500
- this.push(this.queue.shift());
501
- }
502
- }
503
- /**
504
- * Flushes remaining queued chunks before destroying the stream with the provided error.
505
- *
506
- * @param {Error} err The error to destroy the stream with.
507
- */
508
- flushAndDestroy(err) {
509
- this._flushQueue();
510
- this.destroy(err);
511
- }
512
- /**
513
- * Clears the queue without flushing, useful when retrying and discarding partial data.
514
- */
515
- reset() {
516
- this.queue = [];
517
- }
518
- /**
519
- * Flushes all remaining queued chunks when the stream ends.
520
- *
521
- * @param {Function} callback Callback to call when flushing is complete.
522
- */
523
- _flush(callback) {
524
- this._flushQueue();
525
- callback();
526
- }
527
- }
528
460
  /**
529
461
  * Rows returned from queries may be chunked, requiring them to be stitched
530
462
  * together. This function returns a stream that will properly assemble these
@@ -546,73 +478,102 @@ function partialResultStream(requestFn, options) {
546
478
  const maxQueued = 10;
547
479
  let lastResumeToken;
548
480
  let lastRequestStream;
481
+ let dataListener;
482
+ let endListener;
549
483
  let errorListener;
550
484
  const startTime = Date.now();
551
485
  const timeout = options?.gaxOptions?.timeout ?? Infinity;
552
- // requestsStream allows multiple streams to be connected into one. This is good;
553
- // if we need to retry a request and pipe more data to the user's stream.
554
- // We also add an additional stream that can be used to flush any remaining
555
- // items in the checkpoint stream that have been received, and that did not
556
- // contain a resume token.
557
- const requestsStream = new stream_1.PassThrough({ objectMode: true });
558
- const flushStream = new stream_1.PassThrough({ objectMode: true });
559
- flushStream.pipe(requestsStream);
560
- const partialRSStream = new PartialResultStream(options);
561
- const userStream = streamEvents(partialRSStream);
562
- // We keep track of the number of PartialResultSets that did not include a
563
- // resume token, as that is an indication whether it is safe to retry the
564
- // stream halfway.
486
+ const chunkQueue = [];
487
+ const partialResultStreamInstance = new PartialResultStream(options);
488
+ const userStream = streamEvents(partialResultStreamInstance);
565
489
  let withoutCheckpointCount = 0;
490
+ let safeToRetry = true;
566
491
  let receivedLast = false;
567
- const batchAndSplitOnTokenStream = new CheckpointStream({
568
- maxQueued,
569
- isCheckpointFn: (chunk) => {
570
- if (chunk.last) {
571
- receivedLast = true;
572
- destroyRequestStream();
573
- requestsStream.end();
492
+ let isDownstreamPaused = false;
493
+ let isStreamEnded = false;
494
+ let isDestroyed = false;
495
+ const drainQueue = () => {
496
+ if (isDestroyed || userStream.destroyed) {
497
+ return;
498
+ }
499
+ let lastCheckpointIndex = -1;
500
+ for (let i = chunkQueue.length - 1; i >= 0; i--) {
501
+ if (_hasResumeToken(chunkQueue[i]) || chunkQueue[i].last) {
502
+ lastCheckpointIndex = i;
503
+ break;
574
504
  }
575
- const withCheckpoint = _hasResumeToken(chunk) || Boolean(chunk.last);
576
- if (withCheckpoint) {
577
- withoutCheckpointCount = 0;
505
+ }
506
+ let safeCount = 0;
507
+ if (isStreamEnded ||
508
+ receivedLast ||
509
+ !safeToRetry ||
510
+ withoutCheckpointCount > maxQueued) {
511
+ safeCount = chunkQueue.length;
512
+ }
513
+ else if (lastCheckpointIndex !== -1) {
514
+ safeCount = lastCheckpointIndex + 1;
515
+ }
516
+ while (safeCount > 0 && !isDownstreamPaused && !userStream.destroyed) {
517
+ const chunk = chunkQueue.shift();
518
+ safeCount--;
519
+ if (lastCheckpointIndex >= 0) {
520
+ lastCheckpointIndex--;
578
521
  }
579
- else {
580
- withoutCheckpointCount++;
522
+ else if (!isStreamEnded && !receivedLast) {
523
+ safeToRetry = false;
581
524
  }
582
- return withCheckpoint;
583
- },
584
- });
585
- // This listener ensures that the last request that executed successfully
586
- // after one or more retries will end the requestsStream.
587
- const endListener = () => {
588
- if (receivedLast) {
589
- return;
590
- }
591
- setImmediate(() => {
592
- if (receivedLast) {
593
- return;
525
+ const canAcceptMore = userStream.write(chunk);
526
+ if (!canAcceptMore) {
527
+ isDownstreamPaused = true;
528
+ if (lastRequestStream && !lastRequestStream.isPaused()) {
529
+ lastRequestStream.pause();
530
+ }
531
+ break;
594
532
  }
595
- // Push a fake PartialResultSet without any values but with a resume token
596
- // into the stream to ensure that the checkpoint stream is emptied, and
597
- // then push `null` to end the stream.
598
- flushStream.push({ resumeToken: '_' });
599
- flushStream.push(null);
600
- });
533
+ }
534
+ if ((isStreamEnded || receivedLast) &&
535
+ chunkQueue.length === 0 &&
536
+ !userStream.destroyed &&
537
+ userStream.writable &&
538
+ !userStream.writableEnded) {
539
+ userStream.end();
540
+ }
541
+ };
542
+ const handleResume = () => {
543
+ isDownstreamPaused = false;
544
+ drainQueue();
545
+ if (lastRequestStream &&
546
+ lastRequestStream.isPaused() &&
547
+ !isDownstreamPaused) {
548
+ lastRequestStream.resume();
549
+ }
601
550
  };
602
- const destroyRequestStream = () => {
551
+ userStream.on('paused', () => {
552
+ isDownstreamPaused = true;
553
+ if (lastRequestStream && !lastRequestStream.isPaused()) {
554
+ lastRequestStream.pause();
555
+ }
556
+ });
557
+ userStream.on('resumed', handleResume);
558
+ userStream.on('drain', handleResume);
559
+ const destroyRequestStream = (allowDrain = false) => {
603
560
  if (lastRequestStream) {
604
561
  const streamToClean = lastRequestStream;
605
562
  lastRequestStream = undefined;
606
- streamToClean.removeListener('end', endListener);
563
+ if (dataListener) {
564
+ streamToClean.removeListener('data', dataListener);
565
+ dataListener = undefined;
566
+ }
567
+ if (endListener) {
568
+ streamToClean.removeListener('end', endListener);
569
+ endListener = undefined;
570
+ }
607
571
  if (errorListener) {
608
572
  streamToClean.removeListener('error', errorListener);
573
+ errorListener = undefined;
609
574
  }
610
575
  streamToClean.on('error', () => { });
611
- streamToClean.unpipe(requestsStream);
612
- if (receivedLast) {
613
- // Query completed successfully. Do not cancel the gRPC call; allow it
614
- // to drain remaining trailers/EOF in the background so it is not marked
615
- // CANCELLED by Spanner or Cloud Monitoring.
576
+ if (allowDrain || receivedLast) {
616
577
  streamToClean.resume();
617
578
  }
618
579
  else {
@@ -620,73 +581,92 @@ function partialResultStream(requestFn, options) {
620
581
  }
621
582
  }
622
583
  };
584
+ const flushAndDestroy = (err) => {
585
+ isDestroyed = true;
586
+ destroyRequestStream(false);
587
+ if (!userStream.destroyed && userStream.writable) {
588
+ while (chunkQueue.length > 0) {
589
+ const chunk = chunkQueue.shift();
590
+ userStream.write(chunk);
591
+ }
592
+ }
593
+ setImmediate(() => userStream.destroy(err));
594
+ };
623
595
  const makeRequest = () => {
624
- if ((0, helper_1.isDefined)(lastResumeToken) && lastResumeToken.length > 0) {
625
- partialRSStream._resetPendingValues();
596
+ if (isDestroyed || userStream.destroyed) {
597
+ return;
626
598
  }
627
599
  lastRequestStream = requestFn(lastResumeToken);
628
- lastRequestStream.on('end', endListener);
600
+ if (isDownstreamPaused) {
601
+ lastRequestStream.pause();
602
+ }
603
+ dataListener = (chunk) => {
604
+ if (receivedLast) {
605
+ return;
606
+ }
607
+ chunkQueue.push(chunk);
608
+ if (chunk.last) {
609
+ receivedLast = true;
610
+ destroyRequestStream(true);
611
+ }
612
+ if (_hasResumeToken(chunk)) {
613
+ lastResumeToken = chunk.resumeToken;
614
+ safeToRetry = true;
615
+ withoutCheckpointCount = 0;
616
+ }
617
+ else if (!chunk.last) {
618
+ withoutCheckpointCount++;
619
+ }
620
+ drainQueue();
621
+ };
622
+ endListener = () => {
623
+ if (receivedLast) {
624
+ return;
625
+ }
626
+ destroyRequestStream(true);
627
+ isStreamEnded = true;
628
+ drainQueue();
629
+ };
629
630
  errorListener = (err) => {
630
631
  if (receivedLast) {
631
632
  return;
632
633
  }
633
- destroyRequestStream();
634
+ destroyRequestStream(false);
634
635
  setImmediate(() => retry(err));
635
636
  };
637
+ lastRequestStream.on('data', dataListener);
638
+ lastRequestStream.on('end', endListener);
636
639
  lastRequestStream.on('error', errorListener);
637
- lastRequestStream.pipe(requestsStream, { end: false });
638
640
  };
639
641
  const retry = (err) => {
640
- destroyRequestStream();
642
+ if (isDestroyed || userStream.destroyed) {
643
+ return;
644
+ }
641
645
  const elapsed = Date.now() - startTime;
642
646
  if (elapsed >= timeout) {
643
- // The timeout has reached so this will flush any rows the
644
- // checkpoint stream has queued. After that, we will destroy the
645
- // user's stream with the Deadline exceeded error.
646
- setImmediate(() => batchAndSplitOnTokenStream.flushAndDestroy(new transaction_runner_1.DeadlineError(err)));
647
+ flushAndDestroy(new transaction_runner_1.DeadlineError(err));
647
648
  return;
648
649
  }
649
650
  if (!(err.code &&
650
651
  (retryableCodes.includes(err.code) || (0, transaction_runner_1.isRetryableInternalError)(err))) ||
651
- // If we have received too many chunks without a resume token, it is not
652
- // safe to retry.
653
- withoutCheckpointCount > maxQueued) {
654
- // This is not a retryable error so this will flush any rows the
655
- // checkpoint stream has queued. After that, we will destroy the
656
- // user's stream with the same error.
657
- setImmediate(() => batchAndSplitOnTokenStream.flushAndDestroy(err));
652
+ !safeToRetry) {
653
+ flushAndDestroy(err);
658
654
  return;
659
655
  }
660
- // Delay the retry until all the values that are already in the stream
661
- // pipeline have been handled. This ensures that the checkpoint stream is
662
- // reset to the correct point. Calling .reset() directly here could cause
663
- // any values that are currently in the pipeline and that have not been
664
- // handled yet, to be pushed twice into the entire stream.
665
- setImmediate(() => {
666
- // Empty queued rows on the checkpoint stream (will not emit them to user).
667
- batchAndSplitOnTokenStream.reset();
668
- makeRequest();
669
- });
656
+ while (chunkQueue.length > 0 &&
657
+ !_hasResumeToken(chunkQueue[chunkQueue.length - 1])) {
658
+ chunkQueue.pop();
659
+ }
660
+ withoutCheckpointCount = 0;
661
+ makeRequest();
670
662
  };
671
663
  userStream.once('reading', makeRequest);
672
664
  userStream.once('close', () => {
673
- destroyRequestStream();
674
- requestsStream.destroy();
675
- flushStream.destroy();
676
- batchAndSplitOnTokenStream.destroy();
665
+ isDestroyed = true;
666
+ destroyRequestStream(false);
667
+ chunkQueue.length = 0;
677
668
  });
678
- return (requestsStream
679
- .pipe(batchAndSplitOnTokenStream)
680
- // If we get this error, the checkpoint stream has flushed any rows
681
- // it had queued. We can now destroy the user's stream, as our retry
682
- // attempts are over.
683
- .on('error', (err) => userStream.destroy(err))
684
- .on('checkpoint', (row) => {
685
- lastResumeToken = row.resumeToken;
686
- })
687
- .pipe(userStream)
688
- .on('paused', () => requestsStream.pause())
689
- .on('resumed', () => requestsStream.resume()));
669
+ return userStream;
690
670
  }
691
671
  function _hasResumeToken(chunk) {
692
672
  return (0, helper_1.isDefined)(chunk.resumeToken) && chunk.resumeToken.length > 0;