@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,371 @@
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
+ // https://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.MetricsTracer = void 0;
17
+ const grpc_js_1 = require("@grpc/grpc-js");
18
+ const metrics_tracer_factory_1 = require("./metrics-tracer-factory");
19
+ const constants_1 = require("./constants");
20
+ const __1 = require("..");
21
+ /**
22
+ * MetricAttemptTracer tracks the start time and status of a single gRPC attempt.
23
+ *
24
+ * This class is used to record the timestamp when an attempt begins and to store
25
+ * the status code of the attempt upon completion. It is to be used
26
+ * by MetricsTracer to monitor and report metrics for each individual gRPC call attempt.
27
+ */
28
+ class MetricAttemptTracer {
29
+ _startTime;
30
+ status;
31
+ constructor() {
32
+ this._startTime = new Date(Date.now());
33
+ this.status = grpc_js_1.status[grpc_js_1.status.UNKNOWN];
34
+ }
35
+ /**
36
+ * Returns the start time of the attempt.
37
+ */
38
+ get startTime() {
39
+ return this._startTime;
40
+ }
41
+ }
42
+ /**
43
+ * MetricOperationTracer tracks the lifecycle and metadata of a single gRPC spanner operation,
44
+ * which may consist of multiple attempts.
45
+ *
46
+ * This class is responsible for:
47
+ * - Recording the start time of the operation.
48
+ * - Tracking the number of attempts made for the operation.
49
+ * - Holding a reference to the current attempt's tracer (MetricAttemptTracer).
50
+ * - Storing the final status code of the operation.
51
+ *
52
+ * Usage:
53
+ * - Call `start()` to reset the operation's start time.
54
+ * - Call `createNewAttempt()` to begin tracking a new attempt within the operation.
55
+ * - Access `currentAttempt` to retrieve the current MetricAttemptTracer instance.
56
+ * - Access `attemptCount` to get the number of attempts made so far.
57
+ * - Access `startTime` to get the operation's start time.
58
+ * - Set or read `status` to track the operation's final status code.
59
+ */
60
+ class MetricOperationTracer {
61
+ _attemptCount;
62
+ _startTime;
63
+ _currentAttempt;
64
+ constructor() {
65
+ this._attemptCount = 0;
66
+ this._startTime = new Date(Date.now());
67
+ this._currentAttempt = null;
68
+ }
69
+ /**
70
+ * Returns the number of attempts made for this operation.
71
+ */
72
+ get attemptCount() {
73
+ return this._attemptCount;
74
+ }
75
+ /**
76
+ * Returns the current MetricAttemptTracer instance for the ongoing attempt.
77
+ */
78
+ get currentAttempt() {
79
+ return this._currentAttempt;
80
+ }
81
+ /**
82
+ * Returns the start time of the operation.
83
+ */
84
+ get startTime() {
85
+ return this._startTime;
86
+ }
87
+ /**
88
+ * Increments the attempt count and creates a new MetricAttemptTracer
89
+ * for tracking the next attempt within this operation.
90
+ */
91
+ createNewAttempt() {
92
+ this._attemptCount += 1;
93
+ this._currentAttempt = new MetricAttemptTracer();
94
+ }
95
+ }
96
+ /**
97
+ * MetricsTracer is responsible for recording and managing metrics related to
98
+ * gRPC Spanner operations and attempts counters, and latencies,
99
+ * as well as Google Front End (GFE)/AFE metrics such as latency and connectivity errors.
100
+ *
101
+ * This class provides methods to record the start and completion of operations
102
+ * and attempts, extract GFE/AFE latency from response headers.
103
+ * It also handles setting of required Spanner metric attributes to
104
+ * be later consumed by the SpannerMetricsExporter.
105
+ */
106
+ class MetricsTracer {
107
+ _instrumentAttemptCounter;
108
+ _instrumentAttemptLatency;
109
+ _instrumentOperationCounter;
110
+ _instrumentOperationLatency;
111
+ _instrumentGfeConnectivityErrorCount;
112
+ _instrumentGfeLatency;
113
+ _instrumentAfeConnectivityErrorCount;
114
+ _instrumentAfeLatency;
115
+ enabled;
116
+ _database;
117
+ _instance;
118
+ _methodName;
119
+ _request;
120
+ /**
121
+ * The current MetricOperationTracer instance tracking the ongoing operation.
122
+ */
123
+ currentOperation = null;
124
+ /**
125
+ * Stores client and resource attributes for labeling metrics.
126
+ */
127
+ _clientAttributes = {};
128
+ /*
129
+ * The current GFE latency associated with this tracer.
130
+ */
131
+ gfeLatency = null;
132
+ /*
133
+ * The current AFE latency associated with this tracer.
134
+ */
135
+ afeLatency = null;
136
+ /**
137
+ * Constructs a new MetricsTracer.
138
+ *
139
+ * @param _instrumentAttemptCounter Counter for attempt count metrics.
140
+ * @param _instrumentAttemptLatency Histogram for attempt latency metrics.
141
+ * @param _instrumentOperationCounter Counter for operation count metrics.
142
+ * @param _instrumentOperationLatency Histogram for operation latency metrics.
143
+ * @param _instrumentGfeConnectivityErrorCount Counter for GFE connectivity errors.
144
+ * @param _instrumentGfeLatency Histogram for GFE latency metrics.
145
+ * @param _instrumentAfeConnectivityErrorCount Counter for AFE connectivity errors.
146
+ * @param _instrumentAfeLatency Histogram for AFE latency metrics.
147
+ * @param enabled Whether metrics recording is enabled.
148
+ */
149
+ constructor(_instrumentAttemptCounter, _instrumentAttemptLatency, _instrumentOperationCounter, _instrumentOperationLatency, _instrumentGfeConnectivityErrorCount, _instrumentGfeLatency, _instrumentAfeConnectivityErrorCount, _instrumentAfeLatency, enabled, _database, _instance, _methodName, _request) {
150
+ this._instrumentAttemptCounter = _instrumentAttemptCounter;
151
+ this._instrumentAttemptLatency = _instrumentAttemptLatency;
152
+ this._instrumentOperationCounter = _instrumentOperationCounter;
153
+ this._instrumentOperationLatency = _instrumentOperationLatency;
154
+ this._instrumentGfeConnectivityErrorCount = _instrumentGfeConnectivityErrorCount;
155
+ this._instrumentGfeLatency = _instrumentGfeLatency;
156
+ this._instrumentAfeConnectivityErrorCount = _instrumentAfeConnectivityErrorCount;
157
+ this._instrumentAfeLatency = _instrumentAfeLatency;
158
+ this.enabled = enabled;
159
+ this._database = _database;
160
+ this._instance = _instance;
161
+ this._methodName = _methodName;
162
+ this._request = _request;
163
+ this._clientAttributes[constants_1.METRIC_LABEL_KEY_DATABASE] = _database;
164
+ this._clientAttributes[constants_1.METRIC_LABEL_KEY_METHOD] = _methodName;
165
+ this._clientAttributes[constants_1.MONITORED_RES_LABEL_KEY_INSTANCE] = _instance;
166
+ }
167
+ /**
168
+ * Returns the difference in milliseconds between two Date objects.
169
+ * @param start The start time.
170
+ * @param end The end time.
171
+ * @returns The time difference in milliseconds.
172
+ */
173
+ _getMillisecondTimeDifference(start, end) {
174
+ return end.valueOf() - start.valueOf();
175
+ }
176
+ /**
177
+ * Gets the current client and resource attributes for metrics.
178
+ */
179
+ get clientAttributes() {
180
+ return this._clientAttributes;
181
+ }
182
+ /**
183
+ * Gets the attempt counter OTEL instrument.
184
+ */
185
+ get instrumentAttemptCounter() {
186
+ return this._instrumentAttemptCounter;
187
+ }
188
+ /**
189
+ * Gets the attempt latency histogram OTEL instrument.
190
+ */
191
+ get instrumentAttemptLatency() {
192
+ return this._instrumentAttemptLatency;
193
+ }
194
+ /**
195
+ * Gets the operation counter OTEL instrument.
196
+ */
197
+ get instrumentOperationCounter() {
198
+ return this._instrumentOperationCounter;
199
+ }
200
+ /**
201
+ * Gets the operation latency histogram OTEL instrument.
202
+ */
203
+ get instrumentOperationLatency() {
204
+ return this._instrumentOperationLatency;
205
+ }
206
+ /**
207
+ * Records the start of a new attempt within the current operation.
208
+ * Increments the attempt count and creates a new MetricAttemptTracer.
209
+ */
210
+ recordAttemptStart() {
211
+ if (!this.enabled)
212
+ return;
213
+ this.currentOperation.createNewAttempt();
214
+ }
215
+ /**
216
+ * Records the completion of the current attempt, including its status and latency.
217
+ * These statuses code are defined in grpc.status
218
+ * @param status The status code of the attempt (default: Status.OK).
219
+ */
220
+ recordAttemptCompletion(statusCode = grpc_js_1.status.OK) {
221
+ if (!this.enabled)
222
+ return;
223
+ this.currentOperation.currentAttempt.status = grpc_js_1.status[statusCode];
224
+ const attemptAttributes = this._createAttemptOtelAttributes();
225
+ const endTime = new Date(Date.now());
226
+ const attemptLatencyMilliseconds = this._getMillisecondTimeDifference(this.currentOperation.currentAttempt.startTime, endTime);
227
+ this.instrumentAttemptLatency?.record(attemptLatencyMilliseconds, attemptAttributes);
228
+ this.instrumentAttemptCounter?.add(1, attemptAttributes);
229
+ }
230
+ /**
231
+ * Records the start of a new operation, resetting the operation tracer and start time.
232
+ */
233
+ recordOperationStart() {
234
+ if (!this.enabled)
235
+ return;
236
+ if (this.currentOperation !== null) {
237
+ return; // Don't re-start an already started operation
238
+ }
239
+ this.currentOperation = new MetricOperationTracer();
240
+ }
241
+ /**
242
+ * Records the completion of the current operation, including its status,
243
+ * latency, and attempt count. Also clears the current tracer from the factory.
244
+ */
245
+ recordOperationCompletion() {
246
+ if (!this.enabled || !this.currentOperation)
247
+ return;
248
+ const endTime = new Date(Date.now());
249
+ const operationAttributes = this._createOperationOtelAttributes();
250
+ const operationLatencyMilliseconds = this._getMillisecondTimeDifference(this.currentOperation.startTime, endTime);
251
+ this.instrumentOperationCounter?.add(1, operationAttributes);
252
+ this.instrumentOperationLatency?.record(operationLatencyMilliseconds, operationAttributes);
253
+ metrics_tracer_factory_1.MetricsTracerFactory.getInstance().clearCurrentTracer(this._request);
254
+ }
255
+ /**
256
+ * Extracts the GFE latency value (in milliseconds) from a 'server-timing' header string.
257
+ * Returns null if the header is missing or does not contain a valid latency value.
258
+ *
259
+ * @param header The 'server-timing' header string.
260
+ * @returns The extracted GFE latency in milliseconds, or null if not found.
261
+ */
262
+ extractGfeLatency(header) {
263
+ const regex = /gfet4t7; dur=([0-9]+).*/;
264
+ if (header === undefined)
265
+ return null;
266
+ const match = header.match(regex);
267
+ if (!match)
268
+ return null;
269
+ return Number(match[1]);
270
+ }
271
+ /**
272
+ * Extracts the AFE latency value (in milliseconds) from a 'server-timing' header string.
273
+ * Returns null if the header is missing or does not contain a valid latency value.
274
+ *
275
+ * @param header The 'server-timing' header string.
276
+ * @returns The extracted AFE latency in milliseconds, or null if not found.
277
+ */
278
+ extractAfeLatency(header) {
279
+ if (!__1.Spanner.isAFEServerTimingEnabled())
280
+ return null;
281
+ const regex = /afe; dur=([0-9]+).*/;
282
+ if (header === undefined)
283
+ return null;
284
+ const match = header.match(regex);
285
+ if (!match)
286
+ return null;
287
+ return Number(match[1]);
288
+ }
289
+ /**
290
+ * Records the provided GFE latency.
291
+ * @param latency The GFE latency in milliseconds.
292
+ */
293
+ recordGfeLatency(statusCode) {
294
+ if (!this.enabled)
295
+ return;
296
+ if (!this.gfeLatency) {
297
+ console.error('ERROR: Attempted to record GFE metric with no latency value.');
298
+ return;
299
+ }
300
+ const attributes = { ...this._clientAttributes };
301
+ attributes[constants_1.METRIC_LABEL_KEY_STATUS] = grpc_js_1.status[statusCode];
302
+ this._instrumentGfeLatency?.record(this.gfeLatency, attributes);
303
+ this.gfeLatency = null; // Reset latency value
304
+ }
305
+ /**
306
+ * Increments the GFE connectivity error count metric.
307
+ */
308
+ recordGfeConnectivityErrorCount(statusCode) {
309
+ if (!this.enabled)
310
+ return;
311
+ const attributes = { ...this._clientAttributes };
312
+ attributes[constants_1.METRIC_LABEL_KEY_STATUS] = grpc_js_1.status[statusCode];
313
+ this._instrumentGfeConnectivityErrorCount?.add(1, attributes);
314
+ }
315
+ /**
316
+ * Increments the AFE connectivity error count metric.
317
+ */
318
+ recordAfeConnectivityErrorCount(statusCode) {
319
+ if (!this.enabled || !__1.Spanner.isAFEServerTimingEnabled())
320
+ return;
321
+ const attributes = { ...this._clientAttributes };
322
+ attributes[constants_1.METRIC_LABEL_KEY_STATUS] = grpc_js_1.status[statusCode];
323
+ this._instrumentAfeConnectivityErrorCount?.add(1, attributes);
324
+ }
325
+ /**
326
+ * Records the provided AFE latency.
327
+ * @param latency The AFE latency in milliseconds.
328
+ */
329
+ recordAfeLatency(statusCode) {
330
+ if (!this.enabled || !__1.Spanner.isAFEServerTimingEnabled())
331
+ return;
332
+ if (!this.afeLatency) {
333
+ console.error('ERROR: Attempted to record AFE metric with no latency value.');
334
+ return;
335
+ }
336
+ const attributes = { ...this._clientAttributes };
337
+ attributes[constants_1.METRIC_LABEL_KEY_STATUS] = grpc_js_1.status[statusCode];
338
+ this._instrumentAfeLatency?.record(this.afeLatency, attributes);
339
+ this.afeLatency = null; // Reset latency value
340
+ }
341
+ /**
342
+ * Creates and returns a set of OTEL attributes for operation-level metrics.
343
+ * @returns The operation attributes object.
344
+ */
345
+ _createOperationOtelAttributes() {
346
+ if (!this.enabled)
347
+ return {};
348
+ const attributes = { ...this._clientAttributes };
349
+ attributes[constants_1.METRIC_LABEL_KEY_STATUS] =
350
+ this.currentOperation.currentAttempt?.status ?? grpc_js_1.status[grpc_js_1.status.UNKNOWN];
351
+ return attributes;
352
+ }
353
+ /**
354
+ * Creates and returns a set of OTEL attributes for attempt-level metrics.
355
+ * The overall operation status is set at this time based on the last
356
+ * attempt's status.
357
+ * @returns The attempt attributes object.
358
+ */
359
+ _createAttemptOtelAttributes() {
360
+ if (!this.enabled)
361
+ return {};
362
+ const attributes = { ...this._clientAttributes };
363
+ if (this.currentOperation?.currentAttempt === null)
364
+ return attributes;
365
+ attributes[constants_1.METRIC_LABEL_KEY_STATUS] =
366
+ this.currentOperation.currentAttempt.status;
367
+ return attributes;
368
+ }
369
+ }
370
+ exports.MetricsTracer = MetricsTracer;
371
+ //# sourceMappingURL=metrics-tracer.js.map
@@ -0,0 +1,35 @@
1
+ import { PushMetricExporter, ResourceMetrics } from '@opentelemetry/sdk-metrics';
2
+ import { ExportResult } from '@opentelemetry/core';
3
+ import { ExporterOptions } from './external-types';
4
+ export declare const MAX_BATCH_EXPORT_SIZE = 200;
5
+ /**
6
+ * Format and sends metrics information to Google Cloud Monitoring.
7
+ */
8
+ export declare class CloudMonitoringMetricsExporter implements PushMetricExporter {
9
+ private _projectId;
10
+ private _lastExported;
11
+ private readonly _client;
12
+ constructor({ auth }: ExporterOptions);
13
+ /**
14
+ * Implementation for {@link PushMetricExporter.export}.
15
+ * Calls the async wrapper method {@link _exportAsync} and
16
+ * assures no rejected promises bubble up to the caller.
17
+ *
18
+ * @param metrics Metrics to be sent to the Google Cloud 3Monitoring backend
19
+ * @param resultCallback result callback to be called on finish
20
+ */
21
+ export(metrics: ResourceMetrics, resultCallback: (result: ExportResult) => void): void;
22
+ shutdown(): Promise<void>;
23
+ forceFlush(): Promise<void>;
24
+ /**
25
+ * Asnyc wrapper for the {@link export} implementation.
26
+ * Writes the current values of all exported {@link MetricRecord}s
27
+ * to the Google Cloud Monitoring backend.
28
+ *
29
+ * @param resourceMetrics Metrics to be sent to the Google Cloud Monitoring backend
30
+ */
31
+ private _exportAsync;
32
+ private _sendTimeSeries;
33
+ /** Returns the minimum number of arrays of max size chunkSize, partitioned from the given array. */
34
+ private _partitionList;
35
+ }
@@ -0,0 +1,119 @@
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.CloudMonitoringMetricsExporter = exports.MAX_BATCH_EXPORT_SIZE = void 0;
17
+ const core_1 = require("@opentelemetry/core");
18
+ const monitoring_1 = require("@google-cloud/monitoring");
19
+ const transform_1 = require("./transform");
20
+ const grpc_js_1 = require("@grpc/grpc-js");
21
+ const constants_1 = require("./constants");
22
+ // Stackdriver Monitoring v3 only accepts up to 200 TimeSeries per
23
+ // CreateTimeSeries call.
24
+ exports.MAX_BATCH_EXPORT_SIZE = 200;
25
+ /**
26
+ * Format and sends metrics information to Google Cloud Monitoring.
27
+ */
28
+ class CloudMonitoringMetricsExporter {
29
+ _projectId;
30
+ _lastExported = new Date(0);
31
+ _client;
32
+ constructor({ auth }) {
33
+ this._client = new monitoring_1.MetricServiceClient({ auth: auth });
34
+ // Start this async process as early as possible. It will be
35
+ // awaited on the first export because constructors are synchronous
36
+ this._projectId = auth.getProjectId().catch(err => {
37
+ console.error(err);
38
+ });
39
+ }
40
+ /**
41
+ * Implementation for {@link PushMetricExporter.export}.
42
+ * Calls the async wrapper method {@link _exportAsync} and
43
+ * assures no rejected promises bubble up to the caller.
44
+ *
45
+ * @param metrics Metrics to be sent to the Google Cloud 3Monitoring backend
46
+ * @param resultCallback result callback to be called on finish
47
+ */
48
+ export(metrics, resultCallback) {
49
+ // Do not export metrics if we've already exported within the last 30s
50
+ const now = new Date();
51
+ if (now.getTime() - this._lastExported.getTime() <=
52
+ constants_1.MIN_EXPORT_FREQUENCY_MS) {
53
+ return;
54
+ }
55
+ this._lastExported = now;
56
+ this._exportAsync(metrics).then(resultCallback, err => {
57
+ console.error(err.message);
58
+ resultCallback({ code: core_1.ExportResultCode.FAILED, error: err });
59
+ });
60
+ }
61
+ async shutdown() { }
62
+ async forceFlush() { }
63
+ /**
64
+ * Asnyc wrapper for the {@link export} implementation.
65
+ * Writes the current values of all exported {@link MetricRecord}s
66
+ * to the Google Cloud Monitoring backend.
67
+ *
68
+ * @param resourceMetrics Metrics to be sent to the Google Cloud Monitoring backend
69
+ */
70
+ async _exportAsync(resourceMetrics) {
71
+ if (this._projectId instanceof Promise) {
72
+ this._projectId = await this._projectId;
73
+ }
74
+ if (!this._projectId) {
75
+ const error = new Error('expecting a non-blank ProjectID');
76
+ console.error(error.message);
77
+ return { code: core_1.ExportResultCode.FAILED, error };
78
+ }
79
+ const timeSeriesList = (0, transform_1.transformResourceMetricToTimeSeriesArray)(resourceMetrics);
80
+ let failure = {
81
+ sendFailed: false,
82
+ };
83
+ await Promise.all(this._partitionList(timeSeriesList, exports.MAX_BATCH_EXPORT_SIZE).map(async (batchedTimeSeries) => this._sendTimeSeries(batchedTimeSeries))).catch(e => {
84
+ const error = e;
85
+ if (error.code === grpc_js_1.status.PERMISSION_DENIED) {
86
+ console.warn(`Need monitoring metric writer permission on project ${this._projectId}. Follow https://cloud.google.com/spanner/docs/view-manage-client-side-metrics#access-client-side-metrics to set up permissions`);
87
+ }
88
+ const err = asError(e);
89
+ err.message = `Send TimeSeries failed: ${err.message}`;
90
+ failure = { sendFailed: true, error: err };
91
+ console.error(`ERROR: ${err.message}`);
92
+ });
93
+ return failure.sendFailed
94
+ ? {
95
+ code: core_1.ExportResultCode.FAILED,
96
+ error: failure.error,
97
+ }
98
+ : { code: core_1.ExportResultCode.SUCCESS };
99
+ }
100
+ async _sendTimeSeries(timeSeries) {
101
+ if (timeSeries.length === 0) {
102
+ return Promise.resolve();
103
+ }
104
+ // TODO: Use createServiceTimeSeries when it is available
105
+ await this._client.createTimeSeries({
106
+ name: `projects/${this._projectId}`,
107
+ timeSeries: timeSeries,
108
+ });
109
+ }
110
+ /** Returns the minimum number of arrays of max size chunkSize, partitioned from the given array. */
111
+ _partitionList(list, chunkSize) {
112
+ return Array.from({ length: Math.ceil(list.length / chunkSize) }, (_, i) => list.slice(i * chunkSize, (i + 1) * chunkSize));
113
+ }
114
+ }
115
+ exports.CloudMonitoringMetricsExporter = CloudMonitoringMetricsExporter;
116
+ function asError(error) {
117
+ return error instanceof Error ? error : new Error(String(error));
118
+ }
119
+ //# sourceMappingURL=spanner-metrics-exporter.js.map
@@ -0,0 +1,144 @@
1
+ import { MetricData, DataPoint, ResourceMetrics } from '@opentelemetry/sdk-metrics';
2
+ import { Resource } from '@opentelemetry/resources';
3
+ import { MonitoredResource } from '@google-cloud/opentelemetry-resource-util';
4
+ import { MetricKind, ValueType } from './external-types';
5
+ /** Transforms a OpenTelemetry instrument type to a GCM MetricKind. */
6
+ declare function _transformMetricKind(metric: MetricData): MetricKind;
7
+ /** Transforms resource to Google Cloud Monitoring monitored resource */
8
+ declare function _transformResource(labels: {
9
+ [key: string]: string;
10
+ }): MonitoredResource;
11
+ /** Transforms a OpenTelemetry ValueType to a GCM ValueType. */
12
+ declare function _transformValueType(metric: MetricData): ValueType;
13
+ /**
14
+ * Convert the metrics data to a list of Google Cloud Monitoring time series.
15
+ */
16
+ export declare function transformResourceMetricToTimeSeriesArray(resourceMetrics: ResourceMetrics): {
17
+ metric: {
18
+ type: string;
19
+ labels: {};
20
+ };
21
+ resource: MonitoredResource;
22
+ metricKind: MetricKind;
23
+ valueType: ValueType;
24
+ points: ({
25
+ value: {
26
+ int64Value: string;
27
+ doubleValue?: undefined;
28
+ } | {
29
+ doubleValue: string;
30
+ int64Value?: undefined;
31
+ };
32
+ interval: {
33
+ endTime: {
34
+ seconds: any;
35
+ nanos: any;
36
+ };
37
+ startTime?: {
38
+ seconds: any;
39
+ nanos: any;
40
+ } | undefined;
41
+ };
42
+ } | {
43
+ value: {
44
+ distributionValue: {
45
+ count: string;
46
+ mean: number;
47
+ bucketOptions: any;
48
+ bucketCounts: string[];
49
+ };
50
+ };
51
+ interval: {
52
+ startTime: {
53
+ seconds: any;
54
+ nanos: any;
55
+ };
56
+ endTime: {
57
+ seconds: any;
58
+ nanos: any;
59
+ };
60
+ };
61
+ } | {
62
+ value: unknown;
63
+ interval: {
64
+ endTime: {
65
+ seconds: any;
66
+ nanos: any;
67
+ };
68
+ startTime?: undefined;
69
+ };
70
+ })[];
71
+ unit: string;
72
+ }[];
73
+ /**
74
+ * Transform timeseries's point, so that metric can be uploaded to GCM.
75
+ */
76
+ declare function _transformPoint<T>(metric: MetricData, dataPoint: DataPoint<T>): {
77
+ value: {
78
+ int64Value: string;
79
+ doubleValue?: undefined;
80
+ } | {
81
+ doubleValue: string;
82
+ int64Value?: undefined;
83
+ };
84
+ interval: {
85
+ endTime: {
86
+ seconds: any;
87
+ nanos: any;
88
+ };
89
+ startTime?: {
90
+ seconds: any;
91
+ nanos: any;
92
+ } | undefined;
93
+ };
94
+ } | {
95
+ value: {
96
+ distributionValue: {
97
+ count: string;
98
+ mean: number;
99
+ bucketOptions: any;
100
+ bucketCounts: string[];
101
+ };
102
+ };
103
+ interval: {
104
+ startTime: {
105
+ seconds: any;
106
+ nanos: any;
107
+ };
108
+ endTime: {
109
+ seconds: any;
110
+ nanos: any;
111
+ };
112
+ };
113
+ } | {
114
+ value: T;
115
+ interval: {
116
+ endTime: {
117
+ seconds: any;
118
+ nanos: any;
119
+ };
120
+ startTime?: undefined;
121
+ };
122
+ };
123
+ /** Extracts metric and monitored resource labels from data point */
124
+ declare function _extractLabels<T>({ attributes }: DataPoint<T> | Resource): {
125
+ metricLabels: {};
126
+ monitoredResourceLabels: {};
127
+ };
128
+ declare function _normalizeLabelKey(key: string): string;
129
+ /** Transforms an OpenTelemetry time value to a GCM time value. */
130
+ declare function _formatHrTimeToGcmTime(hrTime: any): {
131
+ seconds: any;
132
+ nanos: any;
133
+ };
134
+ export declare const _TEST_ONLY: {
135
+ _normalizeLabelKey: typeof _normalizeLabelKey;
136
+ _transformMetricKind: typeof _transformMetricKind;
137
+ _extractLabels: typeof _extractLabels;
138
+ _formatHrTimeToGcmTime: typeof _formatHrTimeToGcmTime;
139
+ _transformResource: typeof _transformResource;
140
+ _transformPoint: typeof _transformPoint;
141
+ _transformValueType: typeof _transformValueType;
142
+ transformResourceMetricToTimeSeriesArray: typeof transformResourceMetricToTimeSeriesArray;
143
+ };
144
+ export {};