@google-cloud/spanner 8.10.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.
Files changed (71) hide show
  1. package/build/protos/status.json +243 -0
  2. package/build/src/backup.d.ts +2 -1
  3. package/build/src/batch-transaction.d.ts +2 -1
  4. package/build/src/codec.d.ts +2 -1
  5. package/build/src/codec.js +21 -20
  6. package/build/src/common-grpc/service.js +9 -10
  7. package/build/src/common.d.ts +3 -2
  8. package/build/src/database.d.ts +7 -2
  9. package/build/src/database.js +58 -37
  10. package/build/src/index.d.ts +3 -2
  11. package/build/src/index.js +7 -16
  12. package/build/src/instance-config.d.ts +3 -3
  13. package/build/src/instance-config.js +1 -1
  14. package/build/src/instance.d.ts +5 -5
  15. package/build/src/instance.js +3 -2
  16. package/build/src/instrument.js +5 -4
  17. package/build/src/multiplexed-session.d.ts +3 -0
  18. package/build/src/multiplexed-session.js +28 -2
  19. package/build/src/partial-result-stream.d.ts +2 -1
  20. package/build/src/partial-result-stream.js +161 -35
  21. package/build/src/protos.d.ts +21 -0
  22. package/build/src/protos.js +52 -0
  23. package/build/src/session-factory.d.ts +4 -2
  24. package/build/src/session-factory.js +14 -3
  25. package/build/src/session.d.ts +2 -1
  26. package/build/src/table.d.ts +3 -2
  27. package/build/src/table.js +4 -3
  28. package/build/src/transaction-runner.d.ts +2 -1
  29. package/build/src/transaction-runner.js +6 -8
  30. package/build/src/transaction.d.ts +45 -4
  31. package/build/src/transaction.js +105 -6
  32. package/build/src/v1/index.d.ts +1 -4
  33. package/build/src/v1/index.js +5 -8
  34. package/package.json +4 -9
  35. package/build/protos/google/spanner/admin/database/v1/backup.proto +0 -773
  36. package/build/protos/google/spanner/admin/database/v1/backup_schedule.proto +0 -230
  37. package/build/protos/google/spanner/admin/database/v1/common.proto +0 -132
  38. package/build/protos/google/spanner/admin/database/v1/spanner_database_admin.proto +0 -1314
  39. package/build/protos/google/spanner/admin/instance/v1/common.proto +0 -64
  40. package/build/protos/google/spanner/admin/instance/v1/spanner_instance_admin.proto +0 -2184
  41. package/build/protos/google/spanner/executor/v1/cloud_executor.proto +0 -1604
  42. package/build/protos/google/spanner/v1/change_stream.proto +0 -451
  43. package/build/protos/google/spanner/v1/commit_response.proto +0 -80
  44. package/build/protos/google/spanner/v1/keys.proto +0 -163
  45. package/build/protos/google/spanner/v1/location.proto +0 -388
  46. package/build/protos/google/spanner/v1/mutation.proto +0 -156
  47. package/build/protos/google/spanner/v1/query_plan.proto +0 -156
  48. package/build/protos/google/spanner/v1/result_set.proto +0 -260
  49. package/build/protos/google/spanner/v1/spanner.proto +0 -1472
  50. package/build/protos/google/spanner/v1/transaction.proto +0 -329
  51. package/build/protos/google/spanner/v1/type.proto +0 -214
  52. package/build/protos/protos.d.ts +0 -44031
  53. package/build/protos/protos.js +0 -122630
  54. package/build/protos/protos.json +0 -11631
  55. package/build/src/v1/database_admin_client.d.ts +0 -2367
  56. package/build/src/v1/database_admin_client.js +0 -2914
  57. package/build/src/v1/database_admin_client_config.json +0 -169
  58. package/build/src/v1/database_admin_proto_list.json +0 -6
  59. package/build/src/v1/gapic_metadata.json +0 -27
  60. package/build/src/v1/instance_admin_client.d.ts +0 -2106
  61. package/build/src/v1/instance_admin_client.js +0 -2387
  62. package/build/src/v1/instance_admin_client_config.json +0 -129
  63. package/build/src/v1/instance_admin_proto_list.json +0 -4
  64. package/build/src/v1/spanner_client.d.ts +0 -1319
  65. package/build/src/v1/spanner_client.js +0 -1446
  66. package/build/src/v1/spanner_client_config.json +0 -123
  67. package/build/src/v1/spanner_executor_proxy_client.d.ts +0 -419
  68. package/build/src/v1/spanner_executor_proxy_client.js +0 -728
  69. package/build/src/v1/spanner_executor_proxy_client_config.json +0 -30
  70. package/build/src/v1/spanner_executor_proxy_proto_list.json +0 -15
  71. package/build/src/v1/spanner_proto_list.json +0 -12
