@google-cloud/spanner 8.11.0 → 8.12.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.
@@ -28,7 +28,6 @@ const extend = require("extend");
28
28
  const google_gax_1 = require("google-gax");
29
29
  const retryRequest = require("retry-request");
30
30
  const stream_1 = require("stream");
31
- const helper_2 = require("../helper");
32
31
  const gaxProtoPath = path.join(path.dirname(require.resolve('google-gax')), '..', 'protos');
33
32
  // TODO: convert this object to an array
34
33
  /**
@@ -173,7 +172,7 @@ class ObjectToStructConverter {
173
172
  for (const prop in obj) {
174
173
  if (Object.prototype.hasOwnProperty.call(obj, prop)) {
175
174
  const value = obj[prop];
176
- if ((0, helper_2.isUndefined)(value)) {
175
+ if ((0, helper_1.isUndefined)(value)) {
177
176
  continue;
178
177
  }
179
178
  convertedObject.fields[prop] = this.encodeValue_(value);
@@ -198,22 +197,22 @@ class ObjectToStructConverter {
198
197
  */
199
198
  encodeValue_(value) {
200
199
  let convertedValue;
201
- if ((0, helper_2.isNull)(value)) {
200
+ if ((0, helper_1.isNull)(value)) {
202
201
  convertedValue = {
203
202
  nullValue: 0,
204
203
  };
205
204
  }
206
- else if ((0, helper_2.isNumber)(value)) {
205
+ else if ((0, helper_1.isNumber)(value)) {
207
206
  convertedValue = {
208
207
  numberValue: value,
209
208
  };
210
209
  }
211
- else if ((0, helper_2.isString)(value)) {
210
+ else if ((0, helper_1.isString)(value)) {
212
211
  convertedValue = {
213
212
  stringValue: value,
214
213
  };
215
214
  }
216
- else if ((0, helper_2.isBoolean)(value)) {
215
+ else if ((0, helper_1.isBoolean)(value)) {
217
216
  convertedValue = {
218
217
  boolValue: value,
219
218
  };
@@ -223,7 +222,7 @@ class ObjectToStructConverter {
223
222
  blobValue: value,
224
223
  };
225
224
  }
226
- else if ((0, helper_2.isObject)(value)) {
225
+ else if ((0, helper_1.isObject)(value)) {
227
226
  if (this.seenObjects.has(value)) {
228
227
  // Circular reference.
229
228
  if (!this.removeCircular) {
@@ -242,7 +241,7 @@ class ObjectToStructConverter {
242
241
  };
243
242
  }
244
243
  }
245
- else if ((0, helper_2.isArray)(value)) {
244
+ else if ((0, helper_1.isArray)(value)) {
246
245
  convertedValue = {
247
246
  listValue: {
248
247
  values: value.map(this.encodeValue_.bind(this)),
@@ -531,7 +530,7 @@ class GrpcService extends common_1.Service {
531
530
  const service = this.getService_(protoOpts);
532
531
  const grpcMetadata = this.grpcMetadata;
533
532
  const grpcOpts = {};
534
- if ((0, helper_2.isNumber)(protoOpts.timeout)) {
533
+ if ((0, helper_1.isNumber)(protoOpts.timeout)) {
535
534
  grpcOpts.deadline = GrpcService.createDeadline_(protoOpts.timeout);
536
535
  }
537
536
  try {
@@ -625,7 +624,7 @@ class GrpcService extends common_1.Service {
625
624
  * @return {error|null}
626
625
  */
627
626
  static decorateError_(err) {
628
- const errorObj = (0, helper_2.isError)(err) ? err : {};
627
+ const errorObj = (0, helper_1.isError)(err) ? err : {};
629
628
  return GrpcService.decorateGrpcResponse_(errorObj, err);
630
629
  }
631
630
  /**
@@ -1801,6 +1801,8 @@ declare class Database extends common.GrpcServiceObject {
1801
1801
  */
1802
1802
  runTransaction(runFn: RunTransactionCallback): void;
1803
1803
  runTransaction(options: RunTransactionOptions, runFn: RunTransactionCallback): void;
1804
+ private _runTransaction;
1805
+ private _executeTransactionRunner;
1804
1806
  runTransactionAsync<T = {}>(runFn: AsyncRunTransactionCallback<T>): Promise<T>;
1805
1807
  runTransactionAsync<T = {}>(options: RunTransactionOptions, runFn: AsyncRunTransactionCallback<T>): Promise<T>;
1806
1808
  /**
@@ -1229,12 +1229,13 @@ class Database extends common.GrpcServiceObject {
1229
1229
  (0, instrument_1.startTrace)('Database.runTransaction', {
1230
1230
  ...this._traceConfig,
1231
1231
  transactionTag: options.requestOptions?.transactionTag,
1232
- }, span => {
1233
- this.sessionFactory_.getSessionForReadWrite((err, session, transaction) => {
1234
- if (err) {
1235
- (0, instrument_1.setSpanError)(span, err);
1236
- }
1237
- if (err && (0, session_pool_1.isSessionNotFoundError)(err)) {
1232
+ }, span => this._runTransaction(span, options, runFn));
1233
+ }
1234
+ _runTransaction(span, options, runFn) {
1235
+ this.sessionFactory_.getSessionForReadWrite((err, session, transaction) => {
1236
+ if (err) {
1237
+ (0, instrument_1.setSpanError)(span, err);
1238
+ if ((0, session_pool_1.isSessionNotFoundError)(err)) {
1238
1239
  span.addEvent('No session available', {
1239
1240
  'session.id': session?.id,
1240
1241
  });
@@ -1242,34 +1243,46 @@ class Database extends common.GrpcServiceObject {
1242
1243
  this.runTransaction(options, runFn);
1243
1244
  return;
1244
1245
  }
1245
- if (err) {
1246
- span.end();
1247
- runFn(err);
1248
- return;
1249
- }
1250
- transaction._observabilityOptions = this._observabilityOptions;
1251
- transaction.requestOptions = Object.assign(transaction.requestOptions || {}, options.requestOptions);
1252
- transaction.setReadWriteTransactionOptions(options);
1253
- const release = () => {
1254
- this.sessionFactory_.release(session);
1255
- span.end();
1256
- };
1257
- const runner = new transaction_runner_1.TransactionRunner(session, transaction, runFn, options);
1258
- runner.run().then(release, err => {
1259
- (0, instrument_1.setSpanError)(span, err);
1260
- if ((0, session_pool_1.isSessionNotFoundError)(err)) {
1261
- span.addEvent('No session available', {
1262
- 'session.id': session?.id,
1263
- });
1264
- release();
1265
- this.runTransaction(options, runFn);
1266
- }
1267
- else {
1268
- setImmediate(runFn, err);
1269
- release();
1270
- }
1246
+ span.end();
1247
+ runFn(err);
1248
+ return;
1249
+ }
1250
+ this._executeTransactionRunner(session, transaction, span, options, runFn);
1251
+ });
1252
+ }
1253
+ _executeTransactionRunner(session, transaction, span, options, runFn) {
1254
+ transaction._observabilityOptions = this._observabilityOptions;
1255
+ transaction.requestOptions = Object.assign(transaction.requestOptions || {}, options.requestOptions);
1256
+ transaction.setReadWriteTransactionOptions(options);
1257
+ const release = () => {
1258
+ this.sessionFactory_.release(session);
1259
+ span.end();
1260
+ };
1261
+ const runner = new transaction_runner_1.TransactionRunner(session, transaction, runFn, options);
1262
+ runner
1263
+ .run()
1264
+ .then(() => {
1265
+ release();
1266
+ return null;
1267
+ }, err => {
1268
+ (0, instrument_1.setSpanError)(span, err);
1269
+ if ((0, session_pool_1.isSessionNotFoundError)(err)) {
1270
+ span.addEvent('No session available', {
1271
+ 'session.id': session.id,
1271
1272
  });
1272
- });
1273
+ release();
1274
+ this.runTransaction(options, runFn);
1275
+ }
1276
+ else {
1277
+ setImmediate(runFn, err);
1278
+ release();
1279
+ }
1280
+ return null;
1281
+ })
1282
+ .catch(err => {
1283
+ (0, instrument_1.setSpanErrorAndException)(span, err);
1284
+ span.end();
1285
+ this.emit('error', err);
1273
1286
  });
1274
1287
  }
1275
1288
  /**
@@ -1531,11 +1544,19 @@ class Database extends common.GrpcServiceObject {
1531
1544
  return;
1532
1545
  }
1533
1546
  span.addEvent('Using Session', { 'session.id': session?.id });
1534
- this._releaseOnEnd(session, transaction, span);
1547
+ const activeTransaction = transaction ?? session?.transaction(this.queryOptions_);
1548
+ if (!activeTransaction) {
1549
+ const error = new Error('No transaction available to commit');
1550
+ (0, instrument_1.setSpanError)(span, error);
1551
+ span.end();
1552
+ cb(error);
1553
+ return;
1554
+ }
1555
+ this._releaseOnEnd(session, activeTransaction, span);
1535
1556
  try {
1536
- transaction.setReadWriteTransactionOptions(options);
1537
- transaction?.setQueuedMutations(mutations.proto());
1538
- return transaction?.commit(options, (err, resp) => {
1557
+ activeTransaction.setReadWriteTransactionOptions(options);
1558
+ activeTransaction.setQueuedMutations(mutations.proto());
1559
+ return activeTransaction.commit(options, (err, resp) => {
1539
1560
  if (err) {
1540
1561
  (0, instrument_1.setSpanError)(span, err);
1541
1562
  }
@@ -15,10 +15,9 @@
15
15
  declare const common: any;
16
16
  import { protos } from '@google-cloud/spanner-api';
17
17
  import instanceAdmin = protos.google;
18
- import { Operation as GaxOperation } from 'google-gax';
18
+ import { Operation as GaxOperation, CallOptions } from 'google-gax';
19
19
  import { LongRunningCallback, RequestCallback, ResourceCallback, NormalCallback } from './common';
20
20
  import { GetInstanceConfigCallback, GetInstanceConfigOptions, GetInstanceConfigResponse, RequestConfig, Spanner } from './index';
21
- import { CallOptions } from 'google-gax';
22
21
  export type IOperation = instanceAdmin.longrunning.IOperation;
23
22
  export type CreateInstanceConfigCallback = LongRunningCallback<InstanceConfig>;
24
23
  export type SetInstanceConfigMetadataCallback = ResourceCallback<GaxOperation, IOperation>;
@@ -16,10 +16,10 @@
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
17
  exports.InstanceConfig = void 0;
18
18
  const common = require('./common-grpc/service-object');
19
+ const google_gax_1 = require("google-gax");
19
20
  const snakeCase = require("lodash.snakecase");
20
21
  const common_1 = require("./common");
21
22
  const promisify_1 = require("@google-cloud/promisify");
22
- const google_gax_1 = require("google-gax");
23
23
  /**
24
24
  * The {@link InstanceConfig} class represents a possible configuration for a
25
25
  * Cloud Spanner instance.
@@ -16,7 +16,7 @@
16
16
  import { GetConfig } from '@google-cloud/common';
17
17
  declare const common: any;
18
18
  import { Database, SessionPoolConstructor } from './database';
19
- import { Spanner, RequestConfig } from '.';
19
+ import { Spanner, RequestConfig, CreateInstanceRequest } from '.';
20
20
  import { RequestCallback, PagedOptions, PagedResponse, LongRunningCallback, NormalCallback, ResourceCallback, PagedOptionsWithFilter } from './common';
21
21
  import { Duplex } from 'stream';
22
22
  import { SessionPoolOptions, SessionPool } from './session-pool';
@@ -26,7 +26,6 @@ import { protos } from '@google-cloud/spanner-api';
26
26
  import databaseAdmin = protos.google;
27
27
  import instanceAdmin = protos.google;
28
28
  import spannerClient = protos.google;
29
- import { CreateInstanceRequest } from './index';
30
29
  import { ObservabilityOptions } from './instrument';
31
30
  export type IBackup = databaseAdmin.spanner.admin.database.v1.IBackup;
32
31
  export type IDatabase = databaseAdmin.spanner.admin.database.v1.IDatabase;
@@ -133,7 +133,7 @@ function _resetTracingEnabledForTest() {
133
133
  */
134
134
  function startTrace(spanNameSuffix, config, cb) {
135
135
  if (!isTracingEnabled(config?.opts)) {
136
- return cb(new noopSpan());
136
+ return cb(NOOP_SPAN);
137
137
  }
138
138
  if (!config) {
139
139
  config = {};
@@ -236,17 +236,17 @@ function getActiveOrNoopSpan() {
236
236
  if (span) {
237
237
  return span;
238
238
  }
239
- return new noopSpan();
239
+ return NOOP_SPAN;
240
240
  }
241
241
  /**
242
- * noopSpan is a pass-through Span that does nothing and shall not
242
+ * NoopSpan is a pass-through Span that does nothing and shall not
243
243
  * be exported, nor added into any context. It serves as a placeholder
244
244
  * to allow calls in sensitive areas like sessionPools to transparently
245
245
  * add attributes to spans without lots of ugly null checks.
246
246
  *
247
247
  * It exists because OpenTelemetry-JS does not seem to export the NoopSpan.
248
248
  */
249
- class noopSpan {
249
+ class NoopSpan {
250
250
  constructor() { }
251
251
  spanContext() {
252
252
  return api_1.INVALID_SPAN_CONTEXT;
@@ -278,4 +278,5 @@ class noopSpan {
278
278
  return this;
279
279
  }
280
280
  }
281
+ const NOOP_SPAN = new NoopSpan();
281
282
  //# sourceMappingURL=instrument.js.map
@@ -100,6 +100,9 @@ export declare class MultiplexedSession extends EventEmitter implements Multiple
100
100
  _maintain(): void;
101
101
  /**
102
102
  * Retrieves a session asynchronously and invokes a callback with the session details.
103
+ * Note: The callback receives `(null, session)`. To prevent unnecessary allocations on
104
+ * read query paths, a `Transaction` is not created here. Callers requiring a read-write
105
+ * transaction should use `SessionFactory.prototype.getSessionForReadWrite`.
103
106
  *
104
107
  * @param {GetSessionCallback} callback - The callback to be invoked once the session is acquired or an error occurs.
105
108
  *
@@ -57,10 +57,11 @@ class MultiplexedSession extends events_1.EventEmitter {
57
57
  this._createSession()
58
58
  .then(() => {
59
59
  this._maintain();
60
+ return null;
60
61
  })
61
62
  // Ignore errors here. If this fails, the next user request will
62
63
  // automatically trigger a retry via `_getSession`.
63
- .catch(err => { });
64
+ .catch(() => { });
64
65
  }
65
66
  /**
66
67
  * Creates a new multiplexed session.
@@ -145,6 +146,9 @@ class MultiplexedSession extends events_1.EventEmitter {
145
146
  }
146
147
  /**
147
148
  * Retrieves a session asynchronously and invokes a callback with the session details.
149
+ * Note: The callback receives `(null, session)`. To prevent unnecessary allocations on
150
+ * read query paths, a `Transaction` is not created here. Callers requiring a read-write
151
+ * transaction should use `SessionFactory.prototype.getSessionForReadWrite`.
148
152
  *
149
153
  * @param {GetSessionCallback} callback - The callback to be invoked once the session is acquired or an error occurs.
150
154
  *
@@ -152,7 +156,29 @@ class MultiplexedSession extends events_1.EventEmitter {
152
156
  *
153
157
  */
154
158
  getSession(callback) {
155
- this._getSession().then(session => callback(null, session, session.transaction(session.parent.queryOptions_)), callback);
159
+ if (this._multiplexedSession !== null) {
160
+ const session = this._multiplexedSession;
161
+ const span = (0, instrument_1.getActiveOrNoopSpan)();
162
+ span.addEvent('Cache hit: has usable multiplexed session');
163
+ // Use process.nextTick to guarantee asynchronous callback execution ("never release Zalgo").
164
+ // This avoids microtask and Promise allocation overhead while preventing race conditions
165
+ // where callers (such as Database.prototype.runStream) need to return their stream and
166
+ // register lifecycle listeners before the session callback executes.
167
+ process.nextTick(() => {
168
+ callback(null, session);
169
+ });
170
+ return;
171
+ }
172
+ this._getSession()
173
+ .then(session => {
174
+ callback(null, session);
175
+ return null;
176
+ }, callback)
177
+ .catch(err => {
178
+ process.nextTick(() => {
179
+ throw err;
180
+ });
181
+ });
156
182
  }
157
183
  /**
158
184
  * Attempts to get a session, waiting for it to become available if necessary.
@@ -18,9 +18,6 @@ Object.defineProperty(exports, "__esModule", { value: true });
18
18
  exports.PartialResultStream = void 0;
19
19
  exports.partialResultStream = partialResultStream;
20
20
  const service_1 = require("./common-grpc/service");
21
- const checkpointStream = require("checkpoint-stream");
22
- const eventsIntercept = require("events-intercept");
23
- const mergeStream = require("merge-stream");
24
21
  const stream_1 = require("stream");
25
22
  const streamEvents = require("stream-events");
26
23
  const google_gax_1 = require("google-gax");
@@ -28,10 +25,24 @@ const transaction_runner_1 = require("./transaction-runner");
28
25
  const codec_1 = require("./codec");
29
26
  const spanner_api_1 = require("@google-cloud/spanner-api");
30
27
  var google = spanner_api_1.protos.google;
31
- const stream = require("stream");
32
28
  const helper_1 = require("./helper");
33
29
  const originalDecode = codec_1.codec.decode;
34
30
  const originalConvertFieldsToJson = codec_1.codec.convertFieldsToJson;
31
+ /**
32
+ * Row implementation extending Array to provide a shared, non-enumerable
33
+ * toJSON method without per-row closures or Object.setPrototypeOf overhead.
34
+ */
35
+ class RowImpl extends Array {
36
+ toJSON(options) {
37
+ return codec_1.codec.convertFieldsToJson(this, options);
38
+ }
39
+ }
40
+ Object.defineProperty(RowImpl.prototype, 'constructor', {
41
+ value: Array,
42
+ writable: true,
43
+ configurable: true,
44
+ enumerable: false,
45
+ });
35
46
  /**
36
47
  * The PartialResultStream transforms partial result set objects into Row
37
48
  * objects.
@@ -116,6 +127,11 @@ class PartialResultStream extends stream_1.Transform {
116
127
  }
117
128
  if (chunk.last) {
118
129
  this.push(null);
130
+ // Calling next() notifies Node's stream machinery that processing of this
131
+ // chunk is complete on the Writable side of this Transform stream.
132
+ // This is a local, synchronous callback to Node's internal buffer; it does
133
+ // not block the event loop or wait for upstream network I/O or gRPC trailers.
134
+ next();
119
135
  return;
120
136
  }
121
137
  if (res) {
@@ -275,7 +291,7 @@ class PartialResultStream extends stream_1.Transform {
275
291
  */
276
292
  _createRow(values) {
277
293
  const len = values.length;
278
- const fields = new Array(len);
294
+ const fields = new RowImpl(len);
279
295
  const decoders = this._decoders;
280
296
  const classFields = this._fields;
281
297
  for (let i = 0; i < len; i++) {
@@ -284,11 +300,6 @@ class PartialResultStream extends stream_1.Transform {
284
300
  value: decoders[i](values[i]),
285
301
  };
286
302
  }
287
- Object.defineProperty(fields, 'toJSON', {
288
- value: (options) => {
289
- return codec_1.codec.convertFieldsToJson(fields, options);
290
- },
291
- });
292
303
  return fields;
293
304
  }
294
305
  /**
@@ -344,6 +355,83 @@ class PartialResultStream extends stream_1.Transform {
344
355
  }
345
356
  }
346
357
  exports.PartialResultStream = PartialResultStream;
358
+ /**
359
+ * A custom Transform stream that buffers PartialResultSet chunks and flushes them
360
+ * asynchronously to prevent blocking the event loop.
361
+ *
362
+ * It holds chunks in a queue until a "checkpoint" is reached (as determined by
363
+ * `isCheckpointFn`) or until the queue exceeds `maxQueued` items.
364
+ *
365
+ * @private
366
+ */
367
+ class CheckpointStream extends stream_1.Transform {
368
+ queue = [];
369
+ maxQueued;
370
+ isCheckpointFn;
371
+ constructor(options) {
372
+ super({ objectMode: true });
373
+ this.maxQueued = options.maxQueued ?? 10;
374
+ this.isCheckpointFn = options.isCheckpointFn;
375
+ }
376
+ /**
377
+ * Buffers chunks and flushes queue synchronously on checkpoints or when max limit is reached.
378
+ *
379
+ * @param {google.spanner.v1.PartialResultSet} chunk The chunk to transform.
380
+ * @param {string} enc Encoding (unused).
381
+ * @param {Function} callback Callback to signal completion of transformation.
382
+ */
383
+ _transform(chunk, enc, callback) {
384
+ this.queue.push(chunk);
385
+ const isCheckpoint = this.isCheckpointFn(chunk);
386
+ let shouldFlush = false;
387
+ if (isCheckpoint) {
388
+ this.emit('checkpoint', chunk);
389
+ shouldFlush = true;
390
+ }
391
+ else if (this.queue.length > this.maxQueued) {
392
+ shouldFlush = true;
393
+ }
394
+ if (!shouldFlush) {
395
+ return callback();
396
+ }
397
+ this._flushQueue();
398
+ callback();
399
+ }
400
+ /**
401
+ * Flushes queued chunks synchronously to prevent state races on retry/reset.
402
+ *
403
+ * @private
404
+ */
405
+ _flushQueue() {
406
+ while (this.queue.length > 0 && !this.destroyed) {
407
+ this.push(this.queue.shift());
408
+ }
409
+ }
410
+ /**
411
+ * Flushes remaining queued chunks before destroying the stream with the provided error.
412
+ *
413
+ * @param {Error} err The error to destroy the stream with.
414
+ */
415
+ flushAndDestroy(err) {
416
+ this._flushQueue();
417
+ this.destroy(err);
418
+ }
419
+ /**
420
+ * Clears the queue without flushing, useful when retrying and discarding partial data.
421
+ */
422
+ reset() {
423
+ this.queue = [];
424
+ }
425
+ /**
426
+ * Flushes all remaining queued chunks when the stream ends.
427
+ *
428
+ * @param {Function} callback Callback to call when flushing is complete.
429
+ */
430
+ _flush(callback) {
431
+ this._flushQueue();
432
+ callback();
433
+ }
434
+ }
347
435
  /**
348
436
  * Rows returned from queries may be chunked, requiring them to be stitched
349
437
  * together. This function returns a stream that will properly assemble these
@@ -365,26 +453,33 @@ function partialResultStream(requestFn, options) {
365
453
  const maxQueued = 10;
366
454
  let lastResumeToken;
367
455
  let lastRequestStream;
456
+ let errorListener;
368
457
  const startTime = Date.now();
369
458
  const timeout = options?.gaxOptions?.timeout ?? Infinity;
370
- // mergeStream allows multiple streams to be connected into one. This is good;
459
+ // requestsStream allows multiple streams to be connected into one. This is good;
371
460
  // if we need to retry a request and pipe more data to the user's stream.
372
461
  // We also add an additional stream that can be used to flush any remaining
373
462
  // items in the checkpoint stream that have been received, and that did not
374
463
  // contain a resume token.
375
- const requestsStream = mergeStream();
376
- const flushStream = new stream.PassThrough({ objectMode: true });
377
- requestsStream.add(flushStream);
464
+ const requestsStream = new stream_1.PassThrough({ objectMode: true });
465
+ const flushStream = new stream_1.PassThrough({ objectMode: true });
466
+ flushStream.pipe(requestsStream);
378
467
  const partialRSStream = new PartialResultStream(options);
379
468
  const userStream = streamEvents(partialRSStream);
380
469
  // We keep track of the number of PartialResultSets that did not include a
381
470
  // resume token, as that is an indication whether it is safe to retry the
382
471
  // stream halfway.
383
472
  let withoutCheckpointCount = 0;
384
- const batchAndSplitOnTokenStream = checkpointStream.obj({
473
+ let receivedLast = false;
474
+ const batchAndSplitOnTokenStream = new CheckpointStream({
385
475
  maxQueued,
386
476
  isCheckpointFn: (chunk) => {
387
- const withCheckpoint = _hasResumeToken(chunk);
477
+ if (chunk.last) {
478
+ receivedLast = true;
479
+ destroyRequestStream();
480
+ requestsStream.end();
481
+ }
482
+ const withCheckpoint = _hasResumeToken(chunk) || Boolean(chunk.last);
388
483
  if (withCheckpoint) {
389
484
  withoutCheckpointCount = 0;
390
485
  }
@@ -397,30 +492,65 @@ function partialResultStream(requestFn, options) {
397
492
  // This listener ensures that the last request that executed successfully
398
493
  // after one or more retries will end the requestsStream.
399
494
  const endListener = () => {
495
+ if (receivedLast) {
496
+ return;
497
+ }
400
498
  setImmediate(() => {
499
+ if (receivedLast) {
500
+ return;
501
+ }
401
502
  // Push a fake PartialResultSet without any values but with a resume token
402
503
  // into the stream to ensure that the checkpoint stream is emptied, and
403
504
  // then push `null` to end the stream.
404
505
  flushStream.push({ resumeToken: '_' });
405
506
  flushStream.push(null);
406
- requestsStream.end();
407
507
  });
408
508
  };
509
+ const destroyRequestStream = () => {
510
+ if (lastRequestStream) {
511
+ const streamToClean = lastRequestStream;
512
+ lastRequestStream = undefined;
513
+ streamToClean.removeListener('end', endListener);
514
+ if (errorListener) {
515
+ streamToClean.removeListener('error', errorListener);
516
+ }
517
+ streamToClean.on('error', () => { });
518
+ streamToClean.unpipe(requestsStream);
519
+ if (receivedLast) {
520
+ // Query completed successfully. Do not cancel the gRPC call; allow it
521
+ // to drain remaining trailers/EOF in the background so it is not marked
522
+ // CANCELLED by Spanner or Cloud Monitoring.
523
+ streamToClean.resume();
524
+ }
525
+ else {
526
+ streamToClean.destroy();
527
+ }
528
+ }
529
+ };
409
530
  const makeRequest = () => {
410
531
  if ((0, helper_1.isDefined)(lastResumeToken) && lastResumeToken.length > 0) {
411
532
  partialRSStream._resetPendingValues();
412
533
  }
413
534
  lastRequestStream = requestFn(lastResumeToken);
414
535
  lastRequestStream.on('end', endListener);
415
- requestsStream.add(lastRequestStream);
536
+ errorListener = (err) => {
537
+ if (receivedLast) {
538
+ return;
539
+ }
540
+ destroyRequestStream();
541
+ setImmediate(() => retry(err));
542
+ };
543
+ lastRequestStream.on('error', errorListener);
544
+ lastRequestStream.pipe(requestsStream, { end: false });
416
545
  };
417
546
  const retry = (err) => {
547
+ destroyRequestStream();
418
548
  const elapsed = Date.now() - startTime;
419
549
  if (elapsed >= timeout) {
420
550
  // The timeout has reached so this will flush any rows the
421
551
  // checkpoint stream has queued. After that, we will destroy the
422
552
  // user's stream with the Deadline exceeded error.
423
- setImmediate(() => batchAndSplitOnTokenStream.destroy(new transaction_runner_1.DeadlineError(err)));
553
+ setImmediate(() => batchAndSplitOnTokenStream.flushAndDestroy(new transaction_runner_1.DeadlineError(err)));
424
554
  return;
425
555
  }
426
556
  if (!(err.code &&
@@ -431,13 +561,9 @@ function partialResultStream(requestFn, options) {
431
561
  // This is not a retryable error so this will flush any rows the
432
562
  // checkpoint stream has queued. After that, we will destroy the
433
563
  // user's stream with the same error.
434
- setImmediate(() => batchAndSplitOnTokenStream.destroy(err));
564
+ setImmediate(() => batchAndSplitOnTokenStream.flushAndDestroy(err));
435
565
  return;
436
566
  }
437
- if (lastRequestStream) {
438
- lastRequestStream.removeListener('end', endListener);
439
- lastRequestStream.destroy();
440
- }
441
567
  // Delay the retry until all the values that are already in the stream
442
568
  // pipeline have been handled. This ensures that the checkpoint stream is
443
569
  // reset to the correct point. Calling .reset() directly here could cause
@@ -450,13 +576,12 @@ function partialResultStream(requestFn, options) {
450
576
  });
451
577
  };
452
578
  userStream.once('reading', makeRequest);
453
- eventsIntercept.patch(requestsStream);
454
- // need types for events-intercept
455
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
456
- requestsStream.intercept('error', err =>
457
- // Retry __after__ all pending data has been processed to ensure that the
458
- // checkpoint stream is reset at the correct position.
459
- setImmediate(() => retry(err)));
579
+ userStream.once('close', () => {
580
+ destroyRequestStream();
581
+ requestsStream.destroy();
582
+ flushStream.destroy();
583
+ batchAndSplitOnTokenStream.destroy();
584
+ });
460
585
  return (requestsStream
461
586
  .pipe(batchAndSplitOnTokenStream)
462
587
  // If we get this error, the checkpoint stream has flushed any rows
@@ -21,8 +21,10 @@ declare const common: any;
21
21
  /**
22
22
  * @callback GetSessionCallback
23
23
  * @param {?Error} error Request error, if any.
24
- * @param {Session} session The read-write session.
25
- * @param {Transaction} transaction The transaction object.
24
+ * @param {Session} [session] The session object.
25
+ * @param {Transaction} [transaction] The transaction object, if applicable.
26
+ * Omitted for read-only multiplexed session acquisitions to prevent throwaway
27
+ * allocations. Provided by getSessionForReadWrite or when using regular session pools.
26
28
  */
27
29
  export interface GetSessionCallback {
28
30
  (err: Error | null, session?: Session | null, transaction?: Transaction | null): void;
@@ -108,9 +108,20 @@ class SessionFactory extends common.GrpcServiceObject {
108
108
  * @param {GetSessionCallback} callback The callback function.
109
109
  */
110
110
  getSessionForReadWrite(callback) {
111
- this.isMultiplexedRW
112
- ? this.getSession(callback)
113
- : this.pool_.getSession(callback);
111
+ if (this.isMultiplexedRW) {
112
+ this.getSession((error, session, transaction) => {
113
+ if (error || !session) {
114
+ callback(error ?? new Error('No session found'), null);
115
+ return;
116
+ }
117
+ const database = session.parent;
118
+ const activeTransaction = transaction ?? session.transaction(database.queryOptions_);
119
+ callback(null, session, activeTransaction);
120
+ });
121
+ }
122
+ else {
123
+ this.pool_.getSession(callback);
124
+ }
114
125
  }
115
126
  /**
116
127
  * Returns the regular session pool object.
@@ -23,7 +23,7 @@ import { Json, JSONOptions, Type, Value } from './codec';
23
23
  import { PartialResultStream, ResumeToken, Row } from './partial-result-stream';
24
24
  import { Session } from './session';
25
25
  import { Key } from './table';
26
- import { Span } from './instrument';
26
+ import { Span, ObservabilityOptions, traceConfig } from './instrument';
27
27
  import { NormalCallback } from './common';
28
28
  import { protos } from '@google-cloud/spanner-api';
29
29
  import spannerClient = protos.google;
@@ -31,7 +31,6 @@ import google = protos.google;
31
31
  import IQueryOptions = google.spanner.v1.ExecuteSqlRequest.IQueryOptions;
32
32
  import IRequestOptions = google.spanner.v1.IRequestOptions;
33
33
  import { Spanner } from '.';
34
- import { ObservabilityOptions, traceConfig } from './instrument';
35
34
  import { RunTransactionOptions } from './transaction-runner';
36
35
  export type Rows = Array<Row | Json>;
37
36
  export interface TimestampBounds {
@@ -47,6 +46,13 @@ export interface BatchWriteOptions {
47
46
  gaxOptions?: CallOptions;
48
47
  excludeTxnFromChangeStreams?: boolean;
49
48
  }
49
+ export interface QueueSendOptions {
50
+ payload?: Value;
51
+ deliverTime?: Date | spannerClient.protobuf.ITimestamp;
52
+ }
53
+ export interface QueueAckOptions {
54
+ ignoreNotFound?: boolean;
55
+ }
50
56
  export interface RequestOptions {
51
57
  json?: boolean;
52
58
  jsonOptions?: JSONOptions;
@@ -1377,6 +1383,22 @@ export declare class Transaction extends Dml {
1377
1383
  * ```
1378
1384
  */
1379
1385
  insert(table: string, rows: object | object[]): void;
1386
+ /**
1387
+ * Queue a send mutation.
1388
+ *
1389
+ * @param {string} queue The name of the queue.
1390
+ * @param {Key} key The key of the message to send.
1391
+ * @param {QueueSendOptions} [options] Options for the send mutation.
1392
+ */
1393
+ queueSend(queue: string, key: Key, options?: QueueSendOptions): void;
1394
+ /**
1395
+ * Queue an ack mutation.
1396
+ *
1397
+ * @param {string} queue The name of the queue.
1398
+ * @param {Key} key The key of the message to ack.
1399
+ * @param {QueueAckOptions} [options] Options for the ack mutation.
1400
+ */
1401
+ queueAck(queue: string, key: Key, options?: QueueAckOptions): void;
1380
1402
  /**
1381
1403
  * Replace rows of data within a table.
1382
1404
  *
@@ -1613,6 +1635,22 @@ export declare class MutationSet {
1613
1635
  * @param {object|object[]} rows. A single row object or an array of row objects to insert.
1614
1636
  */
1615
1637
  insert(table: string, rows: object | object[]): void;
1638
+ /**
1639
+ * Queue a send mutation.
1640
+ *
1641
+ * @param {string} queue The name of the queue.
1642
+ * @param {Key} key The key of the message to send.
1643
+ * @param {QueueSendOptions} [options] Options for the send mutation.
1644
+ */
1645
+ queueSend(queue: string, key: Key, options?: QueueSendOptions): void;
1646
+ /**
1647
+ * Queue an ack mutation.
1648
+ *
1649
+ * @param {string} queue The name of the queue.
1650
+ * @param {Key} key The key of the message to ack.
1651
+ * @param {QueueAckOptions} [options] Options for the ack mutation.
1652
+ */
1653
+ queueAck(queue: string, key: Key, options?: QueueAckOptions): void;
1616
1654
  /**
1617
1655
  * Adds an update operation to the mutation set.
1618
1656
  * @param {string} table. The name of the table to update.
@@ -1682,6 +1720,8 @@ export declare class MutationGroup {
1682
1720
  private _proto;
1683
1721
  constructor();
1684
1722
  insert(table: string, rows: object | object[]): void;
1723
+ queueSend(queue: string, key: Key, options?: QueueSendOptions): void;
1724
+ queueAck(queue: string, key: Key, options?: QueueAckOptions): void;
1685
1725
  update(table: string, rows: object | object[]): void;
1686
1726
  upsert(table: string, rows: object | object[]): void;
1687
1727
  replace(table: string, rows: object | object[]): void;
@@ -24,13 +24,13 @@ const google_gax_1 = require("google-gax");
24
24
  const stream_1 = require("stream");
25
25
  const codec_1 = require("./codec");
26
26
  const partial_result_stream_1 = require("./partial-result-stream");
27
+ const instrument_1 = require("./instrument");
27
28
  const common_1 = require("./common");
28
29
  const spanner_api_1 = require("@google-cloud/spanner-api");
29
30
  var spannerClient = spanner_api_1.protos.google;
30
31
  var google = spanner_api_1.protos.google;
31
32
  var IsolationLevel = google.spanner.v1.TransactionOptions.IsolationLevel;
32
33
  var ReadLockMode = google.spanner.v1.TransactionOptions.ReadWrite.ReadLockMode;
33
- const instrument_1 = require("./instrument");
34
34
  const request_id_header_1 = require("./request_id_header");
35
35
  const RETRY_INFO_TYPE = 'type.googleapis.com/google.rpc.retryinfo';
36
36
  const RETRY_INFO_BIN = 'google.rpc.retryinfo-bin';
@@ -1807,6 +1807,26 @@ class Transaction extends Dml {
1807
1807
  insert(table, rows) {
1808
1808
  this._mutate('insert', table, rows);
1809
1809
  }
1810
+ /**
1811
+ * Queue a send mutation.
1812
+ *
1813
+ * @param {string} queue The name of the queue.
1814
+ * @param {Key} key The key of the message to send.
1815
+ * @param {QueueSendOptions} [options] Options for the send mutation.
1816
+ */
1817
+ queueSend(queue, key, options) {
1818
+ this._queuedMutations.push(buildSendMutation(queue, key, options));
1819
+ }
1820
+ /**
1821
+ * Queue an ack mutation.
1822
+ *
1823
+ * @param {string} queue The name of the queue.
1824
+ * @param {Key} key The key of the message to ack.
1825
+ * @param {QueueAckOptions} [options] Options for the ack mutation.
1826
+ */
1827
+ queueAck(queue, key, options) {
1828
+ this._queuedMutations.push(buildAckMutation(queue, key, options));
1829
+ }
1810
1830
  /**
1811
1831
  * Replace rows of data within a table.
1812
1832
  *
@@ -2098,6 +2118,58 @@ function buildDeleteMutation(table, keys) {
2098
2118
  };
2099
2119
  return mutation;
2100
2120
  }
2121
+ /**
2122
+ * Builds a send mutation.
2123
+ *
2124
+ * @param {string} queue - The name of the queue.
2125
+ * @param {Key} key - The key for the message.
2126
+ * @param {QueueSendOptions} [options] - Options for sending the message.
2127
+ * @returns {spannerClient.spanner.v1.Mutation} - The formatted send mutation.
2128
+ */
2129
+ function buildSendMutation(queue, key, options) {
2130
+ const send = {
2131
+ queue,
2132
+ key: codec_1.codec.convertToListValue((0, helper_1.toArray)(key)),
2133
+ };
2134
+ if (options) {
2135
+ if (options.payload !== undefined) {
2136
+ send.payload = codec_1.codec.encode(options.payload);
2137
+ }
2138
+ if (options.deliverTime) {
2139
+ if (options.deliverTime instanceof Date) {
2140
+ send.deliverTime = codec_1.codec.convertMsToProtoTimestamp(options.deliverTime.getTime());
2141
+ }
2142
+ else {
2143
+ send.deliverTime = options.deliverTime;
2144
+ }
2145
+ }
2146
+ }
2147
+ const mutation = {
2148
+ send,
2149
+ };
2150
+ return mutation;
2151
+ }
2152
+ /**
2153
+ * Builds an ack mutation.
2154
+ *
2155
+ * @param {string} queue - The name of the queue.
2156
+ * @param {Key} key - The key for the message.
2157
+ * @param {QueueAckOptions} [options] - Options for acking the message.
2158
+ * @returns {spannerClient.spanner.v1.Mutation} - The formatted ack mutation.
2159
+ */
2160
+ function buildAckMutation(queue, key, options) {
2161
+ const ack = {
2162
+ queue,
2163
+ key: codec_1.codec.convertToListValue((0, helper_1.toArray)(key)),
2164
+ };
2165
+ if (options && options.ignoreNotFound !== undefined) {
2166
+ ack.ignoreNotFound = options.ignoreNotFound;
2167
+ }
2168
+ const mutation = {
2169
+ ack,
2170
+ };
2171
+ return mutation;
2172
+ }
2101
2173
  /**
2102
2174
  * MutationSet represent a set of changes to be applied atomically to a Cloud Spanner
2103
2175
  * database with a {@link Transaction}.
@@ -2150,6 +2222,26 @@ class MutationSet {
2150
2222
  insert(table, rows) {
2151
2223
  this._queuedMutations.push(buildMutation('insert', table, rows));
2152
2224
  }
2225
+ /**
2226
+ * Queue a send mutation.
2227
+ *
2228
+ * @param {string} queue The name of the queue.
2229
+ * @param {Key} key The key of the message to send.
2230
+ * @param {QueueSendOptions} [options] Options for the send mutation.
2231
+ */
2232
+ queueSend(queue, key, options) {
2233
+ this._queuedMutations.push(buildSendMutation(queue, key, options));
2234
+ }
2235
+ /**
2236
+ * Queue an ack mutation.
2237
+ *
2238
+ * @param {string} queue The name of the queue.
2239
+ * @param {Key} key The key of the message to ack.
2240
+ * @param {QueueAckOptions} [options] Options for the ack mutation.
2241
+ */
2242
+ queueAck(queue, key, options) {
2243
+ this._queuedMutations.push(buildAckMutation(queue, key, options));
2244
+ }
2153
2245
  /**
2154
2246
  * Adds an update operation to the mutation set.
2155
2247
  * @param {string} table. The name of the table to update.
@@ -2235,6 +2327,12 @@ class MutationGroup {
2235
2327
  insert(table, rows) {
2236
2328
  this._proto.mutations.push(buildMutation('insert', table, rows));
2237
2329
  }
2330
+ queueSend(queue, key, options) {
2331
+ this._proto.mutations.push(buildSendMutation(queue, key, options));
2332
+ }
2333
+ queueAck(queue, key, options) {
2334
+ this._proto.mutations.push(buildAckMutation(queue, key, options));
2335
+ }
2238
2336
  update(table, rows) {
2239
2337
  this._proto.mutations.push(buildMutation('update', table, rows));
2240
2338
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@google-cloud/spanner",
3
3
  "description": "Cloud Spanner Client Library for Node.js",
4
- "version": "8.11.0",
4
+ "version": "8.12.0",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Google Inc.",
7
7
  "engines": {
@@ -71,19 +71,15 @@
71
71
  "@types/big.js": "^6.2.2",
72
72
  "@types/stack-trace": "^0.0.33",
73
73
  "big.js": "^7.0.0",
74
- "checkpoint-stream": "^0.1.2",
75
74
  "duplexify": "^4.1.3",
76
- "events-intercept": "^2.0.0",
77
75
  "extend": "^3.0.2",
78
76
  "google-auth-library": "^10.0.0-rc.1",
79
77
  "google-gax": "5.0.6",
80
78
  "grpc-gcp": "^1.0.1",
81
79
  "lodash.snakecase": "^4.1.1",
82
- "merge-stream": "^2.0.0",
83
80
  "p-queue": "^6.0.2",
84
81
  "protobufjs": "^7.4.0",
85
82
  "retry-request": "^8.0.0",
86
- "split-array-stream": "^2.0.0",
87
83
  "stack-trace": "0.0.10",
88
84
  "stream-events": "^1.0.5",
89
85
  "teeny-request": "^10.0.0",
@@ -98,7 +94,6 @@
98
94
  "@types/extend": "^3.0.4",
99
95
  "@types/is": "^0.0.25",
100
96
  "@types/lodash.snakecase": "^4.1.9",
101
- "@types/merge-stream": "^2.0.0",
102
97
  "@types/mocha": "^10.0.10",
103
98
  "@types/mv": "^2.1.4",
104
99
  "@types/ncp": "^2.0.8",