@google-cloud/spanner 7.21.0 → 8.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/README.md +2 -0
  2. package/build/protos/google/spanner/admin/database/v1/backup.proto +1 -1
  3. package/build/protos/google/spanner/admin/database/v1/backup_schedule.proto +1 -1
  4. package/build/protos/google/spanner/admin/database/v1/common.proto +1 -1
  5. package/build/protos/google/spanner/admin/database/v1/spanner_database_admin.proto +36 -1
  6. package/build/protos/google/spanner/admin/instance/v1/common.proto +1 -1
  7. package/build/protos/google/spanner/admin/instance/v1/spanner_instance_admin.proto +1 -1
  8. package/build/protos/google/spanner/executor/v1/cloud_executor.proto +1 -1
  9. package/build/protos/google/spanner/v1/change_stream.proto +451 -0
  10. package/build/protos/google/spanner/v1/commit_response.proto +10 -5
  11. package/build/protos/google/spanner/v1/keys.proto +1 -1
  12. package/build/protos/google/spanner/v1/mutation.proto +1 -1
  13. package/build/protos/google/spanner/v1/query_plan.proto +1 -1
  14. package/build/protos/google/spanner/v1/result_set.proto +55 -49
  15. package/build/protos/google/spanner/v1/spanner.proto +1 -1
  16. package/build/protos/google/spanner/v1/transaction.proto +41 -357
  17. package/build/protos/google/spanner/v1/type.proto +1 -1
  18. package/build/protos/protos.d.ts +1577 -194
  19. package/build/protos/protos.js +3977 -288
  20. package/build/protos/protos.json +325 -3
  21. package/build/src/backup.js +7 -0
  22. package/build/src/batch-transaction.d.ts +48 -29
  23. package/build/src/batch-transaction.js +15 -100
  24. package/build/src/codec.js +63 -47
  25. package/build/src/common-grpc/service-object.js +1 -0
  26. package/build/src/common-grpc/service.js +35 -18
  27. package/build/src/common.d.ts +1 -0
  28. package/build/src/common.js +9 -1
  29. package/build/src/database.d.ts +1 -0
  30. package/build/src/database.js +54 -42
  31. package/build/src/helper.d.ts +99 -0
  32. package/build/src/helper.js +178 -0
  33. package/build/src/index.d.ts +33 -0
  34. package/build/src/index.js +202 -21
  35. package/build/src/instance-config.d.ts +1 -1
  36. package/build/src/instance-config.js +4 -0
  37. package/build/src/instance.js +12 -6
  38. package/build/src/instrument.js +5 -6
  39. package/build/src/metrics/constants.d.ts +36 -0
  40. package/build/src/metrics/constants.js +106 -0
  41. package/build/src/metrics/external-types.d.ts +20 -0
  42. package/build/src/metrics/external-types.js +32 -0
  43. package/build/src/metrics/interceptor.d.ts +13 -0
  44. package/build/src/metrics/interceptor.js +87 -0
  45. package/build/src/metrics/metrics-tracer-factory.d.ts +165 -0
  46. package/build/src/metrics/metrics-tracer-factory.js +389 -0
  47. package/build/src/metrics/metrics-tracer.d.ts +204 -0
  48. package/build/src/metrics/metrics-tracer.js +371 -0
  49. package/build/src/metrics/spanner-metrics-exporter.d.ts +35 -0
  50. package/build/src/metrics/spanner-metrics-exporter.js +119 -0
  51. package/build/src/metrics/transform.d.ts +144 -0
  52. package/build/src/metrics/transform.js +272 -0
  53. package/build/src/multiplexed-session.js +7 -1
  54. package/build/src/partial-result-stream.js +18 -10
  55. package/build/src/request_id_header.js +1 -0
  56. package/build/src/session-factory.d.ts +34 -0
  57. package/build/src/session-factory.js +35 -2
  58. package/build/src/session-pool.js +24 -8
  59. package/build/src/session.d.ts +0 -1
  60. package/build/src/session.js +7 -2
  61. package/build/src/table.js +6 -3
  62. package/build/src/transaction-runner.d.ts +1 -0
  63. package/build/src/transaction-runner.js +18 -2
  64. package/build/src/transaction.d.ts +42 -1
  65. package/build/src/transaction.js +258 -94
  66. package/build/src/v1/database_admin_client.d.ts +37 -2
  67. package/build/src/v1/database_admin_client.js +718 -168
  68. package/build/src/v1/database_admin_client_config.json +4 -0
  69. package/build/src/v1/instance_admin_client.d.ts +122 -1
  70. package/build/src/v1/instance_admin_client.js +765 -146
  71. package/build/src/v1/spanner_client.d.ts +2 -1
  72. package/build/src/v1/spanner_client.js +391 -85
  73. package/build/src/v1/spanner_executor_proxy_client.d.ts +2 -1
  74. package/build/src/v1/spanner_executor_proxy_client.js +41 -19
  75. package/build/src/v1/spanner_proto_list.json +1 -0
  76. package/package.json +64 -58