@@ -44,9 +44,11 @@ Object.defineProperty(exports, "Instance", { enumerable: true, get: function ()
44
44
  const instance_config_1 = require("./instance-config");
45
45
  Object.defineProperty(exports, "InstanceConfig", { enumerable: true, get: function () { return instance_config_1.InstanceConfig; } });
46
46
  const google_gax_1 = require("google-gax");
47
- const protos_1 = require("../protos/protos");
48
- var IsolationLevel = protos_1.google.spanner.v1.TransactionOptions.IsolationLevel;
49
- var ReadLockMode = protos_1.google.spanner.v1.TransactionOptions.ReadWrite.ReadLockMode;
47
+ const spanner_api_1 = require("@google-cloud/spanner-api");
48
+ Object.defineProperty(exports, "protos", { enumerable: true, get: function () { return spanner_api_1.protos; } });
49
+ var google = spanner_api_1.protos.google;
50
+ var IsolationLevel = google.spanner.v1.TransactionOptions.IsolationLevel;
51
+ var ReadLockMode = google.spanner.v1.TransactionOptions.ReadWrite.ReadLockMode;
50
52
  const common_1 = require("./common");
51
53
  const session_1 = require("./session");
52
54
  Object.defineProperty(exports, "Session", { enumerable: true, get: function () { return session_1.Session; } });
@@ -174,8 +176,8 @@ class Spanner extends service_1.GrpcService {
174
176
  * @type {string}
175
177
  */
176
178
  static COMMIT_TIMESTAMP = 'spanner.commit_timestamp()';
177
- static POSTGRESQL = protos_1.google.spanner.admin.database.v1.DatabaseDialect.POSTGRESQL;
178
- static GOOGLE_STANDARD_SQL = protos_1.google.spanner.admin.database.v1.DatabaseDialect.GOOGLE_STANDARD_SQL;
179
+ static POSTGRESQL = google.spanner.admin.database.v1.DatabaseDialect.POSTGRESQL;
180
+ static GOOGLE_STANDARD_SQL = google.spanner.admin.database.v1.DatabaseDialect.GOOGLE_STANDARD_SQL;
179
181
  /**
180
182
  * Returns whether AFE (Application Frontend Extension) server timing is enabled.
181
183
  *
@@ -1369,16 +1371,5 @@ process.on('beforeExit', () => {
1369
1371
  'getDatabaseAdminClient',
1370
1372
  ],
1371
1373
  });
1372
- /**
1373
- * @type {object}
1374
- * @property {constructor} DatabaseAdminClient
1375
- * Reference to {@link v1.DatabaseAdminClient}
1376
- * @property {constructor} InstanceAdminClient
1377
- * Reference to {@link v1.InstanceAdminClient}
1378
- * @property {constructor} SpannerClient
1379
- * Reference to {@link v1.SpannerClient}
1380
- */
1381
- const protos = require("../protos/protos");
1382
- exports.protos = protos;
1383
1374
  exports.default = { Spanner };
1384
1375
  //# sourceMappingURL=index.js.map
@@ -13,11 +13,11 @@
13
13
  * limitations under the License.
14
14
  */
15
15
  declare const common: any;
16
- import { google as instanceAdmin } from '../protos/protos';
17
- import { Operation as GaxOperation } from 'google-gax';
16
+ import { protos } from '@google-cloud/spanner-api';
17
+ import instanceAdmin = protos.google;
18
+ import { Operation as GaxOperation, CallOptions } from 'google-gax';
18
19
  import { LongRunningCallback, RequestCallback, ResourceCallback, NormalCallback } from './common';
19
20
  import { GetInstanceConfigCallback, GetInstanceConfigOptions, GetInstanceConfigResponse, RequestConfig, Spanner } from './index';
20
- import { CallOptions } from 'google-gax';
21
21
  export type IOperation = instanceAdmin.longrunning.IOperation;
22
22
  export type CreateInstanceConfigCallback = LongRunningCallback<InstanceConfig>;
23
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,16 +16,16 @@
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';
23
23
  import { Operation as GaxOperation, CallOptions } from 'google-gax';
24
24
  import { Backup, CopyBackupCallback, CopyBackupResponse, CopyBackupOptions } from './backup';
25
- import { google as instanceAdmin } from '../protos/protos';
26
- import { google as databaseAdmin } from '../protos/protos';
27
- import { google as spannerClient } from '../protos/protos';
28
- import { CreateInstanceRequest } from './index';
25
+ import { protos } from '@google-cloud/spanner-api';
26
+ import databaseAdmin = protos.google;
27
+ import instanceAdmin = protos.google;
28
+ import spannerClient = protos.google;
29
29
  import { ObservabilityOptions } from './instrument';
30
30
  export type IBackup = databaseAdmin.spanner.admin.database.v1.IBackup;
31
31
  export type IDatabase = databaseAdmin.spanner.admin.database.v1.IDatabase;
@@ -26,7 +26,8 @@ const database_1 = require("./database");
26
26
  const common_1 = require("./common");
27
27
  const google_gax_1 = require("google-gax");
28
28
  const backup_1 = require("./backup");
29
- const protos_1 = require("../protos/protos");
29
+ const spanner_api_1 = require("@google-cloud/spanner-api");
30
+ var databaseAdmin = spanner_api_1.protos.google;
30
31
  /**
31
32
  * The {@link Instance} class represents a [Cloud Spanner
32
33
  * instance](https://cloud.google.com/spanner/docs/instances).
@@ -465,7 +466,7 @@ class Instance extends common.GrpcServiceObject {
465
466
  const poolOptions = options.poolOptions;
466
467
  const poolCtor = options.poolCtor;
467
468
  let createStatement = 'CREATE DATABASE `' + name.split('/').pop() + '`';
468
- if (protos_1.google.spanner.admin.database.v1.DatabaseDialect.POSTGRESQL ===
469
+ if (databaseAdmin.spanner.admin.database.v1.DatabaseDialect.POSTGRESQL ===
469
470
  options.databaseDialect) {
470
471
  createStatement = 'CREATE DATABASE "' + name.split('/').pop() + '"';
471
472
  }
@@ -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.
@@ -16,7 +16,8 @@
16
16
  import { Readable, Transform } from 'stream';
17
17
  import { CallOptions } from 'google-gax';
18
18
  import { JSONOptions, Json, Field, Value } from './codec';
19
- import { google } from '../protos/protos';
19
+ import { protos } from '@google-cloud/spanner-api';
20
+ import google = protos.google;
20
21
  export type ResumeToken = string | Uint8Array;
21
22
  /**
22
23
  * @callback RequestFunction
@@ -18,19 +18,31 @@ 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");
27
24
  const transaction_runner_1 = require("./transaction-runner");
28
25
  const codec_1 = require("./codec");
29
- const protos_1 = require("../protos/protos");
30
- const stream = require("stream");
26
+ const spanner_api_1 = require("@google-cloud/spanner-api");
27
+ var google = spanner_api_1.protos.google;
31
28
  const helper_1 = require("./helper");
32
29
  const originalDecode = codec_1.codec.decode;
33
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
+ });
34
46
  /**
35
47
  * The PartialResultStream transforms partial result set objects into Row
36
48
  * objects.
@@ -115,6 +127,11 @@ class PartialResultStream extends stream_1.Transform {
115
127
  }
116
128
  if (chunk.last) {
117
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();
118
135
  return;
119
136
  }
120
137
  if (res) {
@@ -274,7 +291,7 @@ class PartialResultStream extends stream_1.Transform {
274
291
  */
275
292
  _createRow(values) {
276
293
  const len = values.length;
277
- const fields = new Array(len);
294
+ const fields = new RowImpl(len);
278
295
  const decoders = this._decoders;
279
296
  const classFields = this._fields;
280
297
  for (let i = 0; i < len; i++) {
@@ -283,11 +300,6 @@ class PartialResultStream extends stream_1.Transform {
283
300
  value: decoders[i](values[i]),
284
301
  };
285
302
  }
286
- Object.defineProperty(fields, 'toJSON', {
287
- value: (options) => {
288
- return codec_1.codec.convertFieldsToJson(fields, options);
289
- },
290
- });
291
303
  return fields;
292
304
  }
293
305
  /**
@@ -303,9 +315,9 @@ class PartialResultStream extends stream_1.Transform {
303
315
  */
304
316
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
305
317
  static merge(type, head, tail) {
306
- if (type.code === protos_1.google.spanner.v1.TypeCode.ARRAY ||
318
+ if (type.code === google.spanner.v1.TypeCode.ARRAY ||
307
319
  type.code === 'ARRAY' ||
308
- type.code === protos_1.google.spanner.v1.TypeCode.STRUCT ||
320
+ type.code === google.spanner.v1.TypeCode.STRUCT ||
309
321
  type.code === 'STRUCT') {
310
322
  if (head === null || tail === null) {
311
323
  return [head, tail];
@@ -331,7 +343,7 @@ class PartialResultStream extends stream_1.Transform {
331
343
  static mergeLists(type, head, tail) {
332
344
  let listType;
333
345
  if (type.code === 'ARRAY' ||
334
- type.code === protos_1.google.spanner.v1.TypeCode.ARRAY) {
346
+ type.code === google.spanner.v1.TypeCode.ARRAY) {
335
347
  listType = type.arrayElementType;
336
348
  }
337
349
  else {
@@ -343,6 +355,83 @@ class PartialResultStream extends stream_1.Transform {
343
355
  }
344
356
  }
345
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
+ }
346
435
  /**
347
436
  * Rows returned from queries may be chunked, requiring them to be stitched
348
437
  * together. This function returns a stream that will properly assemble these
@@ -364,26 +453,33 @@ function partialResultStream(requestFn, options) {
364
453
  const maxQueued = 10;
365
454
  let lastResumeToken;
366
455
  let lastRequestStream;
456
+ let errorListener;
367
457
  const startTime = Date.now();
368
458
  const timeout = options?.gaxOptions?.timeout ?? Infinity;
369
- // 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;
370
460
  // if we need to retry a request and pipe more data to the user's stream.
371
461
  // We also add an additional stream that can be used to flush any remaining
372
462
  // items in the checkpoint stream that have been received, and that did not
373
463
  // contain a resume token.
374
- const requestsStream = mergeStream();
375
- const flushStream = new stream.PassThrough({ objectMode: true });
376
- 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);
377
467
  const partialRSStream = new PartialResultStream(options);
378
468
  const userStream = streamEvents(partialRSStream);
379
469
  // We keep track of the number of PartialResultSets that did not include a
380
470
  // resume token, as that is an indication whether it is safe to retry the
381
471
  // stream halfway.
382
472
  let withoutCheckpointCount = 0;
383
- const batchAndSplitOnTokenStream = checkpointStream.obj({
473
+ let receivedLast = false;
474
+ const batchAndSplitOnTokenStream = new CheckpointStream({
384
475
  maxQueued,
385
476
  isCheckpointFn: (chunk) => {
386
- 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);
387
483
  if (withCheckpoint) {
388
484
  withoutCheckpointCount = 0;
389
485
  }
@@ -396,30 +492,65 @@ function partialResultStream(requestFn, options) {
396
492
  // This listener ensures that the last request that executed successfully
397
493
  // after one or more retries will end the requestsStream.
398
494
  const endListener = () => {
495
+ if (receivedLast) {
496
+ return;
497
+ }
399
498
  setImmediate(() => {
499
+ if (receivedLast) {
500
+ return;
501
+ }
400
502
  // Push a fake PartialResultSet without any values but with a resume token
401
503
  // into the stream to ensure that the checkpoint stream is emptied, and
402
504
  // then push `null` to end the stream.
403
505
  flushStream.push({ resumeToken: '_' });
404
506
  flushStream.push(null);
405
- requestsStream.end();
406
507
  });
407
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
+ };
408
530
  const makeRequest = () => {
409
531
  if ((0, helper_1.isDefined)(lastResumeToken) && lastResumeToken.length > 0) {
410
532
  partialRSStream._resetPendingValues();
411
533
  }
412
534
  lastRequestStream = requestFn(lastResumeToken);
413
535
  lastRequestStream.on('end', endListener);
414
- 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 });
415
545
  };
416
546
  const retry = (err) => {
547
+ destroyRequestStream();
417
548
  const elapsed = Date.now() - startTime;
418
549
  if (elapsed >= timeout) {
419
550
  // The timeout has reached so this will flush any rows the
420
551
  // checkpoint stream has queued. After that, we will destroy the
421
552
  // user's stream with the Deadline exceeded error.
422
- setImmediate(() => batchAndSplitOnTokenStream.destroy(new transaction_runner_1.DeadlineError(err)));
553
+ setImmediate(() => batchAndSplitOnTokenStream.flushAndDestroy(new transaction_runner_1.DeadlineError(err)));
423
554
  return;
424
555
  }
425
556
  if (!(err.code &&
@@ -430,13 +561,9 @@ function partialResultStream(requestFn, options) {
430
561
  // This is not a retryable error so this will flush any rows the
431
562
  // checkpoint stream has queued. After that, we will destroy the
432
563
  // user's stream with the same error.
433
- setImmediate(() => batchAndSplitOnTokenStream.destroy(err));
564
+ setImmediate(() => batchAndSplitOnTokenStream.flushAndDestroy(err));
434
565
  return;
435
566
  }
436
- if (lastRequestStream) {
437
- lastRequestStream.removeListener('end', endListener);
438
- lastRequestStream.destroy();
439
- }
440
567
  // Delay the retry until all the values that are already in the stream
441
568
  // pipeline have been handled. This ensures that the checkpoint stream is
442
569
  // reset to the correct point. Calling .reset() directly here could cause
@@ -449,13 +576,12 @@ function partialResultStream(requestFn, options) {
449
576
  });
450
577
  };
451
578
  userStream.once('reading', makeRequest);
452
- eventsIntercept.patch(requestsStream);
453
- // need types for events-intercept
454
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
455
- requestsStream.intercept('error', err =>
456
- // Retry __after__ all pending data has been processed to ensure that the
457
- // checkpoint stream is reset at the correct position.
458
- setImmediate(() => retry(err)));
579
+ userStream.once('close', () => {
580
+ destroyRequestStream();
581
+ requestsStream.destroy();
582
+ flushStream.destroy();
583
+ batchAndSplitOnTokenStream.destroy();
584
+ });
459
585
  return (requestsStream
460
586
  .pipe(batchAndSplitOnTokenStream)
461
587
  // If we get this error, the checkpoint stream has flushed any rows
@@ -0,0 +1,21 @@
1
+ declare const RetryInfo: import("protobufjs").Type;
2
+ /**
3
+ * Builds the filesystem path to a particular proto sub-path, for protos
4
+ * stored in `@google-cloud/spanner-api`.
5
+ *
6
+ * @param protoSubPath A sub-path like 'google/spanner', or undefined to get the base path.
7
+ * @returns The requested path.
8
+ *
9
+ * @private
10
+ */
11
+ export declare function getProtoPath(protoSubPath?: string): string;
12
+ /**
13
+ * Returns the RetryInfo type that was loaded from status.json. This is
14
+ * not included in the spanner-api package, so it's imported here.
15
+ *
16
+ * @returns The RetryInfo type.
17
+ *
18
+ * @private
19
+ */
20
+ export declare function getRetryInfo(): typeof RetryInfo;
21
+ export {};
@@ -0,0 +1,52 @@
1
+ "use strict";
2
+ // Copyright 2026 Google LLC
3
+ //
4
+ // Licensed under the Apache License, Version 2.0 (the "License");
5
+ // you may not use this file except in compliance with the License.
6
+ // You may obtain a copy of the License at
7
+ //
8
+ // https://www.apache.org/licenses/LICENSE-2.0
9
+ //
10
+ // Unless required by applicable law or agreed to in writing, software
11
+ // distributed under the License is distributed on an "AS IS" BASIS,
12
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ // See the License for the specific language governing permissions and
14
+ // limitations under the License.
15
+ Object.defineProperty(exports, "__esModule", { value: true });
16
+ exports.getProtoPath = getProtoPath;
17
+ exports.getRetryInfo = getRetryInfo;
18
+ const path = require("node:path");
19
+ const API_PATH = path.dirname(require.resolve('@google-cloud/spanner-api/package.json'));
20
+ const IMPORT_PATH = path.join(API_PATH, 'build/protos');
21
+ const protobufjs_1 = require("protobufjs");
22
+ const statusProtoJson = require('../protos/status.json');
23
+ const RetryInfo = protobufjs_1.Root.fromJSON(statusProtoJson).lookupType('google.rpc.RetryInfo');
24
+ /**
25
+ * Builds the filesystem path to a particular proto sub-path, for protos
26
+ * stored in `@google-cloud/spanner-api`.
27
+ *
28
+ * @param protoSubPath A sub-path like 'google/spanner', or undefined to get the base path.
29
+ * @returns The requested path.
30
+ *
31
+ * @private
32
+ */
33
+ function getProtoPath(protoSubPath) {
34
+ if (protoSubPath) {
35
+ return path.join(IMPORT_PATH, protoSubPath);
36
+ }
37
+ else {
38
+ return IMPORT_PATH;
39
+ }
40
+ }
41
+ /**
42
+ * Returns the RetryInfo type that was loaded from status.json. This is
43
+ * not included in the spanner-api package, so it's imported here.
44
+ *
45
+ * @returns The RetryInfo type.
46
+ *
47
+ * @private
48
+ */
49
+ function getRetryInfo() {
50
+ return RetryInfo;
51
+ }
52
+ //# sourceMappingURL=protos.js.map
@@ -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.