@google-cloud/spanner 8.0.0 → 8.2.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 (54) hide show
  1. package/README.md +2 -0
  2. package/build/protos/google/spanner/admin/database/v1/spanner_database_admin.proto +35 -0
  3. package/build/protos/google/spanner/v1/change_stream.proto +451 -0
  4. package/build/protos/google/spanner/v1/commit_response.proto +9 -4
  5. package/build/protos/google/spanner/v1/transaction.proto +40 -356
  6. package/build/protos/protos.d.ts +2087 -4
  7. package/build/protos/protos.js +6191 -349
  8. package/build/protos/protos.json +556 -25
  9. package/build/src/batch-transaction.js +2 -2
  10. package/build/src/codec.js +20 -21
  11. package/build/src/common-grpc/service.js +10 -10
  12. package/build/src/common.d.ts +1 -0
  13. package/build/src/common.js +9 -1
  14. package/build/src/database.d.ts +3 -2
  15. package/build/src/database.js +16 -14
  16. package/build/src/helper.d.ts +90 -0
  17. package/build/src/helper.js +154 -0
  18. package/build/src/index.d.ts +36 -1
  19. package/build/src/index.js +179 -8
  20. package/build/src/instrument.js +3 -2
  21. package/build/src/metrics/constants.d.ts +36 -0
  22. package/build/src/metrics/constants.js +106 -0
  23. package/build/src/metrics/external-types.d.ts +20 -0
  24. package/build/src/metrics/external-types.js +32 -0
  25. package/build/src/metrics/interceptor.d.ts +13 -0
  26. package/build/src/metrics/interceptor.js +87 -0
  27. package/build/src/metrics/metrics-tracer-factory.d.ts +165 -0
  28. package/build/src/metrics/metrics-tracer-factory.js +389 -0
  29. package/build/src/metrics/metrics-tracer.d.ts +204 -0
  30. package/build/src/metrics/metrics-tracer.js +371 -0
  31. package/build/src/metrics/spanner-metrics-exporter.d.ts +35 -0
  32. package/build/src/metrics/spanner-metrics-exporter.js +119 -0
  33. package/build/src/metrics/transform.d.ts +144 -0
  34. package/build/src/metrics/transform.js +272 -0
  35. package/build/src/multiplexed-session.d.ts +1 -1
  36. package/build/src/multiplexed-session.js +2 -4
  37. package/build/src/partial-result-stream.js +9 -5
  38. package/build/src/session-factory.d.ts +34 -0
  39. package/build/src/session-factory.js +30 -0
  40. package/build/src/session-pool.js +1 -2
  41. package/build/src/table.d.ts +2 -0
  42. package/build/src/table.js +5 -0
  43. package/build/src/transaction-runner.d.ts +6 -0
  44. package/build/src/transaction-runner.js +8 -0
  45. package/build/src/transaction.d.ts +44 -1
  46. package/build/src/transaction.js +202 -49
  47. package/build/src/v1/database_admin_client.d.ts +34 -0
  48. package/build/src/v1/database_admin_client.js +167 -1
  49. package/build/src/v1/database_admin_client_config.json +4 -0
  50. package/build/src/v1/instance_admin_client.d.ts +120 -0
  51. package/build/src/v1/instance_admin_client.js +312 -13
  52. package/build/src/v1/spanner_client.js +108 -0
  53. package/build/src/v1/spanner_proto_list.json +1 -0
  54. package/package.json +15 -8
@@ -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
@@ -106,7 +106,7 @@ export declare class MultiplexedSession extends EventEmitter implements Multiple
106
106
  */
107
107
  getSession(callback: GetSessionCallback): void;
108
108
  /**
109
- * Acquires a session asynchronously, and prepares the transaction for the session.
109
+ * Acquires a session asynchronously.
110
110
  *
111
111
  * Once a session is successfully acquired, it returns the session object (which may be `null` if unsuccessful).
112
112
  *
@@ -131,10 +131,10 @@ class MultiplexedSession extends events_1.EventEmitter {
131
131
  *
132
132
  */
133
133
  getSession(callback) {
134
- this._acquire().then(session => callback(null, session, session?.txn), callback);
134
+ this._acquire().then(session => callback(null, session, session.transaction(session.parent.queryOptions_)), callback);
135
135
  }
136
136
  /**
137
- * Acquires a session asynchronously, and prepares the transaction for the session.
137
+ * Acquires a session asynchronously.
138
138
  *
139
139
  * Once a session is successfully acquired, it returns the session object (which may be `null` if unsuccessful).
140
140
  *
@@ -144,8 +144,6 @@ class MultiplexedSession extends events_1.EventEmitter {
144
144
  */
145
145
  async _acquire() {
146
146
  const session = await this._getSession();
147
- // Prepare a transaction for a session
148
- session.txn = session.transaction(session.parent.queryOptions_);
149
147
  return session;
150
148
  }
