@google-cloud/spanner 8.0.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 (50) 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 +1521 -0
  7. package/build/protos/protos.js +3906 -0
  8. package/build/protos/protos.json +317 -1
  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 +1 -0
  15. package/build/src/database.js +2 -0
  16. package/build/src/helper.d.ts +90 -0
  17. package/build/src/helper.js +154 -0
  18. package/build/src/index.d.ts +33 -0
  19. package/build/src/index.js +178 -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/partial-result-stream.js +9 -5
  36. package/build/src/session-factory.d.ts +34 -0
  37. package/build/src/session-factory.js +30 -0
  38. package/build/src/session-pool.js +1 -2
  39. package/build/src/transaction-runner.d.ts +1 -0
  40. package/build/src/transaction-runner.js +6 -0
  41. package/build/src/transaction.d.ts +42 -1
  42. package/build/src/transaction.js +192 -42
  43. package/build/src/v1/database_admin_client.d.ts +34 -0
  44. package/build/src/v1/database_admin_client.js +167 -1
  45. package/build/src/v1/database_admin_client_config.json +4 -0
  46. package/build/src/v1/instance_admin_client.d.ts +120 -0
  47. package/build/src/v1/instance_admin_client.js +312 -13
  48. package/build/src/v1/spanner_client.js +108 -0
  49. package/build/src/v1/spanner_proto_list.json +1 -0
  50. package/package.json +12 -5
