@google-cloud/spanner 7.18.0 → 7.19.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 (84) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/README.md +1 -0
  3. package/build/protos/google/spanner/admin/database/v1/backup.proto +773 -0
  4. package/build/protos/google/spanner/admin/database/v1/backup_schedule.proto +230 -0
  5. package/build/protos/google/spanner/admin/database/v1/common.proto +132 -0
  6. package/build/protos/google/spanner/admin/database/v1/spanner_database_admin.proto +1279 -0
  7. package/build/protos/google/spanner/admin/instance/v1/common.proto +64 -0
  8. package/build/protos/google/spanner/admin/instance/v1/spanner_instance_admin.proto +2110 -0
  9. package/build/protos/google/spanner/executor/v1/cloud_executor.proto +1520 -0
  10. package/build/protos/google/spanner/v1/commit_response.proto +59 -0
  11. package/build/protos/google/spanner/v1/keys.proto +163 -0
  12. package/build/protos/google/spanner/v1/mutation.proto +107 -0
  13. package/build/protos/google/spanner/v1/query_plan.proto +128 -0
  14. package/build/protos/google/spanner/v1/result_set.proto +237 -0
  15. package/build/protos/google/spanner/v1/spanner.proto +1389 -0
  16. package/build/protos/google/spanner/v1/transaction.proto +622 -0
  17. package/build/protos/google/spanner/v1/type.proto +214 -0
  18. package/build/protos/protos.d.ts +39869 -0
  19. package/build/protos/protos.js +101659 -0
  20. package/build/protos/protos.json +10391 -0
  21. package/build/src/backup.d.ts +349 -0
  22. package/build/src/backup.js +246 -0
  23. package/build/src/batch-transaction.d.ts +247 -0
  24. package/build/src/batch-transaction.js +384 -0
  25. package/build/src/codec.d.ts +362 -0
  26. package/build/src/codec.js +791 -0
  27. package/build/src/common-grpc/service-object.d.ts +80 -0
  28. package/build/src/common-grpc/service-object.js +101 -0
  29. package/build/src/common-grpc/service.d.ts +445 -0
  30. package/build/src/common-grpc/service.js +826 -0
  31. package/build/src/common.d.ts +66 -0
  32. package/build/src/common.js +54 -0
  33. package/build/src/database.d.ts +2103 -0
  34. package/build/src/database.js +1660 -0
  35. package/build/src/extra_proto_list.json +1 -0
  36. package/build/src/helper.d.ts +45 -0
  37. package/build/src/helper.js +71 -0
  38. package/build/src/index.d.ts +1195 -0
  39. package/build/src/index.js +1059 -0
  40. package/build/src/instance-config.d.ts +294 -0
  41. package/build/src/instance-config.js +216 -0
  42. package/build/src/instance.d.ts +832 -0
  43. package/build/src/instance.js +781 -0
  44. package/build/src/instrument.d.ts +85 -0
  45. package/build/src/instrument.js +215 -0
  46. package/build/src/multiplexed-session.d.ts +135 -0
  47. package/build/src/multiplexed-session.js +194 -0
  48. package/build/src/partial-result-stream.d.ts +253 -0
  49. package/build/src/partial-result-stream.js +400 -0
  50. package/build/src/request_id_header.d.ts +41 -0
  51. package/build/src/request_id_header.js +138 -0
  52. package/build/src/session-factory.d.ts +115 -0
  53. package/build/src/session-factory.js +106 -0
  54. package/build/src/session-pool.d.ts +471 -0
  55. package/build/src/session-pool.js +765 -0
  56. package/build/src/session.d.ts +258 -0
  57. package/build/src/session.js +348 -0
  58. package/build/src/spanner_grpc_config.json +92 -0
  59. package/build/src/table.d.ts +831 -0
  60. package/build/src/table.js +277 -0
  61. package/build/src/transaction-runner.d.ts +185 -0
  62. package/build/src/transaction-runner.js +282 -0
  63. package/build/src/transaction.d.ts +1691 -0
  64. package/build/src/transaction.js +2003 -0
  65. package/build/src/v1/database_admin_client.d.ts +2332 -0
  66. package/build/src/v1/database_admin_client.js +2364 -0
  67. package/build/src/v1/database_admin_client_config.json +165 -0
  68. package/build/src/v1/database_admin_proto_list.json +6 -0
  69. package/build/src/v1/gapic_metadata.json +27 -0
  70. package/build/src/v1/index.d.ts +4 -0
  71. package/build/src/v1/index.js +29 -0
  72. package/build/src/v1/instance_admin_client.d.ts +1985 -0
  73. package/build/src/v1/instance_admin_client.js +1768 -0
  74. package/build/src/v1/instance_admin_client_config.json +129 -0
  75. package/build/src/v1/instance_admin_proto_list.json +4 -0
  76. package/build/src/v1/spanner_client.d.ts +1250 -0
  77. package/build/src/v1/spanner_client.js +1086 -0
  78. package/build/src/v1/spanner_client_config.json +119 -0
  79. package/build/src/v1/spanner_executor_proxy_client.d.ts +418 -0
  80. package/build/src/v1/spanner_executor_proxy_client.js +706 -0
  81. package/build/src/v1/spanner_executor_proxy_client_config.json +30 -0
  82. package/build/src/v1/spanner_executor_proxy_proto_list.json +14 -0
  83. package/build/src/v1/spanner_proto_list.json +10 -0
  84. package/package.json +1 -1