151
149
  /**
@@ -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.
@@ -89,9 +89,13 @@ class PartialResultStream extends stream_1.Transform {
89
89
  .fields;
90
90
  }
91
91
  let res = true;
92
- if (!is.empty(chunk.values)) {
92
+ if (!(0, helper_1.isEmpty)(chunk.values)) {
93
93
  res = this._addChunk(chunk);
94
94
  }
95
+ if (chunk.last) {
96
+ this.emit('end');
97
+ return;
98
+ }
95
99
  if (res) {
96
100
  next();
97
101
  }
@@ -241,7 +245,7 @@ class PartialResultStream extends stream_1.Transform {
241
245
  }
242
246
  return [PartialResultStream.mergeLists(type, head, tail)];
243
247
  }
244
- if (is.string(head) && is.string(tail)) {
248
+ if ((0, helper_1.isString)(head) && (0, helper_1.isString)(tail)) {
245
249
  return [head + tail];
246
250
  }
247
251
  return [head, tail];
@@ -335,7 +339,7 @@ function partialResultStream(requestFn, options) {
335
339
  });
336
340
  };
337
341
  const makeRequest = () => {
338
- if (is.defined(lastResumeToken) && lastResumeToken.length > 0) {
342
+ if ((0, helper_1.isDefined)(lastResumeToken) && lastResumeToken.length > 0) {
339
343
  partialRSStream._resetPendingValues();
340
344
  }
341
345
  lastRequestStream = requestFn(lastResumeToken);
@@ -399,6 +403,6 @@ function partialResultStream(requestFn, options) {
399
403
  .on('resumed', () => requestsStream.resume()));
400
404
  }
401
405
  function _hasResumeToken(chunk) {
402
- return is.defined(chunk.resumeToken) && chunk.resumeToken.length > 0;
406
+ return (0, helper_1.isDefined)(chunk.resumeToken) && chunk.resumeToken.length > 0;
403
407
  }
404
408
  //# sourceMappingURL=partial-result-stream.js.map
@@ -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 {};
@@ -35,6 +35,7 @@ class SessionFactory extends common.GrpcServiceObject {
35
35
  pool_;
36
36
  isMultiplexed;
37
37
  isMultiplexedPartitionOps;
38
+ isMultiplexedRW;
38
39
  constructor(database, name, poolOptions) {
39
40
  super({
40
41
  parent: database,
@@ -56,6 +57,9 @@ class SessionFactory extends common.GrpcServiceObject {
56
57
  process.env.GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS === 'true' &&
57
58
  process.env.GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS_PARTITIONED_OPS ===
58
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';
59
63
  // Multiplexed sessions should only be created if its enabled.
60
64
  if (this.isMultiplexed) {
61
65
  this.multiplexedSession_.on('error', this.emit.bind(database, 'error'));
@@ -92,6 +96,22 @@ class SessionFactory extends common.GrpcServiceObject {
92
96
  ? this.getSession(callback)
93
97
  : this.pool_.getSession(callback);
94
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
+ }
95
115
  /**
96
116
  * Returns the regular session pool object.
97
117
  *
@@ -128,6 +148,16 @@ class SessionFactory extends common.GrpcServiceObject {
128
148
  isMultiplexedEnabled() {
129
149
  return this.isMultiplexed;
130
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
+ }
131
161
  }
132
162
  exports.SessionFactory = SessionFactory;
133
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");
@@ -605,7 +604,7 @@ class SessionPool extends events_1.EventEmitter {
605
604
  ];
606
605
  const timeout = this.options.acquireTimeout;
607
606
  let removeTimeoutListener = () => { };
608
- if (!is.infinite(timeout)) {
607
+ if (!(0, helper_1.isInfinite)(timeout)) {
609
608
  const elapsed = Date.now() - startTime;
610
609
  const remaining = timeout - elapsed;
611
610
  promises.push(new Promise((_, reject) => {
@@ -23,6 +23,7 @@ import IRequestOptions = databaseAdmin.spanner.v1.IRequestOptions;
23
23
  import { ObservabilityOptions } from './instrument';
24
24
  import { google } from '../protos/protos';
25
25
  import IsolationLevel = google.spanner.v1.TransactionOptions.IsolationLevel;
26
+ import ReadLockMode = google.spanner.v1.TransactionOptions.ReadWrite.ReadLockMode;
26
27
  export type Key = string | string[];
27
28
  export type CreateTableResponse = [
28
29
  Table,
@@ -36,6 +37,7 @@ interface MutateRowsOptions extends CommitOptions {
36
37
  requestOptions?: Omit<IRequestOptions, 'requestTag'>;
37
38
  excludeTxnFromChangeStreams?: boolean;
38
39
  isolationLevel?: IsolationLevel;
40
+ readLockMode?: ReadLockMode;
39
41
  }
40
42
  export type DeleteRowsCallback = CommitCallback;
41
43
  export type DeleteRowsResponse = CommitResponse;
@@ -21,6 +21,7 @@ const through = require("through2");
21
21
  const instrument_1 = require("./instrument");
22
22
  const protos_1 = require("../protos/protos");
23
23
  var IsolationLevel = protos_1.google.spanner.v1.TransactionOptions.IsolationLevel;
24
+ var ReadLockMode = protos_1.google.spanner.v1.TransactionOptions.ReadWrite.ReadLockMode;
24
25
  const GOOGLE_STANDARD_SQL = 'GOOGLE_STANDARD_SQL';
25
26
  const POSTGRESQL = 'POSTGRESQL';
26
27
  /**
@@ -253,10 +254,14 @@ class Table {
253
254
  const isolationLevel = 'isolationLevel' in options
254
255
  ? options.isolationLevel
255
256
  : IsolationLevel.ISOLATION_LEVEL_UNSPECIFIED;
257
+ const readLockMode = 'readLockMode' in options
258
+ ? options.readLockMode
259
+ : ReadLockMode.READ_LOCK_MODE_UNSPECIFIED;
256
260
  this.database.runTransaction({
257
261
  requestOptions: requestOptions,
258
262
  excludeTxnFromChangeStreams: excludeTxnFromChangeStreams,
259
263
  isolationLevel: isolationLevel,
264
+ readLockMode: readLockMode,
260
265
  }, (err, transaction) => {
261
266
  if (err) {
262
267
  (0, instrument_1.setSpanError)(span, err);
@@ -20,6 +20,7 @@ import { NormalCallback } from './common';
20
20
  import { google } from '../protos/protos';
21
21
  import IRequestOptions = google.spanner.v1.IRequestOptions;
22
22
  import IsolationLevel = google.spanner.v1.TransactionOptions.IsolationLevel;
23
+ import ReadLockMode = google.spanner.v1.TransactionOptions.ReadWrite.ReadLockMode;
23
24
  /**
24
25
  * @typedef {object} RunTransactionOptions
25
26
  * @property {number} [timeout] The maximum amount of time (in ms) that a
@@ -28,9 +29,13 @@ import IsolationLevel = google.spanner.v1.TransactionOptions.IsolationLevel;
28
29
  export interface RunTransactionOptions {
29
30
  timeout?: number;
30
31
  requestOptions?: Pick<IRequestOptions, 'transactionTag'>;
32
+ /**
33
+ * @deprecated Use readLockMode instead.
34
+ */
31
35
  optimisticLock?: boolean;