@@ -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
@@ -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) => {
@@ -80,6 +80,7 @@ export declare abstract class Runner<T> {
80
80
  session: Session;
81
81
  transaction?: Transaction;
82
82
  options: RunTransactionOptions;
83
+ multiplexedSessionPreviousTransactionId?: Uint8Array | string;
83
84
  constructor(session: Session, transaction: Transaction, options?: RunTransactionOptions);
84
85
  /**
85
86
  * Runs the user function against the provided transaction. Resolving the
@@ -70,6 +70,7 @@ class Runner {
70
70
  session;
71
71
  transaction;
72
72
  options;
73
+ multiplexedSessionPreviousTransactionId;
73
74
  constructor(session, transaction, options) {
74
75
  this.attempts = 0;
75
76
  this.session = session;
@@ -133,6 +134,8 @@ class Runner {
133
134
  }
134
135
  const transaction = this.session.transaction(this.session.parent.queryOptions_);
135
136
  transaction.setReadWriteTransactionOptions(this.options);
137
+ transaction.multiplexedSessionPreviousTransactionId =
138
+ this.multiplexedSessionPreviousTransactionId;
136
139
  if (this.attempts > 0) {
137
140
  await transaction.begin();
138
141
  }
@@ -161,6 +164,9 @@ class Runner {
161
164
  this.session.lastError = e;
162
165
  lastError = e;
163
166
  }
167
+ finally {
168
+ this.multiplexedSessionPreviousTransactionId = transaction.id;
169
+ }
164
170
  // Note that if the error is a 'Session not found' error, it will be
165
171
  // thrown here. We do this to bubble this error up to the caller who is
166
172
  // responsible for retrying the transaction on a different session.
@@ -23,6 +23,7 @@ import { Json, JSONOptions, Type, Value } from './codec';
23
23
  import { PartialResultStream, ResumeToken, Row } from './partial-result-stream';
24
24
  import { Session } from './session';
25
25
  import { Key } from './table';
26
+ import { Span } from './instrument';
26
27
  import { google as spannerClient } from '../protos/protos';
27
28
  import { NormalCallback } from './common';
28
29
  import { google } from '../protos/protos';
@@ -173,6 +174,7 @@ export interface RunUpdateCallback {
173
174
  (err: null | grpc.ServiceError, rowCount: number): void;
174
175
  }
175
176
  export type CommitCallback = NormalCallback<spannerClient.spanner.v1.ICommitResponse>;
177
+ type PrecommitTokenProvider = spannerClient.spanner.v1.ITransaction | spannerClient.spanner.v1.IPartialResultSet | spannerClient.spanner.v1.IExecuteBatchDmlResponse | spannerClient.spanner.v1.ICommitResponse;
176
178
  /**
177
179
  * @typedef {object} TimestampBounds
178
180
  * @property {boolean} [strong=true] Read at a timestamp where all previously
@@ -233,7 +235,9 @@ export declare class Snapshot extends EventEmitter {
233
235
  protected _waitingRequests: Array<() => void>;
234
236
  protected _inlineBeginStarted: any;
235
237
  protected _useInRunner: boolean;
238
+ protected _latestPreCommitToken: spannerClient.spanner.v1.IMultiplexedSessionPrecommitToken | undefined | null;
236
239
  id?: Uint8Array | string;
240
+ multiplexedSessionPreviousTransactionId?: Uint8Array | string;
237
241
  ended: boolean;
238
242
  metadata?: spannerClient.spanner.v1.ITransaction;
239
243
  readTimestamp?: PreciseDate;
@@ -249,6 +253,7 @@ export declare class Snapshot extends EventEmitter {
249
253
  _observabilityOptions?: ObservabilityOptions;
250
254
  _traceConfig: traceConfig;
251
255
  protected _dbName?: string;
256
+ protected _mutationKey: spannerClient.spanner.v1.Mutation | null;
252
257
  /**
253
258
  * The transaction ID.
254
259
  *
@@ -293,6 +298,40 @@ export declare class Snapshot extends EventEmitter {
293
298
  * are specified for a query.
294
299
  */
295
300
  constructor(session: Session, options?: TimestampBounds, queryOptions?: IQueryOptions);
301
+ protected _updatePrecommitToken(resp: PrecommitTokenProvider): void;
302
+ /**
303
+ * Selects a single representative mutation from a list to be used as the
304
+ * transaction's `mutationKey`.
305
+ *
306
+ * This key is required by Spanner and is sent in the `BeginTransactionRequest`
307
+ * for read-write transactions that only contain mutations. The selection follows
308
+ * a two-tiered heuristic to choose the most significant mutation.
309
+ *
310
+ * The selection heuristic is as follows:
311
+ *
312
+ * 1. Priority of Operation Type: High-priority mutations (`delete`, `update`,
313
+ * `replace`, `insertOrUpdate`) are always chosen over low-priority
314
+ * (`insert`) mutations.
315
+ *
316
+ * 2. Selection Strategy:
317
+ * - If any high-priority mutations exist, one is chosen randomly from
318
+ * that group, ignoring the number of rows.
319
+ * - If only `insert` mutations exist, the one(s) with the largest number
320
+ * of rows are identified, and one is chosen randomly from that subset.
321
+ *
322
+ * @protected
323
+ * @param mutations The list of mutations from which to select the key.
324
+ */
325
+ protected _setMutationKey(mutations: spannerClient.spanner.v1.Mutation[]): void;
326
+ /**
327
+ * Modifies transaction selector to include the multiplexed session previous
328
+ * transaction id.
329
+ * This is essential for operations that use an `inline begin`.
330
+ * @protected
331
+ * @param transaction The transaction selector object that will be mutated
332
+ * to include the multiplexed session previous transaction id.
333
+ */
334
+ protected _setPreviousTransactionId(transaction: spannerClient.spanner.v1.ITransactionSelector): void;
296
335
  /**
297
336
  * @typedef {object} TransactionResponse
298
337
  * @property {string|Buffer} id The transaction ID.
@@ -909,7 +948,7 @@ export declare class Snapshot extends EventEmitter {
909
948
  *
910
949
  * @param {spannerClient.spanner.v1.ITransaction} resp Response object.
911
950
  */
912
- protected _update(resp: spannerClient.spanner.v1.ITransaction): void;
951
+ protected _update(resp: spannerClient.spanner.v1.ITransaction, span: Span): void;
913
952
  /**
914
953
  * Wrap `makeRequest` function with the lock to make sure the inline begin
915
954
  * transaction can happen only once.
@@ -1012,6 +1051,7 @@ export declare class Transaction extends Dml {
1012
1051
  commitTimestamp?: PreciseDate;
1013
1052
  commitTimestampProto?: spannerClient.protobuf.ITimestamp;
1014
1053
  private _queuedMutations;
1054
+ private _retryCommit;
1015
1055
  /**
1016
1056
  * Timestamp at which the transaction was committed. Will be populated once
1017
1057
  * {@link Transaction#commit} is called.
@@ -1695,3 +1735,4 @@ export declare class PartitionedDml extends Dml {
1695
1735
  runUpdate(query: string | ExecuteSqlRequest): Promise<RunUpdateResponse>;
1696
1736
  runUpdate(query: string | ExecuteSqlRequest, callback: RunUpdateCallback): void;
1697
1737
  }
1738
+ export {};