@google-cloud/spanner 8.12.0 → 8.13.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.
@@ -1567,6 +1567,37 @@ declare class Database extends common.GrpcServiceObject {
1567
1567
  run(query: string | ExecuteSqlRequest, options?: TimestampBounds): Promise<RunResponse>;
1568
1568
  run(query: string | ExecuteSqlRequest, callback: RunCallback): void;
1569
1569
  run(query: string | ExecuteSqlRequest, options: TimestampBounds, callback: RunCallback): void;
1570
+ /**
1571
+ * Always runs the query through the full streaming pipeline (Database.prototype.runStream).
1572
+ * Used when runStream has been overridden on Database, or when multiplexed
1573
+ * sessions are disabled (requiring standard session pool checkout and session-not-found retries).
1574
+ *
1575
+ * @private
1576
+ */
1577
+ private _runLegacy;
1578
+ /**
1579
+ * Executes a query using an optimized streaming model:
1580
+ * 1. If all results are returned in a single PartialResultSet, the internal streaming
1581
+ * pipeline is simplified and rows are decoded directly, bypassing Stream overhead.
1582
+ * 2. If there are more than one PartialResultSets, it seamlessly falls back to
1583
+ * the standard streaming model.
1584
+ *
1585
+ * @private
1586
+ */
1587
+ private _run;
1588
+ /**
1589
+ * Acquires a session and executes the query on a snapshot, managing span
1590
+ * lifetimes and session release.
1591
+ *
1592
+ * @private
1593
+ */
1594
+ private _executeRunOnSession;
1595
+ /**
1596
+ * Executes the query on the snapshot and binds session release to snapshot end.
1597
+ *
1598
+ * @private
1599
+ */
1600
+ private _runOnSnapshot;
1570
1601
  /**
1571
1602
  * Partitioned DML transactions are used to execute DML statements with a
1572
1603
  * different execution strategy that provides different, and often better,
@@ -29,6 +29,7 @@ const session_factory_1 = require("./session-factory");
29
29
  const session_1 = require("./session");
30
30
  const session_pool_1 = require("./session-pool");
31
31
  const table_1 = require("./table");
32
+ const transaction_1 = require("./transaction");
32
33
  const transaction_runner_1 = require("./transaction-runner");
33
34
  const common_1 = require("./common");
34
35
  const stream_1 = require("stream");
@@ -941,16 +942,31 @@ class Database extends common.GrpcServiceObject {
941
942
  });
942
943
  }
943
944
  run(query, optionsOrCallback, cb) {
944
- let stats;
945
- let metadata;
946
- const rows = [];
947
945
  const callback = typeof optionsOrCallback === 'function'
948
946
  ? optionsOrCallback
949
947
  : cb;
950
948
  const options = typeof optionsOrCallback === 'object'
951
949
  ? optionsOrCallback
952
950
  : {};
953
- return (0, instrument_1.startTrace)('Database.run', {
951
+ if (this.runStream !== Database.prototype.runStream ||
952
+ !this.sessionFactory_.isMultiplexedEnabled()) {
953
+ this._runLegacy(query, options, callback);
954
+ return;
955
+ }
956
+ this._run(query, options, callback);
957
+ }
958
+ /**
959
+ * Always runs the query through the full streaming pipeline (Database.prototype.runStream).
960
+ * Used when runStream has been overridden on Database, or when multiplexed
961
+ * sessions are disabled (requiring standard session pool checkout and session-not-found retries).
962
+ *
963
+ * @private
964
+ */
965
+ _runLegacy(query, options, callback) {
966
+ const rows = [];
967
+ let stats;
968
+ let metadata;
969
+ (0, instrument_1.startTrace)('Database.run', {
954
970
  ...query,
955
971
  ...this._traceConfig,
956
972
  }, span => {
@@ -975,6 +991,89 @@ class Database extends common.GrpcServiceObject {
975
991
  });
976
992
  });
977
993
  }