32
36
  excludeTxnFromChangeStreams?: boolean;
33
37
  isolationLevel?: IsolationLevel;
38
+ readLockMode?: ReadLockMode;
34
39
  }
35
40
  /**
36
41
  * A function to execute in the context of a transaction.
@@ -80,6 +85,7 @@ export declare abstract class Runner<T> {
80
85
  session: Session;
81
86
  transaction?: Transaction;
82
87
  options: RunTransactionOptions;
88
+ multiplexedSessionPreviousTransactionId?: Uint8Array | string;
83
89
  constructor(session: Session, transaction: Transaction, options?: RunTransactionOptions);
84
90
  /**
85
91
  * Runs the user function against the provided transaction. Resolving the
@@ -24,6 +24,7 @@ const through = require("through2");
24
24
  const session_pool_1 = require("./session-pool");
25
25
  const protos_1 = require("../protos/protos");
26
26
  var IsolationLevel = protos_1.google.spanner.v1.TransactionOptions.IsolationLevel;
27
+ var ReadLockMode = protos_1.google.spanner.v1.TransactionOptions.ReadWrite.ReadLockMode;
27
28
  // eslint-disable-next-line @typescript-eslint/no-var-requires
28
29
  const jsonProtos = require('../protos/protos.json');
29
30
  const RETRY_INFO = 'google.rpc.retryinfo-bin';
@@ -70,6 +71,7 @@ class Runner {
70
71
  session;
71
72
  transaction;
72
73
  options;
74
+ multiplexedSessionPreviousTransactionId;
73
75
  constructor(session, transaction, options) {
74
76
  this.attempts = 0;
75
77
  this.session = session;
@@ -78,6 +80,7 @@ class Runner {
78
80
  const defaults = {
79
81
  timeout: 3600000,
80
82
  isolationLevel: IsolationLevel.ISOLATION_LEVEL_UNSPECIFIED,
83
+ readLockMode: ReadLockMode.READ_LOCK_MODE_UNSPECIFIED,
81
84
  };
82
85
  this.options = Object.assign(defaults, options);
83
86
  }
@@ -133,6 +136,8 @@ class Runner {
133
136
  }
134
137
  const transaction = this.session.transaction(this.session.parent.queryOptions_);
135
138
  transaction.setReadWriteTransactionOptions(this.options);
139
+ transaction.multiplexedSessionPreviousTransactionId =
140
+ this.multiplexedSessionPreviousTransactionId;
136
141
  if (this.attempts > 0) {
137
142
  await transaction.begin();
138
143
  }
@@ -161,6 +166,9 @@ class Runner {
161
166
  this.session.lastError = e;
162
167
  lastError = e;
163
168
  }
169
+ finally {
170
+ this.multiplexedSessionPreviousTransactionId = transaction.id;
171
+ }
164
172
  // Note that if the error is a 'Session not found' error, it will be
165
173
  // thrown here. We do this to bubble this error up to the caller who is
166
174
  // responsible for retrying the transaction on a different session.