@@ -0,0 +1,272 @@
1
+ "use strict";
2
+ // Copyright 2025 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
+ // 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
+ Object.defineProperty(exports, "__esModule", { value: true });
16
+ exports._TEST_ONLY = void 0;
17
+ exports.transformResourceMetricToTimeSeriesArray = transformResourceMetricToTimeSeriesArray;
18
+ const sdk_metrics_1 = require("@opentelemetry/sdk-metrics");
19
+ const path = require("path");
20
+ const external_types_1 = require("./external-types");
21
+ const constants_1 = require("./constants");
22
+ const metrics_tracer_factory_1 = require("./metrics-tracer-factory");
23
+ /** Transforms a OpenTelemetry instrument type to a GCM MetricKind. */
24
+ function _transformMetricKind(metric) {
25
+ switch (metric.dataPointType) {
26
+ case sdk_metrics_1.DataPointType.SUM:
27
+ return metric.isMonotonic ? external_types_1.MetricKind.CUMULATIVE : external_types_1.MetricKind.GAUGE;
28
+ case sdk_metrics_1.DataPointType.GAUGE:
29
+ return external_types_1.MetricKind.GAUGE;
30
+ case sdk_metrics_1.DataPointType.HISTOGRAM:
31
+ case sdk_metrics_1.DataPointType.EXPONENTIAL_HISTOGRAM:
32
+ return external_types_1.MetricKind.CUMULATIVE;
33
+ default:
34
+ exhaust(metric);
35
+ // No logging needed as it will be done in transformPoints()
36
+ return external_types_1.MetricKind.UNSPECIFIED;
37
+ }
38
+ }
39
+ /** Transforms resource to Google Cloud Monitoring monitored resource */
40
+ function _transformResource(labels) {
41
+ return {
42
+ type: constants_1.SPANNER_RESOURCE_TYPE,
43
+ labels: labels,
44
+ };
45
+ }
46
+ /** Transforms a OpenTelemetry ValueType to a GCM ValueType. */
47
+ function _transformValueType(metric) {
48
+ const { dataPointType, descriptor: { name }, } = metric;
49
+ if (dataPointType === sdk_metrics_1.DataPointType.HISTOGRAM ||
50
+ dataPointType === sdk_metrics_1.DataPointType.EXPONENTIAL_HISTOGRAM) {
51
+ return external_types_1.ValueType.DISTRIBUTION;
52
+ }
53
+ else if (dataPointType === sdk_metrics_1.DataPointType.SUM) {
54
+ return external_types_1.ValueType.INT64;
55
+ }
56
+ else if (dataPointType === sdk_metrics_1.DataPointType.GAUGE) {
57
+ return external_types_1.ValueType.DOUBLE;
58
+ }
59
+ console.warn('Encountered unexpected metric %s', name);
60
+ return external_types_1.ValueType.VALUE_TYPE_UNSPECIFIED;
61
+ }
62
+ /**
63
+ * Convert the metrics data to a list of Google Cloud Monitoring time series.
64
+ */
65
+ function transformResourceMetricToTimeSeriesArray(resourceMetrics) {
66
+ const resource = resourceMetrics?.resource;
67
+ const scopeMetrics = resourceMetrics?.scopeMetrics;
68
+ if (!scopeMetrics)
69
+ return [];
70
+ return (scopeMetrics
71
+ // Only keep those whose scope.name matches 'spanner-nodejs'.
72
+ .filter(({ scope: { name } }) => name === constants_1.SPANNER_METER_NAME)
73
+ // Takes each metric array and flattens it into one array
74
+ .flatMap(({ metrics }) =>
75
+ // Only keeps metrics that match our spanner metric names
76
+ metrics.filter(metric => constants_1.METRIC_NAMES.has(metric.descriptor.name)))
77
+ // Flatmap the data points in each metric to create a TimeSeries for each point
78
+ .flatMap(metric => metric.dataPoints.flatMap(dataPoint => _createTimeSeries(metric, dataPoint, resource))));
79
+ }
80
+ /**
81
+ * Creates a GCM TimeSeries.
82
+ */
83
+ function _createTimeSeries(metric, dataPoint, resource) {
84
+ const type = path.posix.join(constants_1.CLIENT_METRICS_PREFIX, metric.descriptor.name);
85
+ const resourceLabels = resource
86
+ ? _extractLabels(resource)
87
+ : { metricLabels: {}, monitoredResourceLabels: {} };
88
+ const dataLabels = _extractLabels(dataPoint);
89
+ const labels = {
90
+ ...resourceLabels.metricLabels,
91
+ ...dataLabels.metricLabels,
92
+ };
93
+ const monitoredResourceLabels = {
94
+ ...resourceLabels.monitoredResourceLabels,
95
+ ...dataLabels.monitoredResourceLabels,
96
+ };
97
+ const transformedMetric = {
98
+ type,
99
+ labels,
100
+ };
101
+ return {
102
+ metric: transformedMetric,
103
+ resource: _transformResource(monitoredResourceLabels),
104
+ metricKind: _transformMetricKind(metric),
105
+ valueType: _transformValueType(metric),
106
+ points: [_transformPoint(metric, dataPoint)],
107
+ unit: metric.descriptor.unit,
108
+ };
109
+ }
110
+ /**
111
+ * Transform timeseries's point, so that metric can be uploaded to GCM.
112
+ */
113
+ function _transformPoint(metric, dataPoint) {
114
+ switch (metric.dataPointType) {
115
+ case sdk_metrics_1.DataPointType.SUM:
116
+ case sdk_metrics_1.DataPointType.GAUGE:
117
+ return {
118
+ value: _transformNumberValue(_transformValueType(metric), dataPoint.value),
119
+ interval: {
120
+ // Add start time for non-gauge points
121
+ ...(metric.dataPointType === sdk_metrics_1.DataPointType.SUM && metric.isMonotonic
122
+ ? {
123
+ startTime: _formatHrTimeToGcmTime(dataPoint.startTime),
124
+ }
125
+ : null),
126
+ endTime: _formatHrTimeToGcmTime(dataPoint.endTime),
127
+ },
128
+ };
129
+ case sdk_metrics_1.DataPointType.HISTOGRAM:
130
+ return {
131
+ value: _transformHistogramValue(dataPoint.value),
132
+ interval: {
133
+ startTime: _formatHrTimeToGcmTime(dataPoint.startTime),
134
+ endTime: _formatHrTimeToGcmTime(dataPoint.endTime),
135
+ },
136
+ };
137
+ case sdk_metrics_1.DataPointType.EXPONENTIAL_HISTOGRAM:
138
+ return {
139
+ value: _transformExponentialHistogramValue(dataPoint.value),
140
+ interval: {
141
+ startTime: _formatHrTimeToGcmTime(dataPoint.startTime),
142
+ endTime: _formatHrTimeToGcmTime(dataPoint.endTime),
143
+ },
144
+ };
145
+ default:
146
+ exhaust(metric);
147
+ return {
148
+ value: dataPoint.value,
149
+ interval: {
150
+ endTime: _formatHrTimeToGcmTime(dataPoint.endTime),
151
+ },
152
+ };
153
+ }
154
+ }
155
+ /** Extracts metric and monitored resource labels from data point */
156
+ function _extractLabels({ attributes = {} }) {
157
+ const factory = metrics_tracer_factory_1.MetricsTracerFactory.getInstance();
158
+ // Add Client name and Client UID metric labels
159
+ attributes[constants_1.METRIC_LABEL_KEY_CLIENT_UID] =
160
+ factory?.clientUid ?? constants_1.UNKNOWN_ATTRIBUTE;
161
+ attributes[constants_1.METRIC_LABEL_KEY_CLIENT_NAME] =
162
+ factory?.clientName ?? constants_1.UNKNOWN_ATTRIBUTE;
163
+ return Object.entries(attributes).reduce((result, [key, value]) => {
164
+ const normalizedKey = _normalizeLabelKey(key);
165
+ const val = value?.toString();
166
+ if (constants_1.METRIC_LABELS.has(key))
167
+ result.metricLabels[normalizedKey] = val;
168
+ if (constants_1.MONITORED_RESOURCE_LABELS.has(key))
169
+ result.monitoredResourceLabels[normalizedKey] = val;
170
+ return result;
171
+ }, { metricLabels: {}, monitoredResourceLabels: {} });
172
+ }
173
+ function _normalizeLabelKey(key) {
174
+ // Replace characters which are not Letter or Decimal_Number unicode category with "_", see
175
+ // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Unicode_Property_Escapes
176
+ //
177
+ // Reimplementation of reference impl in Go:
178
+ // https://github.com/GoogleCloudPlatform/opentelemetry-operations-go/blob/e955c204f4f2bfdc92ff0ad52786232b975efcc2/exporter/metric/metric.go#L595-L604
179
+ let sanitized = key.replace(/[^\p{Letter}\p{Decimal_Number}_]/gu, '_');
180
+ if (sanitized[0].match(/\p{Decimal_Number}/u)) {
181
+ sanitized = 'key_' + sanitized;
182
+ }
183
+ return sanitized;
184
+ }
185
+ /** Transforms a OpenTelemetry Point's value to a GCM Point value. */
186
+ function _transformNumberValue(valueType, value) {
187
+ if (valueType === external_types_1.ValueType.INT64) {
188
+ return { int64Value: Math.round(value).toString() };
189
+ }
190
+ else if (valueType === external_types_1.ValueType.DOUBLE) {
191
+ const doubleString = Number.isInteger(value)
192
+ ? `${value}.0`
193
+ : value.toString();
194
+ return { doubleValue: doubleString };
195
+ }
196
+ throw Error(`unsupported value type: ${valueType}`);
197
+ }
198
+ function _transformHistogramValue(value) {
199
+ return {
200
+ distributionValue: {
201
+ // sumOfSquaredDeviation param not aggregated
202
+ count: value.count.toString(),
203
+ mean: value.count && value.sum ? value.sum / value.count : 0,
204
+ bucketOptions: {
205
+ explicitBuckets: { bounds: value.buckets.boundaries },
206
+ },
207
+ bucketCounts: value.buckets.counts.map(value => value.toString()),
208
+ },
209
+ };
210
+ }
211
+ function _transformExponentialHistogramValue(value) {
212
+ // Adapated from reference impl in Go which has more explanatory comments
213
+ // https://github.com/GoogleCloudPlatform/opentelemetry-operations-go/blob/v1.8.0/exporter/collector/metrics.go#L582
214
+ const underflow = value.zeroCount +
215
+ value.negative.bucketCounts.reduce((prev, current) => prev + current, 0);
216
+ const bucketCounts = [
217
+ underflow,
218
+ ...value.positive.bucketCounts,
219
+ 0, // overflow bucket is always empty
220
+ ];
221
+ let bucketOptions;
222
+ if (value.positive.bucketCounts.length === 0) {
223
+ bucketOptions = {
224
+ explicitBuckets: { bounds: [] },
225
+ };
226
+ }
227
+ else {
228
+ const growthFactor = Math.pow(2, Math.pow(2, -value.scale)); //exp2(exp2(-value.scale));
229
+ const scale = Math.pow(growthFactor, value.positive.offset);
230
+ bucketOptions = {
231
+ exponentialBuckets: {
232
+ growthFactor,
233
+ scale,
234
+ numFiniteBuckets: bucketCounts.length - 2,
235
+ },
236
+ };
237
+ }
238
+ const mean = value.sum === undefined || value.count === 0 ? 0 : value.sum / value.count;
239
+ return {
240
+ distributionValue: {
241
+ // sumOfSquaredDeviation param not aggregated
242
+ count: value.count.toString(),
243
+ mean,
244
+ bucketOptions,
245
+ bucketCounts: bucketCounts.map(value => value.toString()),
246
+ },
247
+ };
248
+ }
249
+ /** Transforms an OpenTelemetry time value to a GCM time value. */
250
+ function _formatHrTimeToGcmTime(hrTime) {
251
+ return {
252
+ seconds: hrTime[0],
253
+ nanos: hrTime[1],
254
+ };
255
+ }
256
+ /**
257
+ * Assert switch case is exhaustive
258
+ */
259
+ function exhaust(switchValue) {
260
+ return switchValue;
261
+ }
262
+ exports._TEST_ONLY = {
263
+ _normalizeLabelKey,
264
+ _transformMetricKind,
265
+ _extractLabels,
266
+ _formatHrTimeToGcmTime,
267
+ _transformResource,
268
+ _transformPoint,
269
+ _transformValueType,
270
+ transformResourceMetricToTimeSeriesArray,
271
+ };
272
+ //# sourceMappingURL=transform.js.map
@@ -30,6 +30,12 @@ exports.MUX_SESSION_CREATE_ERROR = 'mux-session-create-error';
30
30
  * @extends {EventEmitter}