@@ -0,0 +1,253 @@
1
+ /*!
2
+ * Copyright 2016 Google Inc. All Rights Reserved.
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
+ * http://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
+ */
16
+ import { Readable, Transform } from 'stream';
17
+ import { CallOptions } from 'google-gax';
18
+ import { JSONOptions, Json, Field, Value } from './codec';
19
+ import { google } from '../protos/protos';
20
+ export type ResumeToken = string | Uint8Array;
21
+ /**
22
+ * @callback RequestFunction
23
+ * @param {string} [resumeToken] The token used to resume getting results.
24
+ * @returns {Stream}
25
+ */
26
+ interface RequestFunction {
27
+ (resumeToken?: ResumeToken): Readable;
28
+ }
29
+ /**
30
+ * @typedef RowOptions
31
+ * @property {boolean} [json=false] Indicates if the Row objects should be
32
+ * formatted into JSON.
33
+ * @property {JSONOptions} [jsonOptions] JSON options.
34
+ * @property {number} [maxResumeRetries=20] The maximum number of times that the
35
+ * stream will retry to push data downstream, when the downstream indicates
36
+ * that it is not ready for any more data. Increase this value if you
37
+ * experience 'Stream is still not ready to receive data' errors as a
38
+ * result of a slow writer in your receiving stream.
39
+ * @property {object} [columnsMetadata] An object map that can be used to pass
40
+ * additional properties for each column type which can help in deserializing
41
+ * the data coming from backend. (Eg: We need to pass Proto Function and Enum
42
+ * map to deserialize proto messages and enums, respectively.)
43
+ */
44
+ export interface RowOptions {
45
+ json?: boolean;
46
+ jsonOptions?: JSONOptions;
47
+ maxResumeRetries?: number;
48
+ /**
49
+ * An object where column names as keys and custom objects as corresponding
50
+ * values for deserialization. It's specifically useful for data types like
51
+ * protobuf where deserialization logic is on user-specific code. When provided,
52
+ * the custom object enables deserialization of backend-received column data.
53
+ * If not provided, data remains serialized as buffer for Proto Messages and
54
+ * integer for Proto Enums.
55
+ *
56
+ * @example
57
+ * To obtain Proto Messages and Proto Enums as JSON objects, you must supply
58
+ * additional metadata. This metadata should include the protobufjs-cli
59
+ * generated proto message function and enum object. It encompasses the essential
60
+ * logic for proper data deserialization.
61
+ *
62
+ * Eg: To read data from Proto Columns in json format using DQL, you should pass
63
+ * columnsMetadata where key is the name of the column and value is the protobufjs-cli
64
+ * generated proto message function and enum object.
65
+ *
66
+ * const query = {
67
+ * sql: `SELECT SingerId,
68
+ * FirstName,
69
+ * LastName,
70
+ * SingerInfo,
71
+ * SingerGenre,
72
+ * SingerInfoArray,
73
+ * SingerGenreArray
74
+ * FROM Singers
75
+ * WHERE SingerId = 6`,
76
+ * columnsMetadata: {
77
+ * SingerInfo: music.SingerInfo,
78
+ * SingerInfoArray: music.SingerInfo,
79
+ * SingerGenre: music.Genre,
80
+ * SingerGenreArray: music.Genre,
81
+ * },
82
+ * };
83
+ */
84
+ columnsMetadata?: object;
85
+ gaxOptions?: CallOptions;
86
+ }
87
+ /**
88
+ * By default rows are an Array of values in the form of objects containing
89
+ * `name` and `value` properties.
90
+ *
91
+ * If you prefer plain objects, you can use the {@link Row#toJSON} method.
92
+ * NOTE: If you have duplicate field names only the last field will be present.
93
+ *
94
+ * @typedef {Array.<{name: string, value}>} Row
95
+ */
96
+ export interface Row extends Array<Field> {
97
+ /**
98
+ * Converts the Row object into a pojo (plain old JavaScript object).
99
+ *
100
+ * @memberof Row
101
+ * @name toJSON
102
+ *
103
+ * @param {JSONOptions} [options] JSON options.
104
+ * @returns {object}
105
+ */
106
+ toJSON(options?: JSONOptions): Json;
107
+ }
108
+ /**
109
+ * @callback PartialResultStream~rowCallback
110
+ * @param {Row|object} row The row data.
111
+ */
112
+ interface RowCallback {
113
+ (row: Row | Json): void;
114
+ }
115
+ /**
116
+ * @callback PartialResultStream~statsCallback
117
+ * @param {object} stats The result stats.
118
+ */
119
+ interface StatsCallback {
120
+ (stats: google.spanner.v1.ResultSetStats): void;
121
+ }
122
+ /**
123
+ * @callback PartialResultStream~responseCallback
124
+ * @param {object} response The full API response.
125
+ */
126
+ interface ResponseCallback {
127
+ (response: google.spanner.v1.PartialResultSet): void;
128
+ }
129
+ interface ResultEvents {
130
+ addListener(event: 'data', listener: RowCallback): this;
131
+ addListener(event: 'stats', listener: StatsCallback): this;
132
+ addListener(event: 'response', listener: ResponseCallback): this;
133
+ emit(event: 'data', data: Row | Json): boolean;
134
+ emit(event: 'stats', data: google.spanner.v1.ResultSetStats): boolean;
135
+ emit(event: 'response', data: google.spanner.v1.PartialResultSet): boolean;
136
+ on(event: 'data', listener: RowCallback): this;
137
+ on(event: 'stats', listener: StatsCallback): this;
138
+ on(event: 'response', listener: ResponseCallback): this;
139
+ once(event: 'data', listener: RowCallback): this;
140
+ once(event: 'stats', listener: StatsCallback): this;
141
+ once(event: 'response', listener: ResponseCallback): this;
142
+ prependListener(event: 'data', listener: RowCallback): this;
143
+ prependListener(event: 'stats', listener: StatsCallback): this;
144
+ prependListener(event: 'response', listener: ResponseCallback): this;
145
+ prependOnceListener(event: 'data', listener: RowCallback): this;
146
+ prependOnceListener(event: 'stats', listener: StatsCallback): this;
147
+ prependOnceListener(event: 'response', listener: ResponseCallback): this;
148
+ }
149
+ /**
150
+ * The PartialResultStream transforms partial result set objects into Row
151
+ * objects.
152
+ *
153
+ * @class
154
+ * @extends {Transform}
155
+ *
156
+ * @param {RowOptions} [options] The row options.
157
+ */
158
+ export declare class PartialResultStream extends Transform implements ResultEvents {
159
+ private _destroyed;
160
+ private _fields;
161
+ private _options;
162
+ private _pendingValue?;
163
+ private _pendingValueForResume?;
164
+ private _values;
165
+ private _numPushFailed;
166
+ constructor(options?: {});
167
+ /**
168
+ * Destroys the stream.
169
+ *
170
+ * @param {Error} [err] Optional error to destroy stream with.
171
+ */
172
+ destroy(err?: Error): this;
173
+ /**
174
+ * Processes each chunk.
175
+ *
176
+ * @private
177
+ *
178
+ * @param {object} chunk The partial result set.
179
+ * @param {string} encoding Chunk encoding (Not used in object streams).
180
+ * @param {function} next Function to be called upon completion.
181
+ */
182
+ _transform(chunk: google.spanner.v1.PartialResultSet, enc: string, next: Function): void;
183
+ private _tryResume;
184
+ _resetPendingValues(): void;
185
+ /**
186
+ * Manages any chunked values.
187
+ *
188
+ * @private
189
+ *
190
+ * @param {object} chunk The partial result set.
191
+ */
192
+ private _addChunk;
193
+ /**
194
+ * Manages complete values, pushing a completed row into the stream once all
195
+ * values have been received.
196
+ *
197
+ * @private
198
+ *
199
+ * @param {*} value The complete value.
200
+ */
201
+ private _addValue;
202
+ /**
203
+ * Converts an array of values into a row.
204
+ *
205
+ * @private
206
+ *
207
+ * @param {Array.<*>} values The row values.
208
+ * @returns {Row}
209
+ */
210
+ private _createRow;
211
+ /**
212
+ * Attempts to merge chunked values together.
213
+ *
214
+ * @static
215
+ * @private
216
+ *
217
+ * @param {object} type The value type.
218
+ * @param {*} head The head of the combined value.
219
+ * @param {*} tail The tail of the combined value.
220
+ * @returns {Array.<*>}
221
+ */
222
+ static merge(type: google.spanner.v1.Type, head: Value, tail: Value): Value[];
223
+ /**
224
+ * Attempts to merge chunked lists together.
225
+ *
226
+ * @static
227
+ * @private
228
+ *
229
+ * @param {object} type The list type.
230
+ * @param {Array.<*>} head The beginning of the list.
231
+ * @param {Array.<*>} tail The end of the list.
232
+ * @returns {Array.<*>}
233
+ */
234
+ static mergeLists(type: google.spanner.v1.Type, head: Value[], tail: Value[]): Value[];
235
+ }
236
+ /**
237
+ * Rows returned from queries may be chunked, requiring them to be stitched
238
+ * together. This function returns a stream that will properly assemble these
239
+ * rows, as well as retry after an error. Rows are only emitted if they hit a
240
+ * "checkpoint", which is when a `resumeToken` is returned from the API. Without
241
+ * that token, it's unsafe for the query to be retried, as we wouldn't want to
242
+ * emit the same data multiple times.
243
+ *
244
+ * @private
245
+ *
246
+ * @param {RequestFunction} requestFn The function that makes an API request. It
247
+ * will receive one argument, `resumeToken`, which should be used however is
248
+ * necessary to send to the API for additional requests.
249
+ * @param {RowOptions} [options] Options for formatting rows.
250
+ * @returns {PartialResultStream}
251
+ */
252
+ export declare function partialResultStream(requestFn: RequestFunction, options?: RowOptions): PartialResultStream;
253
+ export {};
@@ -0,0 +1,400 @@
1
+ "use strict";
2
+ /*!
3
+ * Copyright 2016 Google Inc. All Rights Reserved.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports.PartialResultStream = void 0;
19
+ exports.partialResultStream = partialResultStream;
20
+ const service_1 = require("./common-grpc/service");
21
+ const checkpointStream = require("checkpoint-stream");
22
+ const eventsIntercept = require("events-intercept");
23
+ const is = require("is");
24
+ const mergeStream = require("merge-stream");
25
+ const stream_1 = require("stream");
26
+ const streamEvents = require("stream-events");
27
+ const google_gax_1 = require("google-gax");
28
+ const transaction_runner_1 = require("./transaction-runner");
29
+ const codec_1 = require("./codec");
30
+ const protos_1 = require("../protos/protos");
31
+ const stream = require("stream");
32
+ /**
33
+ * The PartialResultStream transforms partial result set objects into Row
34
+ * objects.
35
+ *
36
+ * @class
37
+ * @extends {Transform}
38
+ *
39
+ * @param {RowOptions} [options] The row options.
40
+ */
41
+ class PartialResultStream extends stream_1.Transform {
42
+ constructor(options = {}) {
43
+ super({ objectMode: true });
44
+ this._numPushFailed = 0;
45
+ this._destroyed = false;
46
+ this._options = Object.assign({ maxResumeRetries: 20 }, options);
47
+ this._values = [];
48
+ }
49
+ /**
50
+ * Destroys the stream.
51
+ *
52
+ * @param {Error} [err] Optional error to destroy stream with.
53
+ */
54
+ destroy(err) {
55
+ if (this._destroyed) {
56
+ return this;
57
+ }
58
+ this._destroyed = true;
59
+ process.nextTick(() => {
60
+ if (err) {
61
+ this.emit('error', err);
62
+ }
63
+ this.emit('close');
64
+ });
65
+ return this;
66
+ }
67
+ /**
68
+ * Processes each chunk.
69
+ *
70
+ * @private
71
+ *
72
+ * @param {object} chunk The partial result set.
73
+ * @param {string} encoding Chunk encoding (Not used in object streams).
74
+ * @param {function} next Function to be called upon completion.
75
+ */
76
+ _transform(chunk, enc, next) {
77
+ this.emit('response', chunk);
78
+ if (chunk.stats) {
79
+ this.emit('stats', chunk.stats);
80
+ }
81
+ if (!this._fields && chunk.metadata) {
82
+ this._fields = chunk.metadata.rowType
83
+ .fields;
84
+ }
85
+ let res = true;
86
+ if (!is.empty(chunk.values)) {
87
+ res = this._addChunk(chunk);
88
+ }
89
+ if (res) {
90
+ next();
91
+ }
92
+ else {
93
+ // Wait a little before we push any more data into the pipeline as a
94
+ // component downstream has indicated that a break is needed. Pause the
95
+ // request stream to prevent it from filling up the buffer while we are
96
+ // waiting.
97
+ // The stream will initially pause for 2ms, and then double the pause time
98
+ // for each new pause.
99
+ const initialPauseMs = 2;
100
+ setTimeout(() => {
101
+ this._tryResume(next, 2 * initialPauseMs);
102
+ }, initialPauseMs);
103
+ }
104
+ }
105
+ _tryResume(next, timeout) {
106
+ // Try to push an empty chunk to check whether more data can be accepted.
107
+ if (this.push(undefined)) {
108
+ this._numPushFailed = 0;
109
+ this.emit('resumed');
110
+ next();
111
+ }
112
+ else {
113
+ // Downstream returned false indicating that it is still not ready for
114
+ // more data.
115
+ this._numPushFailed++;
116
+ if (this._numPushFailed === this._options.maxResumeRetries) {
117
+ this.destroy(new Error(`Stream is still not ready to receive data after ${this._numPushFailed} attempts to resume.`));
118
+ return;
119
+ }
120
+ setTimeout(() => {
121
+ const nextTimeout = Math.min(timeout * 2, 1024);
122
+ this._tryResume(next, nextTimeout);
123
+ }, timeout);
124
+ }
125
+ }
126
+ _resetPendingValues() {
127
+ if (this._pendingValueForResume) {
128
+ this._pendingValue = this._pendingValueForResume;
129
+ }
130
+ else {
131
+ delete this._pendingValue;
132
+ }
133
+ }
134
+ /**
135
+ * Manages any chunked values.
136
+ *
137
+ * @private
138
+ *
139
+ * @param {object} chunk The partial result set.
140
+ */
141
+ _addChunk(chunk) {
142
+ const values = chunk.values.map(service_1.GrpcService.decodeValue_);
143
+ // If we have a chunk to merge, merge the values now.
144
+ if (this._pendingValue) {
145
+ const currentField = this._values.length % this._fields.length;
146
+ const field = this._fields[currentField];
147
+ const merged = PartialResultStream.merge(field.type, this._pendingValue, values.shift());
148
+ values.unshift(...merged);
149
+ delete this._pendingValue;
150
+ }
151
+ // If the chunk is chunked, store the last value for merging with the next
152
+ // chunk to be processed.
153
+ if (chunk.chunkedValue) {
154
+ this._pendingValue = values.pop();
155
+ if (_hasResumeToken(chunk)) {
156
+ this._pendingValueForResume = this._pendingValue;
157
+ }
158
+ }
159
+ else if (_hasResumeToken(chunk)) {
160
+ delete this._pendingValueForResume;
161
+ }
162
+ let res = true;
163
+ values.forEach(value => {
164
+ res = this._addValue(value) && res;
165
+ if (!res) {
166
+ this.emit('paused');
167
+ }
168
+ });
169
+ return res;
170
+ }
171
+ /**
172
+ * Manages complete values, pushing a completed row into the stream once all
173
+ * values have been received.
174
+ *
175
+ * @private
176
+ *
177
+ * @param {*} value The complete value.
178
+ */
179
+ _addValue(value) {
180
+ const values = this._values;
181
+ values.push(value);
182
+ if (values.length !== this._fields.length) {
183
+ return true;
184
+ }
185
+ this._values = [];
186
+ const row = this._createRow(values);
187
+ if (this._options.json) {
188
+ return this.push(row.toJSON(this._options.jsonOptions));
189
+ }
190
+ return this.push(row);
191
+ }
192
+ /**
193
+ * Converts an array of values into a row.
194
+ *
195
+ * @private
196
+ *
197
+ * @param {Array.<*>} values The row values.
198
+ * @returns {Row}
199
+ */
200
+ _createRow(values) {
201
+ const fields = values.map((value, index) => {
202
+ var _a;
203
+ const { name, type } = this._fields[index];
204
+ const columnMetadata = (_a = this._options.columnsMetadata) === null || _a === void 0 ? void 0 : _a[name];
205
+ return {
206
+ name,
207
+ value: codec_1.codec.decode(value, type, columnMetadata),
208
+ };
209
+ });
210
+ Object.defineProperty(fields, 'toJSON', {
211
+ value: (options) => {
212
+ return codec_1.codec.convertFieldsToJson(fields, options);
213
+ },
214
+ });
215
+ return fields;
216
+ }
217
+ /**
218
+ * Attempts to merge chunked values together.
219
+ *
220
+ * @static
221
+ * @private
222
+ *
223
+ * @param {object} type The value type.
224
+ * @param {*} head The head of the combined value.
225
+ * @param {*} tail The tail of the combined value.
226
+ * @returns {Array.<*>}
227
+ */
228
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
229
+ static merge(type, head, tail) {
230
+ if (type.code === protos_1.google.spanner.v1.TypeCode.ARRAY ||
231
+ type.code === 'ARRAY' ||
232
+ type.code === protos_1.google.spanner.v1.TypeCode.STRUCT ||
233
+ type.code === 'STRUCT') {
234
+ if (head === null || tail === null) {
235
+ return [head, tail];
236
+ }
237
+ return [PartialResultStream.mergeLists(type, head, tail)];
238
+ }
239
+ if (is.string(head) && is.string(tail)) {
240
+ return [head + tail];
241
+ }
242
+ return [head, tail];
243
+ }
244
+ /**
245
+ * Attempts to merge chunked lists together.
246
+ *
247
+ * @static
248
+ * @private
249
+ *
250
+ * @param {object} type The list type.
251
+ * @param {Array.<*>} head The beginning of the list.
252
+ * @param {Array.<*>} tail The end of the list.
253
+ * @returns {Array.<*>}
254
+ */
255
+ static mergeLists(type, head, tail) {
256
+ let listType;
257
+ if (type.code === 'ARRAY' ||
258
+ type.code === protos_1.google.spanner.v1.TypeCode.ARRAY) {
259
+ listType = type.arrayElementType;
260
+ }
261
+ else {
262
+ listType = type.structType.fields[head.length - 1]
263
+ .type;
264
+ }
265
+ const merged = PartialResultStream.merge(listType, head.pop(), tail.shift());
266
+ return [...head, ...merged, ...tail];
267
+ }
268
+ }
269
+ exports.PartialResultStream = PartialResultStream;
270
+ /**
271
+ * Rows returned from queries may be chunked, requiring them to be stitched
272
+ * together. This function returns a stream that will properly assemble these
273
+ * rows, as well as retry after an error. Rows are only emitted if they hit a
274
+ * "checkpoint", which is when a `resumeToken` is returned from the API. Without
275
+ * that token, it's unsafe for the query to be retried, as we wouldn't want to
276
+ * emit the same data multiple times.
277
+ *
278
+ * @private
279
+ *
280
+ * @param {RequestFunction} requestFn The function that makes an API request. It
281
+ * will receive one argument, `resumeToken`, which should be used however is
282
+ * necessary to send to the API for additional requests.
283
+ * @param {RowOptions} [options] Options for formatting rows.
284
+ * @returns {PartialResultStream}
285
+ */
286
+ function partialResultStream(requestFn, options) {
287
+ var _a, _b;
288
+ const retryableCodes = [google_gax_1.grpc.status.UNAVAILABLE];
289
+ const maxQueued = 10;
290
+ let lastResumeToken;
291
+ let lastRequestStream;
292
+ const startTime = Date.now();
293
+ const timeout = (_b = (_a = options === null || options === void 0 ? void 0 : options.gaxOptions) === null || _a === void 0 ? void 0 : _a.timeout) !== null && _b !== void 0 ? _b : Infinity;
294
+ // mergeStream allows multiple streams to be connected into one. This is good;
295
+ // if we need to retry a request and pipe more data to the user's stream.
296
+ // We also add an additional stream that can be used to flush any remaining
297
+ // items in the checkpoint stream that have been received, and that did not
298
+ // contain a resume token.
299
+ const requestsStream = mergeStream();
300
+ const flushStream = new stream.PassThrough({ objectMode: true });
301
+ requestsStream.add(flushStream);
302
+ const partialRSStream = new PartialResultStream(options);
303
+ const userStream = streamEvents(partialRSStream);
304
+ // We keep track of the number of PartialResultSets that did not include a
305
+ // resume token, as that is an indication whether it is safe to retry the
306
+ // stream halfway.
307
+ let withoutCheckpointCount = 0;
308
+ const batchAndSplitOnTokenStream = checkpointStream.obj({
309
+ maxQueued,
310
+ isCheckpointFn: (chunk) => {
311
+ const withCheckpoint = _hasResumeToken(chunk);
312
+ if (withCheckpoint) {
313
+ withoutCheckpointCount = 0;
314
+ }
315
+ else {
316
+ withoutCheckpointCount++;
317
+ }
318
+ return withCheckpoint;
319
+ },
320
+ });
321
+ // This listener ensures that the last request that executed successfully
322
+ // after one or more retries will end the requestsStream.
323
+ const endListener = () => {
324
+ setImmediate(() => {
325
+ // Push a fake PartialResultSet without any values but with a resume token
326
+ // into the stream to ensure that the checkpoint stream is emptied, and
327
+ // then push `null` to end the stream.
328
+ flushStream.push({ resumeToken: '_' });
329
+ flushStream.push(null);
330
+ requestsStream.end();
331
+ });
332
+ };
333
+ const makeRequest = () => {
334
+ if (is.defined(lastResumeToken) && lastResumeToken.length > 0) {
335
+ partialRSStream._resetPendingValues();
336
+ }
337
+ lastRequestStream = requestFn(lastResumeToken);
338
+ lastRequestStream.on('end', endListener);
339
+ requestsStream.add(lastRequestStream);
340
+ };
341
+ const retry = (err) => {
342
+ const elapsed = Date.now() - startTime;
343
+ if (elapsed >= timeout) {
344
+ // The timeout has reached so this will flush any rows the
345
+ // checkpoint stream has queued. After that, we will destroy the
346
+ // user's stream with the Deadline exceeded error.
347
+ setImmediate(() => batchAndSplitOnTokenStream.destroy(new transaction_runner_1.DeadlineError(err)));
348
+ return;
349
+ }
350
+ if (!(err.code &&
351
+ (retryableCodes.includes(err.code) || (0, transaction_runner_1.isRetryableInternalError)(err))) ||
352
+ // If we have received too many chunks without a resume token, it is not
353
+ // safe to retry.
354
+ withoutCheckpointCount > maxQueued) {
355
+ // This is not a retryable error so this will flush any rows the
356
+ // checkpoint stream has queued. After that, we will destroy the
357
+ // user's stream with the same error.
358
+ setImmediate(() => batchAndSplitOnTokenStream.destroy(err));
359
+ return;
360
+ }
361
+ if (lastRequestStream) {
362
+ lastRequestStream.removeListener('end', endListener);
363
+ lastRequestStream.destroy();
364
+ }
365
+ // Delay the retry until all the values that are already in the stream
366
+ // pipeline have been handled. This ensures that the checkpoint stream is
367
+ // reset to the correct point. Calling .reset() directly here could cause
368
+ // any values that are currently in the pipeline and that have not been
369
+ // handled yet, to be pushed twice into the entire stream.
370
+ setImmediate(() => {
371
+ // Empty queued rows on the checkpoint stream (will not emit them to user).
372
+ batchAndSplitOnTokenStream.reset();
373
+ makeRequest();
374
+ });
375
+ };
376
+ userStream.once('reading', makeRequest);
377
+ eventsIntercept.patch(requestsStream);
378
+ // need types for events-intercept
379
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
380
+ requestsStream.intercept('error', err =>
381
+ // Retry __after__ all pending data has been processed to ensure that the
382
+ // checkpoint stream is reset at the correct position.
383
+ setImmediate(() => retry(err)));
384
+ return (requestsStream
385
+ .pipe(batchAndSplitOnTokenStream)
386
+ // If we get this error, the checkpoint stream has flushed any rows
387
+ // it had queued. We can now destroy the user's stream, as our retry
388
+ // attempts are over.
389
+ .on('error', (err) => userStream.destroy(err))
390
+ .on('checkpoint', (row) => {
391
+ lastResumeToken = row.resumeToken;
392
+ })
393
+ .pipe(userStream)
394
+ .on('paused', () => requestsStream.pause())
395
+ .on('resumed', () => requestsStream.resume()));
396
+ }
397
+ function _hasResumeToken(chunk) {
398
+ return is.defined(chunk.resumeToken) && chunk.resumeToken.length > 0;
399
+ }
400
+ //# sourceMappingURL=partial-result-stream.js.map
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Copyright 2025 Google LLC. All Rights Reserved.
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
+ * http://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
+ */
16
+ import * as grpc from '@grpc/grpc-js';
17
+ declare const randIdForProcess: string;
18
+ declare const X_GOOG_SPANNER_REQUEST_ID_HEADER = "x-goog-spanner-request-id";
19
+ declare class AtomicCounter {
20
+ private readonly backingBuffer;
21
+ constructor(initialValue?: number);
22
+ increment(n?: number): number;
23
+ value(): number;
24
+ toString(): string;
25
+ reset(): void;
26
+ }
27
+ declare function craftRequestId(nthClientId: number, channelId: number, nthRequest: number, attempt: number): string;
28
+ export declare function resetNthClientId(): void;
29
+ declare function nextSpannerClientId(): number;
30
+ declare function newAtomicCounter(n?: number): AtomicCounter;
31
+ declare function injectRequestIDIntoError(config: any, err: Error): void;
32
+ declare function injectRequestIDIntoHeaders(headers: {
33
+ [k: string]: string;
34
+ }, session: any, nthRequest?: number, attempt?: number): {
35
+ [k: string]: string;
36
+ };
37
+ declare function nextNthRequest(database: any): number;
38
+ export interface RequestIDError extends grpc.ServiceError {
39
+ requestID: string;
40
+ }
41
+ export { AtomicCounter, X_GOOG_SPANNER_REQUEST_ID_HEADER, craftRequestId, injectRequestIDIntoError, injectRequestIDIntoHeaders, nextNthRequest, nextSpannerClientId, newAtomicCounter, randIdForProcess, };