994
+ /**
995
+ * Executes a query using an optimized streaming model:
996
+ * 1. If all results are returned in a single PartialResultSet, the internal streaming
997
+ * pipeline is simplified and rows are decoded directly, bypassing Stream overhead.
998
+ * 2. If there are more than one PartialResultSets, it seamlessly falls back to
999
+ * the standard streaming model.
1000
+ *
1001
+ * @private
1002
+ */
1003
+ _run(query, options, callback) {
1004
+ const traceConfig = {
1005
+ ...query,
1006
+ ...this._traceConfig,
1007
+ };
1008
+ (0, instrument_1.startTrace)('Database.run', traceConfig, runSpan => {
1009
+ (0, instrument_1.startTrace)('Database.runStream', traceConfig, streamSpan => {
1010
+ this._executeRunOnSession(query, options, runSpan, streamSpan, callback);
1011
+ });
1012
+ });
1013
+ }
1014
+ /**
1015
+ * Acquires a session and executes the query on a snapshot, managing span
1016
+ * lifetimes and session release.
1017
+ *
1018
+ * @private
1019
+ */
1020
+ _executeRunOnSession(query, options, runSpan, streamSpan, callback) {
1021
+ let snapshot;
1022
+ let completed = false;
1023
+ const complete = (error, rows = [], stats, metadata) => {
1024
+ if (completed) {
1025
+ return;
1026
+ }
1027
+ completed = true;
1028
+ if (error) {
1029
+ (0, instrument_1.setSpanError)(streamSpan, error);
1030
+ (0, instrument_1.setSpanError)(runSpan, error);
1031
+ }
1032
+ snapshot?.end();
1033
+ streamSpan.end();
1034
+ runSpan.end();
1035
+ callback(error, rows, stats, metadata);
1036
+ };
1037
+ this.sessionFactory_.getSession((error, session) => {
1038
+ if (error) {
1039
+ complete(error);
1040
+ return;
1041
+ }
1042
+ streamSpan.addEvent('Using Session', { 'session.id': session?.id });
1043
+ snapshot = session.snapshot(options, this.queryOptions_);
1044
+ this._runOnSnapshot(snapshot, session, query, complete);
1045
+ });
1046
+ }
1047
+ /**
1048
+ * Executes the query on the snapshot and binds session release to snapshot end.
1049
+ *
1050
+ * @private
1051
+ */
1052
+ _runOnSnapshot(snapshot, session, query, callback) {
1053
+ snapshot.once('end', () => {
1054
+ try {
1055
+ this.sessionFactory_.release(session);
1056
+ }
1057
+ catch (releaseError) {
1058
+ this.emit('error', releaseError);
1059
+ }
1060
+ });
1061
+ const snapshotWithRun = snapshot;
1062
+ try {
1063
+ if (typeof snapshotWithRun._run === 'function' &&
1064
+ snapshot.runStream === transaction_1.Snapshot.prototype.runStream) {
1065
+ snapshotWithRun._run(query, callback, {
1066
+ startRunSpan: false,
1067
+ });
1068
+ }
1069
+ else {
1070
+ snapshot.run(query, callback);
1071
+ }
1072
+ }
1073
+ catch (syncError) {
1074
+ callback(syncError);
1075
+ }
1076
+ }
978
1077
  runPartitionedUpdate(query, callback) {
979
1078
  return (0, instrument_1.startTrace)('Database.runPartitionedUpdate', {
980
1079
  ...query,
@@ -80,9 +80,12 @@ const CACHE_TTL_MS = 10000; // 10 seconds TTL
80
80
  * @returns {boolean} True if global tracing is enabled.
81
81
  */
82
82
  function isGlobalTracingEnabled() {
83
+ if (globalTracingEnabled === true) {
84
+ return true;
85
+ }
83
86
  const now = Date.now();
84
87
  if (globalTracingEnabled !== undefined &&
85
- (globalTracingEnabled || now - lastCheckTime < CACHE_TTL_MS)) {
88
+ now - lastCheckTime < CACHE_TTL_MS) {
86
89
  return globalTracingEnabled;
87
90
  }
88
91
  lastCheckTime = now;
@@ -47,7 +47,10 @@ const MetricInterceptor = (options, nextCall) => {
47
47
  // GFE/AFE latency if available,
48
48
  // or else increase the GFE/AFE connectivity error count
49
49
  if (metricsTracer) {
50
- const serverTimingHeader = metadata.getMap()['server-timing'];
50
+ const serverTimingEntries = metadata.get('server-timing');
51
+ const serverTimingHeader = serverTimingEntries.length > 0
52
+ ? String(serverTimingEntries[0])
53
+ : undefined;
51
54
  const gfeTiming = metricsTracer?.extractGfeLatency(serverTimingHeader);
52
55
  metricsTracer.gfeLatency = gfeTiming ?? null;
53
56
  const afeTiming = metricsTracer?.extractAfeLatency(serverTimingHeader);
@@ -50,7 +50,9 @@ class CloudMonitoringMetricsExporter {
50
50
  return;
51
51
  }
52
52
  this._lastExported = now;
53
- this._exportAsync(metrics).then(resultCallback, err => {
53
+ this._exportAsync(metrics)
54
+ .then(resultCallback)
55
+ .catch(err => {
54
56
  resultCallback({ code: core_1.ExportResultCode.FAILED, error: err });
55
57
  });
56
58
  }
@@ -106,6 +106,39 @@ export interface Row extends Array<Field> {
106
106
  */
107
107
  toJSON(options?: JSONOptions): Json;
108
108
  }
109
+ /**
110
+ * Creates an array of decoder functions for the specified struct fields.
111
+ *
112
+ * @private
113
+ */
114
+ export declare function createFieldDecoders(fields: google.spanner.v1.StructType.Field[], options?: RowOptions): Function[];
115
+ /**
116
+ * Directly creates a plain JSON object from row cell values, bypassing
117
+ * Struct, Row, and WrappedNumber class wrappers when possible.
118
+ *
119
+ * @private
120
+ */
121
+ export declare function createJsonRow(fields: google.spanner.v1.StructType.Field[], decoders: Function[], values: Value[], includeNameless?: boolean): Json;
122
+ /**
123
+ * Converts an array of decoded cell values into a Row.
124
+ *
125
+ * @private
126
+ */
127
+ export declare function createRow(fields: google.spanner.v1.StructType.Field[], decoders: Function[], values: Value[]): Row;
128
+ /**
129
+ * Formats raw row values into either a plain JSON object or a Row instance
130
+ * according to the provided RowOptions.
131
+ *
132
+ * @private
133
+ */
134
+ export declare function formatRow(fields: google.spanner.v1.StructType.Field[], decoders: Function[], values: Value[], options?: RowOptions): Row;
135
+ /**
136
+ * Directly decodes rows from a PartialResultSet without going through the stream
137
+ * pipeline. Used by the fast-path for queries returning small results in a single chunk.
138
+ *
139
+ * @private
140
+ */
141
+ export declare function decodeRowsDirect(chunk: google.spanner.v1.PartialResultSet, options?: RowOptions, existingFields?: google.spanner.v1.StructType.Field[], existingDecoders?: Function[]): Row[];
109
142
  /**
110
143
  * @callback PartialResultStream~rowCallback
111
144
  * @param {Row|object} row The row data.
@@ -165,6 +198,7 @@ export declare class PartialResultStream extends Transform implements ResultEven
165
198
  private _pendingValueForResume?;
166
199
  private _values;
167
200
  private _numPushFailed;
201
+ private _isFirstChunk;
168
202
  constructor(options?: {});
169
203
  /**
170
204
  * Destroys the stream.
@@ -192,6 +226,15 @@ export declare class PartialResultStream extends Transform implements ResultEven
192
226
  * @param {object} chunk The partial result set.
193
227
  */
194
228
  private _addChunk;
229
+ /**
230
+ * Fast-path handler for single-chunk stream responses. Decodes rows directly
231
+ * and pushes them into the stream without incremental chunk buffering.
232
+ *
233
+ * @private
234
+ * @param {google.spanner.v1.PartialResultSet} chunk The partial result set.
235
+ * @returns {boolean} Whether the stream can accept more data.
236
+ */
237
+ private _addSingleChunk;
195
238
  /**
196
239
  * Manages complete values, pushing a completed row into the stream once all
197
240
  * values have been received.
@@ -16,6 +16,11 @@
16
16
  */
17
17
  Object.defineProperty(exports, "__esModule", { value: true });
18
18
  exports.PartialResultStream = void 0;
19
+ exports.createFieldDecoders = createFieldDecoders;
20
+ exports.createJsonRow = createJsonRow;
21
+ exports.createRow = createRow;
22
+ exports.formatRow = formatRow;
23
+ exports.decodeRowsDirect = decodeRowsDirect;
19
24
  exports.partialResultStream = partialResultStream;
20
25
  const service_1 = require("./common-grpc/service");
21
26
  const stream_1 = require("stream");
@@ -43,6 +48,117 @@ Object.defineProperty(RowImpl.prototype, 'constructor', {
43
48
  configurable: true,
44
49
  enumerable: false,
45
50
  });
51
+ /**
52
+ * Creates an array of decoder functions for the specified struct fields.
53
+ *
54
+ * @private
55
+ */
56
+ function createFieldDecoders(fields, options) {
57
+ const jsonMode = Boolean(options?.json);
58
+ const jsonOptions = options?.jsonOptions;
59
+ const columnsMetadata = options?.columnsMetadata;
60
+ return fields.map(({ name, type }) => {
61
+ const columnMetadata = columnsMetadata &&
62
+ name !== null &&
63
+ name !== undefined &&
64
+ Object.prototype.hasOwnProperty.call(columnsMetadata, name)
65
+ ? columnsMetadata[name]
66
+ : undefined;
67
+ if (codec_1.codec.decode !== originalDecode) {
68
+ return (val) => codec_1.codec.decode(val, type, columnMetadata);
69
+ }
70
+ return codec_1.codec.getDecoder(type, columnMetadata, jsonMode ? jsonOptions || {} : undefined);
71
+ });
72
+ }
73
+ /**
74
+ * Directly creates a plain JSON object from row cell values, bypassing
75
+ * Struct, Row, and WrappedNumber class wrappers when possible.
76
+ *
77
+ * @private
78
+ */
79
+ function createJsonRow(fields, decoders, values, includeNameless) {
80
+ const json = {};
81
+ const len = fields.length;
82
+ for (let i = 0; i < len; i++) {
83
+ const { name } = fields[i];
84
+ if (!name && !includeNameless) {
85
+ continue;
86
+ }
87
+ const fieldName = name || `_${i}`;
88
+ try {
89
+ json[fieldName] = decoders[i](values[i]);
90
+ }
91
+ catch (e) {
92
+ e.message = [
93
+ `Serializing column "${fieldName}" encountered an error: ${e.message}`,
94
+ 'Call row.toJSON({ wrapNumbers: true }) to receive a custom type.',
95
+ ].join(' ');
96
+ throw e;
97
+ }
98
+ }
99
+ return json;
100
+ }
101
+ /**
102
+ * Converts an array of decoded cell values into a Row.
103
+ *
104
+ * @private
105
+ */
106
+ function createRow(fields, decoders, values) {
107
+ const len = fields.length;
108
+ const row = new RowImpl(len);
109
+ for (let i = 0; i < len; i++) {
110
+ row[i] = {
111
+ name: fields[i].name,
112
+ value: decoders[i](values[i]),
113
+ };
114
+ }
115
+ return row;
116
+ }
117
+ /**
118
+ * Formats raw row values into either a plain JSON object or a Row instance
119
+ * according to the provided RowOptions.
120
+ *
121
+ * @private
122
+ */
123
+ function formatRow(fields, decoders, values, options) {
124
+ const jsonMode = Boolean(options?.json);
125
+ const jsonOptions = options?.jsonOptions;
126
+ const isJsonStubbed = codec_1.codec.convertFieldsToJson !== originalConvertFieldsToJson;
127
+ if (jsonMode && !isJsonStubbed) {
128
+ return createJsonRow(fields, decoders, values, Boolean(jsonOptions?.includeNameless));
129
+ }
130
+ const row = createRow(fields, decoders, values);
131
+ return jsonMode ? row.toJSON(jsonOptions) : row;
132
+ }
133
+ /**
134
+ * Directly decodes rows from a PartialResultSet without going through the stream
135
+ * pipeline. Used by the fast-path for queries returning small results in a single chunk.
136
+ *
137
+ * @private
138
+ */
139
+ function decodeRowsDirect(chunk, options, existingFields, existingDecoders) {
140
+ const fields = existingFields ||
141
+ (chunk.metadata?.rowType?.fields ||
142
+ []);
143
+ const numFields = fields.length;
144
+ const chunkValues = chunk.values || [];
145
+ const numValues = chunkValues.length;
146
+ if (numFields === 0 || numValues === 0) {
147
+ return [];
148
+ }
149
+ const rowCount = Math.floor(numValues / numFields);
150
+ const rows = new Array(rowCount);
151
+ const decoders = existingDecoders || createFieldDecoders(fields, options);
152
+ const rowValues = new Array(numFields);
153
+ for (let rowIndex = 0; rowIndex < rowCount; rowIndex++) {
154
+ const offset = rowIndex * numFields;
155
+ for (let columnIndex = 0; columnIndex < numFields; columnIndex++) {
156
+ rowValues[columnIndex] = service_1.GrpcService.decodeValue_(chunkValues[offset + columnIndex]);
157
+ }
158
+ rows[rowIndex] = formatRow(fields, decoders, rowValues, options);
159
+ }
160
+ return rows;
161
+ }
46
162
  /**
47
163
  * The PartialResultStream transforms partial result set objects into Row
48
164
  * objects.
@@ -61,11 +177,13 @@ class PartialResultStream extends stream_1.Transform {
61
177
  _pendingValueForResume;
62
178
  _values;
63
179
  _numPushFailed = 0;
180
+ _isFirstChunk = true;
64
181
  constructor(options = {}) {
65
182
  super({ objectMode: true });
66
183
  this._destroyed = false;
67
184
  this._options = Object.assign({ maxResumeRetries: 20 }, options);
68
185
  this._values = [];
186
+ this._isFirstChunk = true;
69
187
  }
70
188
  /**
71
189
  * Destroys the stream.
@@ -102,18 +220,7 @@ class PartialResultStream extends stream_1.Transform {
102
220
  if (!this._fields && chunk.metadata) {
103
221
  this._fields = chunk.metadata.rowType
104
222
  .fields;
105
- this._decoders = this._fields.map(({ name, type }) => {
106
- const columnMetadata = this._options.columnsMetadata &&
107
- name !== null &&
108
- name !== undefined &&
109
- Object.prototype.hasOwnProperty.call(this._options.columnsMetadata, name)
110
- ? this._options.columnsMetadata[name]
111
- : undefined;
112
- if (codec_1.codec.decode !== originalDecode) {
113
- return val => codec_1.codec.decode(val, type, columnMetadata);
114
- }
115
- return codec_1.codec.getDecoder(type, columnMetadata, this._options.json ? this._options.jsonOptions || {} : undefined);
116
- });
223
+ this._decoders = createFieldDecoders(this._fields, this._options);
117
224
  }
118
225
  let res = true;
119
226
  if (!(0, helper_1.isEmpty)(chunk.values)) {
@@ -187,6 +294,12 @@ class PartialResultStream extends stream_1.Transform {
187
294
  * @param {object} chunk The partial result set.
188
295
  */
189
296
  _addChunk(chunk) {
297
+ const isFirstChunk = this._isFirstChunk;
298
+ this._isFirstChunk = false;
299
+ // Fast path for single-chunk stream responses:
300
+ if (isFirstChunk && chunk.last && !chunk.chunkedValue) {
301
+ return this._addSingleChunk(chunk);
302
+ }
190
303
  const chunkValues = chunk.values;
191
304
  const numValues = chunkValues.length;
192
305
  const values = new Array(numValues);
@@ -222,6 +335,26 @@ class PartialResultStream extends stream_1.Transform {
222
335
  }
223
336
  return res;
224
337
  }
338
+ /**
339
+ * Fast-path handler for single-chunk stream responses. Decodes rows directly
340
+ * and pushes them into the stream without incremental chunk buffering.
341
+ *
342
+ * @private
343
+ * @param {google.spanner.v1.PartialResultSet} chunk The partial result set.
344
+ * @returns {boolean} Whether the stream can accept more data.
345
+ */
346
+ _addSingleChunk(chunk) {
347
+ const rows = decodeRowsDirect(chunk, this._options, this._fields, this._decoders);
348
+ let canAcceptMore = true;
349
+ for (let i = 0; i < rows.length; i++) {
350
+ const accepted = this.push(rows[i]);
351
+ if (!accepted && canAcceptMore) {
352
+ canAcceptMore = false;
353
+ this.emit('paused');
354
+ }
355
+ }
356
+ return canAcceptMore;
357
+ }
225
358
  /**
226
359
  * Manages complete values, pushing a completed row into the stream once all
227
360
  * values have been received.
@@ -237,15 +370,7 @@ class PartialResultStream extends stream_1.Transform {
237
370
  return true;
238
371
  }
239
372
  this._values = [];
240
- const isJsonStubbed = codec_1.codec.convertFieldsToJson !== originalConvertFieldsToJson;
241
- if (this._options.json && !isJsonStubbed) {
242
- return this.push(this._createJsonRow(values));
243
- }
244
- const row = this._createRow(values);
245
- if (this._options.json) {
246
- return this.push(row.toJSON(this._options.jsonOptions));
247
- }
248
- return this.push(row);
373
+ return this.push(formatRow(this._fields, this._decoders, values, this._options));
249
374
  }
250
375
  /**
251
376
  * Directly creates a plain JSON object from row cell values, bypassing
@@ -257,29 +382,7 @@ class PartialResultStream extends stream_1.Transform {
257
382
  * @returns {Json} The plain JavaScript object representing the row.
258
383
  */
259
384
  _createJsonRow(values) {
260
- const json = {};
261
- const fields = this._fields;
262
- const decoders = this._decoders;
263
- const len = fields.length;
264
- const includeNameless = !!this._options.jsonOptions?.includeNameless;
265
- for (let i = 0; i < len; i++) {
266
- const { name } = fields[i];
267
- if (!name && !includeNameless) {
268
- continue;
269
- }
270
- const fieldName = name ? name : `_${i}`;
271
- try {
272
- json[fieldName] = decoders[i](values[i]);
273
- }
274
- catch (e) {
275
- e.message = [
276
- `Serializing column "${fieldName}" encountered an error: ${e.message}`,
277
- 'Call row.toJSON({ wrapNumbers: true }) to receive a custom type.',
278
- ].join(' ');
279
- throw e;
280
- }
281
- }
282
- return json;
385
+ return createJsonRow(this._fields, this._decoders, values, Boolean(this._options.jsonOptions?.includeNameless));
283
386
  }
284
387
  /**
285
388
  * Converts an array of values into a row.
@@ -290,17 +393,7 @@ class PartialResultStream extends stream_1.Transform {
290
393
  * @returns {Row}
291
394
  */
292
395
  _createRow(values) {
293
- const len = values.length;
294
- const fields = new RowImpl(len);
295
- const decoders = this._decoders;
296
- const classFields = this._fields;
297
- for (let i = 0; i < len; i++) {
298
- fields[i] = {
299
- name: classFields[i].name,
300
- value: decoders[i](values[i]),
301
- };
302
- }
303
- return fields;
396
+ return createRow(this._fields, this._decoders, values);
304
397
  }
305
398
  /**
306
399
  * Attempts to merge chunked values together.
@@ -169,10 +169,6 @@ export interface BatchUpdateOptions {
169
169
  export interface BatchUpdateCallback {
170
170
  (err: null | BatchUpdateError, rowCounts: number[], response?: spannerClient.spanner.v1.ExecuteBatchDmlResponse): void;
171
171
  }
172
- export interface BatchUpdateOptions {
173
- requestOptions?: Omit<IRequestOptions, 'transactionTag'>;
174
- gaxOptions?: CallOptions;
175
- }
176
172
  export type ReadCallback = NormalCallback<Rows>;
177
173
  export interface RunCallback {
178
174
  (err: null | grpc.ServiceError, rows: Rows, stats: spannerClient.spanner.v1.ResultSetStats, metadata?: spannerClient.spanner.v1.ResultSetMetadata): void;
@@ -239,7 +235,7 @@ type PrecommitTokenProvider = spannerClient.spanner.v1.ITransaction | spannerCli
239
235
  export declare class Snapshot extends EventEmitter {
240
236
  protected _options: spannerClient.spanner.v1.ITransactionOptions;
241
237
  protected _seqno: number;
242
- protected _waitingRequests: Array<() => void>;
238
+ protected _waitingRequests: Array<(err?: Error) => void>;
243
239
  protected _inlineBeginStarted: any;
244
240
  protected _useInRunner: boolean;
245
241
  protected _latestPreCommitToken: spannerClient.spanner.v1.IMultiplexedSessionPrecommitToken | undefined | null;
@@ -805,6 +801,26 @@ export declare class Snapshot extends EventEmitter {
805
801
  */
806
802
  run(query: string | ExecuteSqlRequest): Promise<RunResponse>;
807
803
  run(query: string | ExecuteSqlRequest, callback: RunCallback): void;
804
+ /**
805
+ * Always runs the query through the full streaming pipeline (Snapshot.prototype.runStream).
806
+ * Used when runStream has been overridden on Snapshot to preserve backward compatibility
807
+ * with custom stream implementations.
808
+ *
809
+ * @private
810
+ */
811
+ private _runLegacy;
812
+ /**
813
+ * Executes a query using an optimized streaming model:
814
+ * 1. If all results are returned in a single PartialResultSet, the internal streaming
815
+ * pipeline is simplified and rows are decoded directly, bypassing Stream overhead.
816
+ * 2. If there are more than one PartialResultSets, it seamlessly falls back to
817
+ * the standard streaming model.
818
+ *
819
+ * @private
820
+ */
821
+ _run(queryInput: string | ExecuteSqlRequest, callback: RunCallback, options?: {
822
+ startRunSpan?: boolean;
823
+ }): void;
808
824
  /**
809
825
  * ExecuteSql request options. This includes all standard ExecuteSqlRequest
810
826
  * options as well as several convenience properties.
@@ -967,7 +983,7 @@ export declare class Snapshot extends EventEmitter {
967
983
  * @private
968
984
  */
969
985
  private _wrapWithIdWaiter;
970
- _releaseWaitingRequests(): void;
986
+ _releaseWaitingRequests(err?: Error): void;
971
987
  /**
972
988
  * Gets the Spanner object
973
989
  *
@@ -31,6 +31,7 @@ var spannerClient = spanner_api_1.protos.google;
31
31
  var google = spanner_api_1.protos.google;
32
32
  var IsolationLevel = google.spanner.v1.TransactionOptions.IsolationLevel;
33
33
  var ReadLockMode = google.spanner.v1.TransactionOptions.ReadWrite.ReadLockMode;
34
+ const transaction_runner_1 = require("./transaction-runner");
34
35
  const request_id_header_1 = require("./request_id_header");
35
36
  const RETRY_INFO_TYPE = 'type.googleapis.com/google.rpc.retryinfo';
36
37
  const RETRY_INFO_BIN = 'google.rpc.retryinfo-bin';
@@ -48,6 +49,17 @@ function injectGaxOpt(existingOpts, key, value) {
48
49
  }),
49
50
  });
50
51
  }
52
+ function normalizeError(err) {
53
+ const errorWithCode = err;
54
+ if (errorWithCode.code === undefined) {
55
+ Object.assign(errorWithCode, {
56
+ code: google_gax_1.grpc.status.UNKNOWN,
57
+ details: err.message,
58
+ metadata: new google_gax_1.grpc.Metadata(),
59
+ });
60
+ }
61
+ return errorWithCode;
62
+ }
51
63
  /**
52
64
  * @typedef {object} TimestampBounds
53
65
  * @property {boolean} [strong=true] Read at a timestamp where all previously
@@ -746,6 +758,7 @@ class Snapshot extends events_1.EventEmitter {
746
758
  return;
747
759
  }
748
760
  this.ended = true;
761
+ this._releaseWaitingRequests(new Error('Transaction has ended.'));
749
762
  process.nextTick(() => this.emit('end'));
750
763
  if (this._affinityKey) {
751
764
  const database = this.session?.parent;
@@ -754,7 +767,7 @@ class Snapshot extends events_1.EventEmitter {
754
767
  if (client?.spannerStub) {
755
768
  Promise.resolve(client.spannerStub)
756
769
  .then((stub) => {
757
- stub?.getChannel?.()?.unbind?.(this._affinityKey);
770
+ return stub?.getChannel?.()?.unbind?.(this._affinityKey);
758
771
  })
759
772
  .catch(() => { });
760
773
  }
@@ -791,6 +804,19 @@ class Snapshot extends events_1.EventEmitter {
791
804
  });
792
805
  }
793
806
  run(query, callback) {
807
+ if (this.runStream !== Snapshot.prototype.runStream) {
808
+ return this._runLegacy(query, callback);
809
+ }
810
+ return this._run(query, callback);
811
+ }
812
+ /**
813
+ * Always runs the query through the full streaming pipeline (Snapshot.prototype.runStream).
814
+ * Used when runStream has been overridden on Snapshot to preserve backward compatibility
815
+ * with custom stream implementations.
816
+ *
817
+ * @private
818
+ */
819
+ _runLegacy(query, callback) {
794
820
  const rows = [];
795
821
  let stats;
796
822
  let metadata;
@@ -798,18 +824,11 @@ class Snapshot extends events_1.EventEmitter {
798
824
  ...query,
799
825
  ...this._traceConfig,
800
826
  }, span => {
801
- return this.runStream(query)
827
+ this.runStream(query)
802
828
  .on('error', err => {
803
829
  (0, instrument_1.setSpanError)(span, err);
804
830
  span.end();
805
- if (!('code' in err)) {
806
- Object.assign(err, {
807
- code: google_gax_1.grpc.status.UNKNOWN,
808
- details: err.message,
809
- metadata: new google_gax_1.grpc.Metadata(),
810
- });
811
- }
812
- callback(err, rows, stats, metadata);
831
+ callback(normalizeError(err), rows, stats, metadata);
813
832
  })
814
833
  .on('response', response => {
815
834
  if (response.metadata) {
@@ -819,14 +838,298 @@ class Snapshot extends events_1.EventEmitter {
819
838
  }
820
839
  }
821
840
  })
822
- .on('data', row => rows.push(row))
823
- .on('stats', _stats => (stats = _stats))
841
+ .on('data', row => {
842
+ rows.push(row);
843
+ })
844
+ .on('stats', _stats => {
845
+ stats = _stats;
846
+ })
824
847
  .on('end', () => {
825
848
  span.end();
826
849
  callback(null, rows, stats, metadata);
827
850
  });
828
851
  });
829
852
  }
853
+ /**
854
+ * Executes a query using an optimized streaming model:
855
+ * 1. If all results are returned in a single PartialResultSet, the internal streaming
856
+ * pipeline is simplified and rows are decoded directly, bypassing Stream overhead.
857
+ * 2. If there are more than one PartialResultSets, it seamlessly falls back to
858
+ * the standard streaming model.
859
+ *
860
+ * @private
861
+ */
862
+ _run(queryInput, callback, options) {
863
+ let query = typeof queryInput === 'string' ? { sql: queryInput } : queryInput;
864
+ query = Object.assign({}, query);
865
+ query.queryOptions = Object.assign(Object.assign({}, this.queryOptions), query.queryOptions);
866
+ const { gaxOptions, json, jsonOptions, maxResumeRetries, requestOptions, columnsMetadata, types: _omittedTypes, directedReadOptions: rawDirectedReadOptions, ...rawQuery } = query;
867
+ void _omittedTypes;
868
+ let formattedRequest;
869
+ const seqno = this._seqno++;
870
+ const directedReadOptions = this._getDirectedReadOptions(rawDirectedReadOptions);
871
+ const sanitizeRequest = () => {
872
+ const { params, paramTypes } = Snapshot.encodeParams(query);
873
+ const transaction = {};
874
+ if (this.id) {
875
+ transaction.id = this.id;
876
+ }
877
+ else if (this._options.readWrite) {
878
+ transaction.begin = this._options;
879
+ }
880
+ else {
881
+ transaction.singleUse = this._options;
882
+ }
883
+ if (!this.id &&
884
+ this._options.readWrite &&
885
+ this.session.parent.isMuxEnabledForRW_) {
886
+ this._setPreviousTransactionId(transaction);
887
+ }
888
+ formattedRequest = Object.assign({}, rawQuery, {
889
+ session: this.session.formattedName_,
890
+ seqno,
891
+ requestOptions: this.configureTagOptions(typeof transaction.singleUse !== 'undefined', this.requestOptions?.transactionTag ?? undefined, requestOptions),
892
+ directedReadOptions,
893
+ transaction,
894
+ params,
895
+ paramTypes,
896
+ });
897
+ };
898
+ const headers = Object.assign({}, this.commonHeaders_);
899
+ if (this._getSpanner().routeToLeaderEnabled &&
900
+ (this._options.readWrite !== undefined ||
901
+ this._options.partitionedDml !== undefined)) {
902
+ (0, common_1.addLeaderAwareRoutingHeader)(headers);
903
+ }
904
+ const traceConfig = {
905
+ transactionTag: this.requestOptions?.transactionTag,
906
+ requestTag: requestOptions?.requestTag,
907
+ ...query,
908
+ ...this._traceConfig,
909
+ };
910
+ const executeWithSpans = (fn) => {
911
+ const startRunSpan = options?.startRunSpan !== false;
912
+ if (startRunSpan) {
913
+ return (0, instrument_1.startTrace)('Snapshot.run', traceConfig, runSpan => {
914
+ return (0, instrument_1.startTrace)('Snapshot.runStream', traceConfig, streamSpan => {
915
+ fn(runSpan, streamSpan);
916
+ });
917
+ });
918
+ }
919
+ else {
920
+ return (0, instrument_1.startTrace)('Snapshot.runStream', traceConfig, streamSpan => {
921
+ fn(null, streamSpan);
922
+ });
923
+ }
924
+ };
925
+ executeWithSpans((runSpan, streamSpan) => {
926
+ let attempt = 0;
927
+ const database = this.session.parent;
928
+ const nthRequest = (0, request_id_header_1.nextNthRequest)(database);
929
+ let completed = false;
930
+ const complete = (err, rows = [], stats, metadata) => {
931
+ if (completed) {
932
+ return;
933
+ }
934
+ completed = true;
935
+ if (err) {
936
+ (0, instrument_1.setSpanError)(streamSpan, err);
937
+ }
938
+ streamSpan.end();
939
+ if (runSpan) {
940
+ if (err) {
941
+ (0, instrument_1.setSpanError)(runSpan, err);
942
+ }
943
+ runSpan.end();
944
+ }
945
+ callback(err ? normalizeError(err) : null, rows, stats, metadata);
946
+ };
947
+ const makeRequest = (resumeToken) => {
948
+ attempt++;
949
+ if (!resumeToken) {
950
+ if (attempt === 1) {
951
+ streamSpan.addEvent('Starting stream');
952
+ }
953
+ else {
954
+ streamSpan.addEvent('Re-attempting start stream', { attempt });
955
+ }
956
+ }
957
+ else {
958
+ streamSpan.addEvent('Resuming stream', {
959
+ resume_token: resumeToken.toString(),
960
+ attempt,
961
+ });
962
+ }
963
+ if (!formattedRequest ||
964
+ (this.id && !formattedRequest.transaction?.id)) {
965
+ try {
966
+ sanitizeRequest();
967
+ }
968
+ catch (e) {
969
+ const errorStream = new stream_1.PassThrough();
970
+ setImmediate(() => {
971
+ errorStream.destroy(e);
972
+ });
973
+ return errorStream;
974
+ }
975
+ }
976
+ const injectedHeaders = (0, request_id_header_1.injectRequestIDIntoHeaders)(headers, this.session, nthRequest, attempt);
977
+ const requestId = injectedHeaders[request_id_header_1.X_GOOG_SPANNER_REQUEST_ID_HEADER];
978
+ if (runSpan && requestId) {
979
+ runSpan.setAttribute(request_id_header_1.X_GOOG_SPANNER_REQUEST_ID_SPAN_ATTR, requestId);
980
+ }
981
+ return this.requestStream({
982
+ client: 'SpannerClient',
983
+ method: 'executeStreamingSql',
984
+ reqOpts: Object.assign({}, formattedRequest, {
985
+ resumeToken,
986
+ }),
987
+ gaxOpts: gaxOptions,
988
+ headers: injectedHeaders,
989
+ });
990
+ };
991
+ const retryableCodes = [google_gax_1.grpc.status.UNAVAILABLE];
992
+ const wrappedMakeRequest = this._wrapWithIdWaiter(makeRequest);
993
+ const startTime = Date.now();
994
+ const timeout = gaxOptions?.timeout ?? Infinity;
995
+ const executeRequest = () => {
996
+ const requestStream = this.id ? makeRequest() : wrappedMakeRequest();
997
+ const onError = (err) => {
998
+ const elapsed = Date.now() - startTime;
999
+ let maxRetries = Infinity;
1000
+ if (maxResumeRetries !== undefined) {
1001
+ maxRetries = maxResumeRetries;
1002
+ }
1003
+ else if (timeout === Infinity) {
1004
+ maxRetries = 10;
1005
+ }
1006
+ if (elapsed < timeout &&
1007
+ attempt <= maxRetries &&
1008
+ err.code &&
1009
+ (retryableCodes.includes(err.code) || (0, transaction_runner_1.isRetryableInternalError)(err))) {
1010
+ requestStream.removeAllListeners();
1011
+ requestStream.on('error', () => { });
1012
+ requestStream.destroy();
1013
+ setImmediate(() => {
1014
+ executeRequest();
1015
+ });
1016
+ return;
1017
+ }
1018
+ const wasAborted = isErrorAborted(err);
1019
+ if (!this.id && this._useInRunner && !wasAborted) {
1020
+ streamSpan.addEvent('Stream broken. Safe to retry');
1021
+ void this.begin();
1022
+ }
1023
+ else if (wasAborted) {
1024
+ streamSpan.addEvent('Stream broken. Not safe to retry', {
1025
+ 'transaction.id': this.id?.toString(),
1026
+ });
1027
+ }
1028
+ const finalError = elapsed >= timeout ? new transaction_runner_1.DeadlineError(err) : err;
1029
+ complete(finalError);
1030
+ };
1031
+ const onEnd = () => {
1032
+ requestStream.removeListener('error', onError);
1033
+ complete(null, []);
1034
+ };
1035
+ const onData = (firstChunk) => {
1036
+ requestStream.removeListener('error', onError);
1037
+ requestStream.removeListener('end', onEnd);
1038
+ if (firstChunk.last && !firstChunk.chunkedValue) {
1039
+ // ⚡ FAST-PATH: Complete result in single chunk!
1040
+ if (firstChunk.metadata?.transaction && !this.id) {
1041
+ this._update(firstChunk.metadata.transaction, streamSpan);
1042
+ }
1043
+ this._updatePrecommitToken(firstChunk);
1044
+ let rows;
1045
+ try {
1046
+ rows = (0, partial_result_stream_1.decodeRowsDirect)(firstChunk, {
1047
+ json,
1048
+ jsonOptions,
1049
+ columnsMetadata,
1050
+ });
1051
+ }
1052
+ catch (decodeErr) {
1053
+ requestStream.removeAllListeners();
1054
+ requestStream.on('error', () => { });
1055
+ requestStream.destroy();
1056
+ complete(decodeErr, [], undefined, firstChunk.metadata || undefined);
1057
+ return;
1058
+ }
1059
+ // Query completed successfully. Do not cancel the gRPC call; allow it
1060
+ // to drain remaining trailers/EOF in the background so it is not marked
1061
+ // CANCELLED by Spanner or Cloud Monitoring.
1062
+ requestStream.removeAllListeners('data');
1063
+ requestStream.removeAllListeners('error');
1064
+ requestStream.on('error', () => { });
1065
+ requestStream.resume();
1066
+ complete(null, rows, firstChunk.stats || undefined, firstChunk.metadata || undefined);
1067
+ return;
1068
+ }
1069
+ // 🌊 FALLBACK PATH: Multi-chunk query!
1070
+ if (firstChunk.metadata?.transaction && !this.id) {
1071
+ this._update(firstChunk.metadata.transaction, streamSpan);
1072
+ }
1073
+ this._updatePrecommitToken(firstChunk);
1074
+ requestStream.removeAllListeners('data');
1075
+ requestStream.removeAllListeners('error');
1076
+ const replayStream = new stream_1.PassThrough({ objectMode: true });
1077
+ replayStream.write(firstChunk);
1078
+ requestStream.pipe(replayStream);
1079
+ requestStream.on('error', err => {
1080
+ replayStream.destroy(err);
1081
+ });
1082
+ replayStream.on('close', () => {
1083
+ if (!requestStream.destroyed) {
1084
+ if (requestStream.readableEnded) {
1085
+ requestStream.resume();
1086
+ }
1087
+ else {
1088
+ requestStream.destroy();
1089
+ }
1090
+ }
1091
+ });
1092
+ let initialStream = replayStream;
1093
+ const fallbackMakeRequest = (resumeToken) => {
1094
+ if (!resumeToken && initialStream) {
1095
+ const stream = initialStream;
1096
+ initialStream = null;
1097
+ return stream;
1098
+ }
1099
+ return makeRequest(resumeToken);
1100
+ };
1101
+ const rows = [];
1102
+ let stats;
1103
+ let metadata;
1104
+ const fallbackStream = (0, partial_result_stream_1.partialResultStream)(fallbackMakeRequest, {
1105
+ json,
1106
+ jsonOptions,
1107
+ maxResumeRetries,
1108
+ columnsMetadata,
1109
+ gaxOptions,
1110
+ });
1111
+ fallbackStream
1112
+ .on('response', response => {
1113
+ this._updatePrecommitToken(response);
1114
+ if (response.metadata?.transaction && !this.id) {
1115
+ this._update(response.metadata.transaction, streamSpan);
1116
+ }
1117
+ if (response.metadata) {
1118
+ metadata = response.metadata;
1119
+ }
1120
+ })
1121
+ .on('data', row => rows.push(row))
1122
+ .on('stats', _stats => (stats = _stats))
1123
+ .on('error', err => complete(err, rows, stats, metadata))
1124
+ .on('end', () => complete(null, rows, stats, metadata));
1125
+ };
1126
+ requestStream.once('error', onError);
1127
+ requestStream.once('data', onData);
1128
+ requestStream.once('end', onEnd);
1129
+ };
1130
+ executeRequest();
1131
+ });
1132
+ }
830
1133
  /**
831
1134
  * ExecuteSql request options. This includes all standard ExecuteSqlRequest
832
1135
  * options as well as several convenience properties.
@@ -1231,10 +1534,17 @@ class Snapshot extends events_1.EventEmitter {
1231
1534
  }
1232
1535
  // Queue subsequent requests.
1233
1536
  return (resumeToken) => {
1537
+ if (this.id) {
1538
+ return makeRequest(resumeToken);
1539
+ }
1234
1540
  const streamProxy = new stream_1.Readable({
1235
1541
  read() { },
1236
1542
  });
1237
- this._waitingRequests.push(() => {
1543
+ this._waitingRequests.push((err) => {
1544
+ if (err) {
1545
+ streamProxy.destroy(err);
1546
+ return;
1547
+ }
1238
1548
  makeRequest(resumeToken)
1239
1549
  .on('data', chunk => streamProxy.emit('data', chunk))
1240
1550
  .on('error', err => streamProxy.emit('error', err))
@@ -1243,10 +1553,10 @@ class Snapshot extends events_1.EventEmitter {
1243
1553
  return streamProxy;
1244
1554
  };
1245
1555
  }
1246
- _releaseWaitingRequests() {
1556
+ _releaseWaitingRequests(err) {
1247
1557
  while (this._waitingRequests.length > 0) {
1248
1558
  const request = this._waitingRequests.shift();
1249
- request?.();
1559
+ request?.(err);
1250
1560
  }
1251
1561
  }
1252
1562
  /**
@@ -1553,7 +1863,8 @@ class Transaction extends Dml {
1553
1863
  if (this.session.parent.isMuxEnabledForRW_) {
1554
1864
  this._setMutationKey(mutations);
1555
1865
  }
1556
- this.begin().then(() => {
1866
+ this.begin()
1867
+ .then(() => {
1557
1868
  this.commit(options, (err, resp) => {
1558
1869
  if (err) {
1559
1870
  (0, instrument_1.setSpanError)(span, err);
@@ -1561,7 +1872,9 @@ class Transaction extends Dml {
1561
1872
  span.end();
1562
1873
  callback(err, resp);
1563
1874
  });
1564
- }, err => {
1875
+ return null;
1876
+ })
1877
+ .catch(err => {
1565
1878
  (0, instrument_1.setSpanError)(span, err);
1566
1879
  span.end();
1567
1880
  callback(err, null);
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.12.0",
4
+ "version": "8.13.0",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Google Inc.",
7
7
  "engines": {
@@ -32,7 +32,7 @@
32
32
  ],
33
33
  "scripts": {
34
34
  "docs": "jsdoc -c .jsdoc.js",
35
- "predocs": "npm run compile",
35
+ "predocs": "pnpm run compile",
36
36
  "lint": "gts check",
37
37
  "system-test": "mocha build/system-test --timeout 1600000",
38
38
  "observability-test": "mocha build/observability-test --timeout 1600000",
@@ -43,9 +43,9 @@
43
43
  "clean": "gts clean",
44
44
  "compile": "tsc -p . && cp -r protos build && cp -r test/data build/test",
45
45
  "prepare": "cp -r protos build && npm run compile",
46
- "pretest": "npm run compile",
47
- "presystem-test": "npm run compile",
48
- "preobservability-test": "npm run compile",
46
+ "pretest": "pnpm run compile",
47
+ "presystem-test": "pnpm run compile",
48
+ "preobservability-test": "pnpm run compile",
49
49
  "benchwrapper": "node bin/benchwrapper.js",
50
50
  "precompile": "gts clean",
51
51
  "coverage": "c8 mocha build/test build/test/common && c8 report --check-coverage"