31
31
  */
32
32
  class MultiplexedSession extends events_1.EventEmitter {
33
+ database;
34
+ // frequency to create new mux session
35
+ refreshRate;
36
+ _multiplexedSession;
37
+ _refreshHandle;
38
+ _observabilityOptions;
33
39
  constructor(database) {
34
40
  super();
35
41
  this.database = database;
@@ -125,7 +131,7 @@ class MultiplexedSession extends events_1.EventEmitter {
125
131
  *
126
132
  */
127
133
  getSession(callback) {
128
- this._acquire().then(session => callback(null, session, session === null || session === void 0 ? void 0 : session.txn), callback);
134
+ this._acquire().then(session => callback(null, session, session?.txn), callback);
129
135
  }
130
136
  /**
131
137
  * Acquires a session asynchronously, and prepares the transaction for the session.
@@ -20,7 +20,6 @@ exports.partialResultStream = partialResultStream;
20
20
  const service_1 = require("./common-grpc/service");
21
21
  const checkpointStream = require("checkpoint-stream");
22
22
  const eventsIntercept = require("events-intercept");
23
- const is = require("is");
24
23
  const mergeStream = require("merge-stream");
25
24
  const stream_1 = require("stream");
26
25
  const streamEvents = require("stream-events");
@@ -29,6 +28,7 @@ const transaction_runner_1 = require("./transaction-runner");
29
28
  const codec_1 = require("./codec");
30
29
  const protos_1 = require("../protos/protos");
31
30
  const stream = require("stream");
31
+ const helper_1 = require("./helper");
32
32
  /**
33
33
  * The PartialResultStream transforms partial result set objects into Row
34
34
  * objects.
@@ -39,9 +39,15 @@ const stream = require("stream");
39
39
  * @param {RowOptions} [options] The row options.
40
40
  */
41
41
  class PartialResultStream extends stream_1.Transform {
42
+ _destroyed;
43
+ _fields;
44
+ _options;
45
+ _pendingValue;
46
+ _pendingValueForResume;
47
+ _values;
48
+ _numPushFailed = 0;
42
49
  constructor(options = {}) {
43
50
  super({ objectMode: true });
44
- this._numPushFailed = 0;
45
51
  this._destroyed = false;
46
52
  this._options = Object.assign({ maxResumeRetries: 20 }, options);
47
53
  this._values = [];
@@ -83,9 +89,13 @@ class PartialResultStream extends stream_1.Transform {
83
89
  .fields;
84
90
  }
85
91
  let res = true;
86
- if (!is.empty(chunk.values)) {
92
+ if (!(0, helper_1.isEmpty)(chunk.values)) {
87
93
  res = this._addChunk(chunk);
88
94
  }
95
+ if (chunk.last) {
96
+ this.emit('end');
97
+ return;
98
+ }
89
99
  if (res) {
90
100
  next();
91
101
  }
@@ -199,9 +209,8 @@ class PartialResultStream extends stream_1.Transform {
199
209
  */
200
210
  _createRow(values) {
201
211
  const fields = values.map((value, index) => {
202
- var _a;
203
212
  const { name, type } = this._fields[index];
204
- const columnMetadata = (_a = this._options.columnsMetadata) === null || _a === void 0 ? void 0 : _a[name];
213
+ const columnMetadata = this._options.columnsMetadata?.[name];
205
214
  return {
206
215
  name,
207
216
  value: codec_1.codec.decode(value, type, columnMetadata),
@@ -236,7 +245,7 @@ class PartialResultStream extends stream_1.Transform {
236
245
  }
237
246
  return [PartialResultStream.mergeLists(type, head, tail)];
238
247
  }
239
- if (is.string(head) && is.string(tail)) {
248
+ if ((0, helper_1.isString)(head) && (0, helper_1.isString)(tail)) {
240
249
  return [head + tail];
241
250
  }
242
251
  return [head, tail];
@@ -284,13 +293,12 @@ exports.PartialResultStream = PartialResultStream;
284
293
  * @returns {PartialResultStream}
285
294
  */
286
295
  function partialResultStream(requestFn, options) {
287
- var _a, _b;
288
296
  const retryableCodes = [google_gax_1.grpc.status.UNAVAILABLE];
289
297
  const maxQueued = 10;
290
298
  let lastResumeToken;
291
299
  let lastRequestStream;
292
300
  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;
301
+ const timeout = options?.gaxOptions?.timeout ?? Infinity;
294
302
  // mergeStream allows multiple streams to be connected into one. This is good;
295
303
  // if we need to retry a request and pipe more data to the user's stream.
296
304
  // We also add an additional stream that can be used to flush any remaining
@@ -331,7 +339,7 @@ function partialResultStream(requestFn, options) {
331
339
  });
332
340
  };
333
341
  const makeRequest = () => {
334
- if (is.defined(lastResumeToken) && lastResumeToken.length > 0) {
342
+ if ((0, helper_1.isDefined)(lastResumeToken) && lastResumeToken.length > 0) {
335
343
  partialRSStream._resetPendingValues();
336
344
  }
337
345
  lastRequestStream = requestFn(lastResumeToken);
@@ -395,6 +403,6 @@ function partialResultStream(requestFn, options) {
395
403
  .on('resumed', () => requestsStream.resume()));
396
404
  }
397
405
  function _hasResumeToken(chunk) {
398
- return is.defined(chunk.resumeToken) && chunk.resumeToken.length > 0;
406
+ return (0, helper_1.isDefined)(chunk.resumeToken) && chunk.resumeToken.length > 0;
399
407
  }
400
408
  //# sourceMappingURL=partial-result-stream.js.map
@@ -34,6 +34,7 @@ exports.randIdForProcess = randIdForProcess;
34
34
  const X_GOOG_SPANNER_REQUEST_ID_HEADER = 'x-goog-spanner-request-id';
35
35
  exports.X_GOOG_SPANNER_REQUEST_ID_HEADER = X_GOOG_SPANNER_REQUEST_ID_HEADER;
36
36
  class AtomicCounter {
37
+ backingBuffer;
37
38
  constructor(initialValue) {
38
39
  this.backingBuffer = new Uint32Array(new SharedArrayBuffer(Uint32Array.BYTES_PER_ELEMENT));
39
40
  if (initialValue) {
@@ -47,6 +47,13 @@ export interface SessionFactoryInterface {
47
47
  * @param {GetSessionCallback} callback The callback function.
48
48
  */
49
49
  getSessionForPartitionedOps(callback: GetSessionCallback): void;
50
+ /**
51
+ * When called returns a session for read write.
52
+ *
53
+ * @name SessionFactoryInterface#getSessionForReadWrite
54
+ * @param {GetSessionCallback} callback The callback function.
55
+ */
56
+ getSessionForReadWrite(callback: GetSessionCallback): void;
50
57
  /**
51
58
  * When called returns the pool object.
52
59
  *
@@ -66,6 +73,12 @@ export interface SessionFactoryInterface {
66
73
  * @name SessionFactoryInterface#isMultiplexedEnabled
67
74
  */
68
75
  isMultiplexedEnabled(): boolean;
76
+ /**
77
+ * When called returns if the multiplexed is enabled or not for read write transactions.
78
+ *
79
+ * @name SessionFactoryInterface#isMultiplexedEnabledForRW
80
+ */
81
+ isMultiplexedEnabledForRW(): boolean;
69
82
  }
70
83
  /**
71
84
  * Creates a SessionFactory object to manage the creation of
@@ -83,6 +96,7 @@ export declare class SessionFactory extends common.GrpcServiceObject implements
83
96
  pool_: SessionPoolInterface;
84
97
  isMultiplexed: boolean;
85
98
  isMultiplexedPartitionOps: boolean;
99
+ isMultiplexedRW: boolean;
86
100
  constructor(database: Database, name: String, poolOptions?: SessionPoolConstructor | SessionPoolOptions);
87
101
  /**
88
102
  * Retrieves a session, either a regular session or a multiplexed session, based on the environment variable configuration.
@@ -105,6 +119,18 @@ export declare class SessionFactory extends common.GrpcServiceObject implements
105
119
  * @param {GetSessionCallback} callback The callback function.
106
120
  */
107
121
  getSessionForPartitionedOps(callback: GetSessionCallback): void;
122
+ /**
123
+ * Retrieves a session for read write operations, selecting the appropriate session type
124
+ * based on whether multiplexed sessions are enabled.
125
+ *
126
+ * If multiplexed sessions are enabled for read write this methods delegates the request to `getSession()`, which returns
127
+ * either a multiplexed session or a regular session based on the configuration.
128
+ *
129
+ * If the multiplexed sessions are disabled, a session is retrieved from the regular session pool.
130
+ *
131
+ * @param {GetSessionCallback} callback The callback function.
132
+ */
133
+ getSessionForReadWrite(callback: GetSessionCallback): void;
108
134
  /**
109
135
  * Returns the regular session pool object.
110
136
  *
@@ -133,5 +159,13 @@ export declare class SessionFactory extends common.GrpcServiceObject implements
133
159
  * @returns {boolean}
134
160
  */
135
161
  isMultiplexedEnabled(): boolean;
162
+ /**
163
+ * Returns if a multiplexed is enabled or not for read write transaction.
164
+ *
165
+ * This method returns true if multiplexed session is enabled for read write transactions, otherwise returns false
166
+ *
167
+ * @returns {boolean}
168
+ */
169
+ isMultiplexedEnabledForRW(): boolean;
136
170
  }
137
171
  export {};
@@ -31,6 +31,11 @@ const common = require('./common-grpc/service-object');
31
31
  * configuration options or custom pool inteface.
32
32
  */
33
33
  class SessionFactory extends common.GrpcServiceObject {
34
+ multiplexedSession_;
35
+ pool_;
36
+ isMultiplexed;
37
+ isMultiplexedPartitionOps;
38
+ isMultiplexedRW;
34
39
  constructor(database, name, poolOptions) {
35
40
  super({
36
41
  parent: database,
@@ -52,6 +57,9 @@ class SessionFactory extends common.GrpcServiceObject {
52
57
  process.env.GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS === 'true' &&
53
58
  process.env.GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS_PARTITIONED_OPS ===
54
59
  'true';
60
+ this.isMultiplexedRW =
61
+ process.env.GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS === 'true' &&
62
+ process.env.GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS_FOR_RW === 'true';
55
63
  // Multiplexed sessions should only be created if its enabled.
56
64
  if (this.isMultiplexed) {
57
65
  this.multiplexedSession_.on('error', this.emit.bind(database, 'error'));
@@ -88,6 +96,22 @@ class SessionFactory extends common.GrpcServiceObject {
88
96
  ? this.getSession(callback)
89
97
  : this.pool_.getSession(callback);
90
98
  }
99
+ /**
100
+ * Retrieves a session for read write operations, selecting the appropriate session type
101
+ * based on whether multiplexed sessions are enabled.
102
+ *
103
+ * If multiplexed sessions are enabled for read write this methods delegates the request to `getSession()`, which returns
104
+ * either a multiplexed session or a regular session based on the configuration.
105
+ *
106
+ * If the multiplexed sessions are disabled, a session is retrieved from the regular session pool.
107
+ *
108
+ * @param {GetSessionCallback} callback The callback function.
109
+ */
110
+ getSessionForReadWrite(callback) {
111
+ this.isMultiplexedRW
112
+ ? this.getSession(callback)
113
+ : this.pool_.getSession(callback);
114
+ }
91
115
  /**
92
116
  * Returns the regular session pool object.
93
117
  *
@@ -110,8 +134,7 @@ class SessionFactory extends common.GrpcServiceObject {
110
134
  * @throws {Error} If the session is invalid or cannot be released.
111
135
  */
112
136
  release(session) {
113
- var _a;
114
- if (!((_a = session.metadata) === null || _a === void 0 ? void 0 : _a.multiplexed)) {
137
+ if (!session.metadata?.multiplexed) {
115
138
  this.pool_.release(session);
116
139
  }
117
140
  }
@@ -125,6 +148,16 @@ class SessionFactory extends common.GrpcServiceObject {
125
148
  isMultiplexedEnabled() {
126
149
  return this.isMultiplexed;
127
150
  }
151
+ /**
152
+ * Returns if a multiplexed is enabled or not for read write transaction.
153
+ *
154
+ * This method returns true if multiplexed session is enabled for read write transactions, otherwise returns false
155
+ *
156
+ * @returns {boolean}
157
+ */
158
+ isMultiplexedEnabledForRW() {
159
+ return this.isMultiplexedRW;
160
+ }
128
161
  }
129
162
  exports.SessionFactory = SessionFactory;
130
163
  //# sourceMappingURL=session-factory.js.map
@@ -18,7 +18,6 @@ Object.defineProperty(exports, "__esModule", { value: true });
18
18
  exports.SessionPool = exports.SessionPoolExhaustedError = exports.SessionLeakError = exports.ReleaseError = void 0;
19
19
  exports.isSessionNotFoundError = isSessionNotFoundError;
20
20
  const events_1 = require("events");
21
- const is = require("is");
22
21
  const p_queue_1 = require("p-queue");
23
22
  const google_gax_1 = require("google-gax");
24
23
  const trace = require("stack-trace");
@@ -43,6 +42,7 @@ const DEFAULTS = {
43
42
  * @private
44
43
  */
45
44
  class ReleaseError extends google_gax_1.GoogleError {
45
+ resource;
46
46
  constructor(resource) {
47
47
  super('Unable to release unknown resource.');
48
48
  this.resource = resource;
@@ -55,6 +55,7 @@ exports.ReleaseError = ReleaseError;
55
55
  * @private
56
56
  */
57
57
  class SessionLeakError extends google_gax_1.GoogleError {
58
+ messages;
58
59
  constructor(leaks) {
59
60
  super(`${leaks.length} session leak(s) detected.`);
60
61
  // Restore error name that was overwritten by the super constructor call.
@@ -67,6 +68,7 @@ exports.SessionLeakError = SessionLeakError;
67
68
  * Error to be thrown when the session pool is exhausted.
68
69
  */
69
70
  class SessionPoolExhaustedError extends google_gax_1.GoogleError {
71
+ messages;
70
72
  constructor(leaks) {
71
73
  super("No resources available." /* errors.Exhausted */);
72
74
  // Restore error name that was overwritten by the super constructor call.
@@ -95,6 +97,19 @@ function isSessionNotFoundError(error) {
95
97
  * @extends {EventEmitter}
96
98
  */
97
99
  class SessionPool extends events_1.EventEmitter {
100
+ database;
101
+ isOpen;
102
+ options;
103
+ _acquires;
104
+ _evictHandle;
105
+ _inventory;
106
+ _onClose;
107
+ _pending = 0;
108
+ _waiters = 0;
109
+ _pingHandle;
110
+ _requests;
111
+ _traces;
112
+ _observabilityOptions;
98
113
  /**
99
114
  * Formats stack trace objects into Node-like stack trace.
100
115
  *
@@ -186,8 +201,6 @@ class SessionPool extends events_1.EventEmitter {
186
201
  */
187
202
  constructor(database, options) {
188
203
  super();
189
- this._pending = 0;
190
- this._waiters = 0;
191
204
  if (options && options.min && options.max && options.min > options.max) {
192
205
  throw new TypeError('Min sessions may not be greater than max sessions.');
193
206
  }
@@ -227,7 +240,9 @@ class SessionPool extends events_1.EventEmitter {
227
240
  this._stopHouseKeeping();
228
241
  this.emit('close');
229
242
  sessions.forEach(session => this._destroy(session));
230
- this._requests.onIdle().then(() => {
243
+ this._requests
244
+ .onIdle()
245
+ .then(() => {
231
246
  const leaks = this._getLeaks();
232
247
  let error;
233
248
  this._inventory.sessions = [];
@@ -236,7 +251,8 @@ class SessionPool extends events_1.EventEmitter {
236
251
  error = new SessionLeakError(leaks);
237
252
  }
238
253
  callback(error);
239
- });
254
+ })
255
+ .catch(err => callback(err));
240
256
  }
241
257
  /**
242
258
  * Retrieve a read session.
@@ -508,7 +524,7 @@ class SessionPool extends events_1.EventEmitter {
508
524
  }
509
525
  const index = this._inventory.sessions.indexOf(session);
510
526
  this._inventory.sessions.splice(index, 1);
511
- this._destroy(session);
527
+ void this._destroy(session);
512
528
  }
513
529
  }
514
530
  /**
@@ -588,7 +604,7 @@ class SessionPool extends events_1.EventEmitter {
588
604
  ];
589
605
  const timeout = this.options.acquireTimeout;
590
606
  let removeTimeoutListener = () => { };
591
- if (!is.infinite(timeout)) {
607
+ if (!(0, helper_1.isInfinite)(timeout)) {
592
608
  const elapsed = Date.now() - startTime;
593
609
  const remaining = timeout - elapsed;
594
610
  promises.push(new Promise((_, reject) => {
@@ -672,7 +688,7 @@ class SessionPool extends events_1.EventEmitter {
672
688
  }
673
689
  catch (e) {
674
690
  this._inventory.borrowed.delete(session);
675
- this._destroy(session);
691
+ await this._destroy(session);
676
692
  }
677
693
  }
678
694
  /**
@@ -88,7 +88,6 @@ export type DeleteSessionCallback = NormalCallback<google.protobuf.IEmpty>;
88
88
  * ```
89
89
  */
90
90
  export declare class Session extends common.GrpcServiceObject {
91
- id: string;
92
91
  formattedName_?: string;
93
92
  txn?: Transaction;
94
93
  lastUsed?: number;
@@ -67,8 +67,13 @@ const request_id_header_1 = require("./request_id_header");
67
67
  * ```
68
68
  */
69
69
  class Session extends common.GrpcServiceObject {
70
+ formattedName_;
71
+ txn;
72
+ lastUsed;
73
+ lastError;
74
+ commonHeaders_;
75
+ _observabilityOptions;
70
76
  constructor(database, name) {
71
- var _a;
72
77
  const methods = {
73
78
  /**
74
79
  * Create a session.
@@ -201,7 +206,7 @@ class Session extends common.GrpcServiceObject {
201
206
  },
202
207
  });
203
208
  this._observabilityOptions = database._observabilityOptions;
204
- this.commonHeaders_ = (0, common_1.getCommonHeaders)(this.parent.formattedName_, (_a = this._observabilityOptions) === null || _a === void 0 ? void 0 : _a.enableEndToEndTracing);
209
+ this.commonHeaders_ = (0, common_1.getCommonHeaders)(this.parent.formattedName_, this._observabilityOptions?.enableEndToEndTracing);
205
210
  this.request = database.request;
206
211
  this.requestStream = database.requestStream;
207
212
  if (name) {