@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.
- package/README.md +2 -0
- package/build/protos/google/spanner/admin/database/v1/spanner_database_admin.proto +35 -0
- package/build/protos/google/spanner/v1/change_stream.proto +451 -0
- package/build/protos/google/spanner/v1/commit_response.proto +9 -4
- package/build/protos/google/spanner/v1/transaction.proto +40 -356
- package/build/protos/protos.d.ts +1521 -0
- package/build/protos/protos.js +3906 -0
- package/build/protos/protos.json +317 -1
- package/build/src/batch-transaction.js +2 -2
- package/build/src/codec.js +20 -21
- package/build/src/common-grpc/service.js +10 -10
- package/build/src/common.d.ts +1 -0
- package/build/src/common.js +9 -1
- package/build/src/database.d.ts +1 -0
- package/build/src/database.js +2 -0
- package/build/src/helper.d.ts +90 -0
- package/build/src/helper.js +154 -0
- package/build/src/index.d.ts +33 -0
- package/build/src/index.js +178 -8
- package/build/src/instrument.js +3 -2
- package/build/src/metrics/constants.d.ts +36 -0
- package/build/src/metrics/constants.js +106 -0
- package/build/src/metrics/external-types.d.ts +20 -0
- package/build/src/metrics/external-types.js +32 -0
- package/build/src/metrics/interceptor.d.ts +13 -0
- package/build/src/metrics/interceptor.js +87 -0
- package/build/src/metrics/metrics-tracer-factory.d.ts +165 -0
- package/build/src/metrics/metrics-tracer-factory.js +389 -0
- package/build/src/metrics/metrics-tracer.d.ts +204 -0
- package/build/src/metrics/metrics-tracer.js +371 -0
- package/build/src/metrics/spanner-metrics-exporter.d.ts +35 -0
- package/build/src/metrics/spanner-metrics-exporter.js +119 -0
- package/build/src/metrics/transform.d.ts +144 -0
- package/build/src/metrics/transform.js +272 -0
- package/build/src/partial-result-stream.js +9 -5
- package/build/src/session-factory.d.ts +34 -0
- package/build/src/session-factory.js +30 -0
- package/build/src/session-pool.js +1 -2
- package/build/src/transaction-runner.d.ts +1 -0
- package/build/src/transaction-runner.js +6 -0
- package/build/src/transaction.d.ts +42 -1
- package/build/src/transaction.js +192 -42
- package/build/src/v1/database_admin_client.d.ts +34 -0
- package/build/src/v1/database_admin_client.js +167 -1
- package/build/src/v1/database_admin_client_config.json +4 -0
- package/build/src/v1/instance_admin_client.d.ts +120 -0
- package/build/src/v1/instance_admin_client.js +312 -13
- package/build/src/v1/spanner_client.js +108 -0
- package/build/src/v1/spanner_proto_list.json +1 -0
- package/package.json +12 -5
|
@@ -0,0 +1,389 @@
|
|
|
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.MetricsTracerFactory = void 0;
|
|
17
|
+
const crypto = require("crypto");
|
|
18
|
+
const os = require("os");
|
|
19
|
+
const process = require("process");
|
|
20
|
+
const uuid_1 = require("uuid");
|
|
21
|
+
const sdk_metrics_1 = require("@opentelemetry/sdk-metrics");
|
|
22
|
+
const resources_1 = require("@opentelemetry/resources");
|
|
23
|
+
const opentelemetry_resource_util_1 = require("@google-cloud/opentelemetry-resource-util");
|
|
24
|
+
const Constants = require("./constants");
|
|
25
|
+
const metrics_tracer_1 = require("./metrics-tracer");
|
|
26
|
+
const version = require('../../../package.json').version;
|
|
27
|
+
/**
|
|
28
|
+
* Factory class for creating and managing MetricsTracer instances and OTEL metric instruments.
|
|
29
|
+
*
|
|
30
|
+
* The MetricsTracerFactory is responsible for:
|
|
31
|
+
* - Creating and managing a singleton instance for metrics collection.
|
|
32
|
+
* - Initializing and providing OTEL MeterProvider.
|
|
33
|
+
* - Generating and storing client-specific metadata (UID, hash, name, location, projectId).
|
|
34
|
+
* - Creating and tracking MetricsTracer instances for individual gRPC Spanner operations.
|
|
35
|
+
* - Providing utility methods for extracting resource attributes and managing tracers.
|
|
36
|
+
*
|
|
37
|
+
* This class is designed to be used as a singleton. Metrics collection can be enabled or disabled
|
|
38
|
+
* globally via the static `enabled` property, that is set from the SpannerClient.
|
|
39
|
+
*/
|
|
40
|
+
class MetricsTracerFactory {
|
|
41
|
+
static _instance = null;
|
|
42
|
+
_meterProvider = null;
|
|
43
|
+
_instrumentAttemptCounter;
|
|
44
|
+
_instrumentAttemptLatency;
|
|
45
|
+
_instrumentOperationCounter;
|
|
46
|
+
_instrumentOperationLatency;
|
|
47
|
+
_instrumentGfeConnectivityErrorCount;
|
|
48
|
+
_instrumentGfeLatency;
|
|
49
|
+
_instrumentAfeConnectivityErrorCount;
|
|
50
|
+
_instrumentAfeLatency;
|
|
51
|
+
_clientHash;
|
|
52
|
+
_clientName;
|
|
53
|
+
_clientUid;
|
|
54
|
+
_location = 'global';
|
|
55
|
+
_projectId;
|
|
56
|
+
_currentOperationTracers = new Map();
|
|
57
|
+
_currentOperationLastUpdatedMs = new Map();
|
|
58
|
+
_intervalTracerCleanup;
|
|
59
|
+
static _readers = [];
|
|
60
|
+
static enabled = true;
|
|
61
|
+
/**
|
|
62
|
+
* Private constructor to enforce singleton pattern.
|
|
63
|
+
* Initializes client metadata and detects client location if metrics are enabled.
|
|
64
|
+
* Location will default to global if host machine is not a GCE or GKE instance.
|
|
65
|
+
* @param projectId The GCP project ID used by the Spanner Client.
|
|
66
|
+
*/
|
|
67
|
+
constructor(projectId) {
|
|
68
|
+
this._projectId = projectId;
|
|
69
|
+
this._clientUid = MetricsTracerFactory._generateClientUId();
|
|
70
|
+
this._clientName = `${Constants.SPANNER_METER_NAME}/${version}`;
|
|
71
|
+
// Only perform async call to retrieve location is metrics are enabled.
|
|
72
|
+
if (MetricsTracerFactory.enabled) {
|
|
73
|
+
(async () => {
|
|
74
|
+
const location = await MetricsTracerFactory._detectClientLocation();
|
|
75
|
+
this._location = location.length > 0 ? location : 'global';
|
|
76
|
+
})().catch(error => {
|
|
77
|
+
throw error;
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
this._clientHash = MetricsTracerFactory._generateClientHash(this._clientUid);
|
|
81
|
+
// Start the Tracer cleanup task at an interval
|
|
82
|
+
this._intervalTracerCleanup = setInterval(this._cleanMetricsTracers.bind(this), Constants.TRACER_CLEANUP_INTERVAL_MS);
|
|
83
|
+
// unref the interval to prevent it from blocking app termination
|
|
84
|
+
// in the event loop
|
|
85
|
+
this._intervalTracerCleanup.unref();
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Returns the singleton instance of MetricsTracerFactory.
|
|
89
|
+
* If metrics are disabled, returns null.
|
|
90
|
+
* The instance is created only once, and enabling/disabling metrics can only be done on the initial call.
|
|
91
|
+
* @param projectId Optional GCP project ID for the factory instantiation. Does nothing for subsequent calls.
|
|
92
|
+
* @returns The singleton MetricsTracerFactory instance or null if disabled.
|
|
93
|
+
*/
|
|
94
|
+
static getInstance(projectId = '') {
|
|
95
|
+
if (!MetricsTracerFactory.enabled) {
|
|
96
|
+
return null;
|
|
97
|
+
}
|
|
98
|
+
// Create a singleton instance, enabling/disabling metrics can only be done on the initial call
|
|
99
|
+
if (MetricsTracerFactory._instance === null) {
|
|
100
|
+
MetricsTracerFactory._instance = new MetricsTracerFactory(projectId);
|
|
101
|
+
}
|
|
102
|
+
return MetricsTracerFactory._instance;
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Returns the MeterProvider, creating it and metric instruments if not already initialized.
|
|
106
|
+
* Client-wide attributes that are known at this time are cached to be provided to all MetricsTracers.
|
|
107
|
+
* @param readers Optional array of MetricReader instances to attach to the MeterProvider.
|
|
108
|
+
* @returns The OTEL MeterProvider instance.
|
|
109
|
+
*/
|
|
110
|
+
getMeterProvider(readers = []) {
|
|
111
|
+
if (this._meterProvider === null) {
|
|
112
|
+
const resource = new resources_1.Resource({
|
|
113
|
+
[Constants.MONITORED_RES_LABEL_KEY_PROJECT]: this._projectId,
|
|
114
|
+
[Constants.MONITORED_RES_LABEL_KEY_CLIENT_HASH]: this._clientHash,
|
|
115
|
+
[Constants.MONITORED_RES_LABEL_KEY_LOCATION]: this._location,
|
|
116
|
+
[Constants.MONITORED_RES_LABEL_KEY_INSTANCE]: 'unknown',
|
|
117
|
+
[Constants.MONITORED_RES_LABEL_KEY_INSTANCE_CONFIG]: 'unknown',
|
|
118
|
+
});
|
|
119
|
+
MetricsTracerFactory._readers = readers;
|
|
120
|
+
this._meterProvider = new sdk_metrics_1.MeterProvider({
|
|
121
|
+
resource: resource,
|
|
122
|
+
readers: readers,
|
|
123
|
+
views: Constants.METRIC_VIEWS,
|
|
124
|
+
});
|
|
125
|
+
this._createMetricInstruments();
|
|
126
|
+
}
|
|
127
|
+
return this._meterProvider;
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* Resets the singleton instance of the MetricsTracerFactory.
|
|
131
|
+
*/
|
|
132
|
+
static async resetInstance() {
|
|
133
|
+
clearInterval(MetricsTracerFactory._instance?._intervalTracerCleanup);
|
|
134
|
+
await MetricsTracerFactory._instance?.resetMeterProvider();
|
|
135
|
+
MetricsTracerFactory._instance = null;
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* Resets the MeterProvider.
|
|
139
|
+
*/
|
|
140
|
+
async resetMeterProvider() {
|
|
141
|
+
if (this._meterProvider !== null) {
|
|
142
|
+
await this._meterProvider.shutdown();
|
|
143
|
+
}
|
|
144
|
+
this._meterProvider = null;
|
|
145
|
+
this._currentOperationTracers = new Map();
|
|
146
|
+
this._currentOperationLastUpdatedMs = new Map();
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* Returns the attempt latency histogram instrument.
|
|
150
|
+
*/
|
|
151
|
+
get instrumentAttemptLatency() {
|
|
152
|
+
return this._instrumentAttemptLatency;
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Returns the attempt counter instrument.
|
|
156
|
+
*/
|
|
157
|
+
get instrumentAttemptCounter() {
|
|
158
|
+
return this._instrumentAttemptCounter;
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* Returns the operation latency histogram instrument.
|
|
162
|
+
*/
|
|
163
|
+
get instrumentOperationLatency() {
|
|
164
|
+
return this._instrumentOperationLatency;
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* Returns the operation counter instrument.
|
|
168
|
+
*/
|
|
169
|
+
get instrumentOperationCounter() {
|
|
170
|
+
return this._instrumentOperationCounter;
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* Returns the GFE connectivity error count counter instrument.
|
|
174
|
+
*/
|
|
175
|
+
get instrumentGfeConnectivityErrorCount() {
|
|
176
|
+
return this._instrumentGfeConnectivityErrorCount;
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* Returns the GFE latency histogram instrument.
|
|
180
|
+
*/
|
|
181
|
+
get instrumentGfeLatency() {
|
|
182
|
+
return this._instrumentGfeLatency;
|
|
183
|
+
}
|
|
184
|
+
/**
|
|
185
|
+
* Returns the Client UID.
|
|
186
|
+
*/
|
|
187
|
+
get clientUid() {
|
|
188
|
+
return this._clientUid;
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* Returns the Client Name.
|
|
192
|
+
*/
|
|
193
|
+
get clientName() {
|
|
194
|
+
return this._clientName;
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* Creates a new MetricsTracer for a given resource name and method, and stores it for later retrieval.
|
|
198
|
+
* Returns null if metrics are disabled.
|
|
199
|
+
* @param formattedName The formatted resource name (e.g., full database path).
|
|
200
|
+
* @param method The gRPC method name.
|
|
201
|
+
* @returns A new MetricsTracer instance or null if metrics are disabled.
|
|
202
|
+
*/
|
|
203
|
+
createMetricsTracer(method, formattedName, requestId) {
|
|
204
|
+
if (!MetricsTracerFactory.enabled) {
|
|
205
|
+
return null;
|
|
206
|
+
}
|
|
207
|
+
const operationRequest = this._extractOperationRequest(requestId);
|
|
208
|
+
if (this._currentOperationTracers.has(operationRequest)) {
|
|
209
|
+
return this._currentOperationTracers.get(operationRequest);
|
|
210
|
+
}
|
|
211
|
+
const { instance, database } = this.getInstanceAttributes(formattedName);
|
|
212
|
+
const tracer = new metrics_tracer_1.MetricsTracer(this._instrumentAttemptCounter, this._instrumentAttemptLatency, this._instrumentOperationCounter, this._instrumentOperationLatency, this._instrumentGfeConnectivityErrorCount, this._instrumentGfeLatency, this._instrumentAfeConnectivityErrorCount, this._instrumentAfeLatency, MetricsTracerFactory.enabled, database, instance, method, operationRequest);
|
|
213
|
+
this._currentOperationTracers.set(operationRequest, tracer);
|
|
214
|
+
this._currentOperationLastUpdatedMs.set(operationRequest, Date.now());
|
|
215
|
+
return tracer;
|
|
216
|
+
}
|
|
217
|
+
/**
|
|
218
|
+
* Takes a formatted name and parses the project, instance, and database.
|
|
219
|
+
* @param formattedName The formatted resource name (e.g., full database path).
|
|
220
|
+
* @returns An object containing project, instance, and database strings.
|
|
221
|
+
*/
|
|
222
|
+
getInstanceAttributes(formattedName) {
|
|
223
|
+
if (typeof formattedName !== 'string' || formattedName === '') {
|
|
224
|
+
return {
|
|
225
|
+
project: Constants.UNKNOWN_ATTRIBUTE,
|
|
226
|
+
instance: Constants.UNKNOWN_ATTRIBUTE,
|
|
227
|
+
database: Constants.UNKNOWN_ATTRIBUTE,
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
const regex = /projects\/(?<projectId>[^/]+)\/instances\/(?<instanceId>[^/]+)(?:\/databases\/(?<databaseId>[^/]+))?/;
|
|
231
|
+
const match = formattedName.match(regex);
|
|
232
|
+
const project = match?.groups?.projectId || Constants.UNKNOWN_ATTRIBUTE;
|
|
233
|
+
const instance = match?.groups?.instanceId || Constants.UNKNOWN_ATTRIBUTE;
|
|
234
|
+
const database = match?.groups?.databaseId || Constants.UNKNOWN_ATTRIBUTE;
|
|
235
|
+
return { project: project, instance: instance, database: database };
|
|
236
|
+
}
|
|
237
|
+
/**
|
|
238
|
+
* Retrieves the current MetricsTracer for a given request id.
|
|
239
|
+
* Returns null if no tracer exists for the request.
|
|
240
|
+
* Does not implicitly create MetricsTracers as that should be done
|
|
241
|
+
* explicitly using the createMetricsTracer function.
|
|
242
|
+
* request id is expected to be as set in the gRPC metadata.
|
|
243
|
+
* @param requestId The request id of the gRPC call set under 'x-goog-spanner-request-id'.
|
|
244
|
+
* @returns The MetricsTracer instance or null if not found.
|
|
245
|
+
*/
|
|
246
|
+
getCurrentTracer(requestId) {
|
|
247
|
+
const operationRequest = this._extractOperationRequest(requestId);
|
|
248
|
+
if (!this._currentOperationTracers.has(operationRequest)) {
|
|
249
|
+
// Attempting to retrieve tracer that doesn't exist.
|
|
250
|
+
return null;
|
|
251
|
+
}
|
|
252
|
+
this._currentOperationLastUpdatedMs.set(operationRequest, Date.now());
|
|
253
|
+
return this._currentOperationTracers.get(operationRequest) ?? null;
|
|
254
|
+
}
|
|
255
|
+
/**
|
|
256
|
+
* Removes the MetricsTracer associated with the given request id.
|
|
257
|
+
* @param requestId The request id of the gRPC call set under 'x-goog-spanner-request-id'.
|
|
258
|
+
*/
|
|
259
|
+
clearCurrentTracer(requestId) {
|
|
260
|
+
const operationRequest = this._extractOperationRequest(requestId);
|
|
261
|
+
if (!this._currentOperationTracers.has(operationRequest)) {
|
|
262
|
+
return;
|
|
263
|
+
}
|
|
264
|
+
this._currentOperationTracers.delete(operationRequest);
|
|
265
|
+
this._currentOperationLastUpdatedMs.delete(operationRequest);
|
|
266
|
+
}
|
|
267
|
+
_extractOperationRequest(requestId) {
|
|
268
|
+
if (!requestId) {
|
|
269
|
+
return '';
|
|
270
|
+
}
|
|
271
|
+
const regex = /^(\d+\.[a-z0-9]+\.\d+\.\d+\.\d+)\.\d+$/i;
|
|
272
|
+
const match = requestId.match(regex);
|
|
273
|
+
if (!match) {
|
|
274
|
+
return '';
|
|
275
|
+
}
|
|
276
|
+
const request = match[1];
|
|
277
|
+
return request;
|
|
278
|
+
}
|
|
279
|
+
/**
|
|
280
|
+
* Creates and initializes all metric instruments (counters and histograms) for the MeterProvider.
|
|
281
|
+
* Instruments are only created if metrics are enabled.
|
|
282
|
+
*/
|
|
283
|
+
_createMetricInstruments() {
|
|
284
|
+
if (!MetricsTracerFactory.enabled) {
|
|
285
|
+
return;
|
|
286
|
+
}
|
|
287
|
+
const meter = this.getMeterProvider().getMeter(Constants.SPANNER_METER_NAME, version);
|
|
288
|
+
this._instrumentAttemptLatency = meter.createHistogram(Constants.METRIC_NAME_ATTEMPT_LATENCIES, { unit: 'ms', description: 'Time an individual attempt took.' });
|
|
289
|
+
this._instrumentAttemptCounter = meter.createCounter(Constants.METRIC_NAME_ATTEMPT_COUNT, { unit: '1', description: 'Number of attempts.' });
|
|
290
|
+
this._instrumentOperationLatency = meter.createHistogram(Constants.METRIC_NAME_OPERATION_LATENCIES, {
|
|
291
|
+
unit: 'ms',
|
|
292
|
+
description: 'Total time until final operation success or failure, including retries and backoff.',
|
|
293
|
+
});
|
|
294
|
+
this._instrumentOperationCounter = meter.createCounter(Constants.METRIC_NAME_OPERATION_COUNT, { unit: '1', description: 'Number of operations.' });
|
|
295
|
+
this._instrumentGfeLatency = meter.createHistogram(Constants.METRIC_NAME_GFE_LATENCIES, {
|
|
296
|
+
unit: 'ms',
|
|
297
|
+
description: "Latency between Google's network receiving an RPC and reading back the first byte of the response",
|
|
298
|
+
});
|
|
299
|
+
this._instrumentGfeConnectivityErrorCount = meter.createCounter(Constants.METRIC_NAME_GFE_CONNECTIVITY_ERROR_COUNT, {
|
|
300
|
+
unit: '1',
|
|
301
|
+
description: 'Number of requests that failed to reach the Google network.',
|
|
302
|
+
});
|
|
303
|
+
this._instrumentAfeLatency = meter.createHistogram(Constants.METRIC_NAME_AFE_LATENCIES, {
|
|
304
|
+
unit: 'ms',
|
|
305
|
+
description: 'Latency between Spanner API Frontend receiving an RPC and starting to write back the response',
|
|
306
|
+
});
|
|
307
|
+
this._instrumentAfeConnectivityErrorCount = meter.createCounter(Constants.METRIC_NAME_AFE_CONNECTIVITY_ERROR_COUNT, {
|
|
308
|
+
unit: '1',
|
|
309
|
+
description: 'Number of requests that failed to reach the Spanner API Frontend.',
|
|
310
|
+
});
|
|
311
|
+
}
|
|
312
|
+
/**
|
|
313
|
+
* Generates a unique identifier for the client_uid metric field. The identifier is composed of a
|
|
314
|
+
* UUID, the process ID (PID), and the hostname.
|
|
315
|
+
* @returns A unique string identifier for the client.
|
|
316
|
+
*/
|
|
317
|
+
static _generateClientUId() {
|
|
318
|
+
const identifier = (0, uuid_1.v4)();
|
|
319
|
+
const pid = process.pid.toString();
|
|
320
|
+
let hostname = 'localhost';
|
|
321
|
+
try {
|
|
322
|
+
hostname = os.hostname();
|
|
323
|
+
}
|
|
324
|
+
catch (err) {
|
|
325
|
+
console.warn('Unable to get the hostname.', err);
|
|
326
|
+
}
|
|
327
|
+
return `${identifier}@${pid}@${hostname}`;
|
|
328
|
+
}
|
|
329
|
+
/**
|
|
330
|
+
* Generates a 6-digit zero-padded lowercase hexadecimal hash using the 10 most significant bits
|
|
331
|
+
* of a 64-bit hash value.
|
|
332
|
+
*
|
|
333
|
+
* The primary purpose of this function is to generate a hash value for the `client_hash`
|
|
334
|
+
* resource label using `client_uid` metric field. The range of values is chosen to be small
|
|
335
|
+
* enough to keep the cardinality of the Resource targets under control. Note: If at later time
|
|
336
|
+
* the range needs to be increased, it can be done by increasing the value of `kPrefixLength` to
|
|
337
|
+
* up to 24 bits without changing the format of the returned value.
|
|
338
|
+
* @param clientUid The client UID string to hash.
|
|
339
|
+
* @returns A 6-digit hexadecimal hash string.
|
|
340
|
+
*/
|
|
341
|
+
static _generateClientHash(clientUid) {
|
|
342
|
+
if (clientUid === null || clientUid === undefined) {
|
|
343
|
+
return '000000';
|
|
344
|
+
}
|
|
345
|
+
const hash = crypto.createHash('sha256');
|
|
346
|
+
hash.update(clientUid);
|
|
347
|
+
const digest = hash.digest('hex');
|
|
348
|
+
const hashPart = digest.substring(0, 16);
|
|
349
|
+
const longHash = BigInt('0x' + hashPart);
|
|
350
|
+
const kPrefixLength = 10;
|
|
351
|
+
const shiftedValue = longHash >> BigInt(64 - kPrefixLength);
|
|
352
|
+
return shiftedValue.toString(16).padStart(6, '0');
|
|
353
|
+
}
|
|
354
|
+
/**
|
|
355
|
+
* Gets the location (region) of the client, otherwise returns to the "global" region.
|
|
356
|
+
* Uses GcpDetectorSync to detect the region from the environment.
|
|
357
|
+
* @returns The detected region string, or "global" if not found.
|
|
358
|
+
*/
|
|
359
|
+
static async _detectClientLocation() {
|
|
360
|
+
const defaultRegion = 'global';
|
|
361
|
+
try {
|
|
362
|
+
const resource = await (0, resources_1.detectResources)({
|
|
363
|
+
detectors: [new opentelemetry_resource_util_1.GcpDetectorSync()],
|
|
364
|
+
});
|
|
365
|
+
await resource?.waitForAsyncAttributes?.();
|
|
366
|
+
const region = resource.attributes[Constants.ATTR_CLOUD_REGION];
|
|
367
|
+
if (typeof region === 'string' && region) {
|
|
368
|
+
return region;
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
catch (err) {
|
|
372
|
+
console.warn('Unable to detect location.', err);
|
|
373
|
+
}
|
|
374
|
+
return defaultRegion;
|
|
375
|
+
}
|
|
376
|
+
_cleanMetricsTracers() {
|
|
377
|
+
if (this._currentOperationLastUpdatedMs.size === 0) {
|
|
378
|
+
return;
|
|
379
|
+
}
|
|
380
|
+
for (const [operationTracer, lastUpdated,] of this._currentOperationLastUpdatedMs.entries()) {
|
|
381
|
+
if (Date.now() - lastUpdated >= Constants.TRACER_CLEANUP_THRESHOLD_MS) {
|
|
382
|
+
this._currentOperationTracers.delete(operationTracer);
|
|
383
|
+
this._currentOperationLastUpdatedMs.delete(operationTracer);
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
exports.MetricsTracerFactory = MetricsTracerFactory;
|
|
389
|
+
//# sourceMappingURL=metrics-tracer-factory.js.map
|
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
import { status as Status } from '@grpc/grpc-js';
|
|
2
|
+
import { Counter, Histogram } from '@opentelemetry/api';
|
|
3
|
+
/**
|
|
4
|
+
* MetricAttemptTracer tracks the start time and status of a single gRPC attempt.
|
|
5
|
+
*
|
|
6
|
+
* This class is used to record the timestamp when an attempt begins and to store
|
|
7
|
+
* the status code of the attempt upon completion. It is to be used
|
|
8
|
+
* by MetricsTracer to monitor and report metrics for each individual gRPC call attempt.
|
|
9
|
+
*/
|
|
10
|
+
declare class MetricAttemptTracer {
|
|
11
|
+
private _startTime;
|
|
12
|
+
status: string;
|
|
13
|
+
constructor();
|
|
14
|
+
/**
|
|
15
|
+
* Returns the start time of the attempt.
|
|
16
|
+
*/
|
|
17
|
+
get startTime(): Date;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* MetricOperationTracer tracks the lifecycle and metadata of a single gRPC spanner operation,
|
|
21
|
+
* which may consist of multiple attempts.
|
|
22
|
+
*
|
|
23
|
+
* This class is responsible for:
|
|
24
|
+
* - Recording the start time of the operation.
|
|
25
|
+
* - Tracking the number of attempts made for the operation.
|
|
26
|
+
* - Holding a reference to the current attempt's tracer (MetricAttemptTracer).
|
|
27
|
+
* - Storing the final status code of the operation.
|
|
28
|
+
*
|
|
29
|
+
* Usage:
|
|
30
|
+
* - Call `start()` to reset the operation's start time.
|
|
31
|
+
* - Call `createNewAttempt()` to begin tracking a new attempt within the operation.
|
|
32
|
+
* - Access `currentAttempt` to retrieve the current MetricAttemptTracer instance.
|
|
33
|
+
* - Access `attemptCount` to get the number of attempts made so far.
|
|
34
|
+
* - Access `startTime` to get the operation's start time.
|
|
35
|
+
* - Set or read `status` to track the operation's final status code.
|
|
36
|
+
*/
|
|
37
|
+
declare class MetricOperationTracer {
|
|
38
|
+
private _attemptCount;
|
|
39
|
+
private _startTime;
|
|
40
|
+
private _currentAttempt;
|
|
41
|
+
constructor();
|
|
42
|
+
/**
|
|
43
|
+
* Returns the number of attempts made for this operation.
|
|
44
|
+
*/
|
|
45
|
+
get attemptCount(): number;
|
|
46
|
+
/**
|
|
47
|
+
* Returns the current MetricAttemptTracer instance for the ongoing attempt.
|
|
48
|
+
*/
|
|
49
|
+
get currentAttempt(): MetricAttemptTracer | null;
|
|
50
|
+
/**
|
|
51
|
+
* Returns the start time of the operation.
|
|
52
|
+
*/
|
|
53
|
+
get startTime(): Date;
|
|
54
|
+
/**
|
|
55
|
+
* Increments the attempt count and creates a new MetricAttemptTracer
|
|
56
|
+
* for tracking the next attempt within this operation.
|
|
57
|
+
*/
|
|
58
|
+
createNewAttempt(): void;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* MetricsTracer is responsible for recording and managing metrics related to
|
|
62
|
+
* gRPC Spanner operations and attempts counters, and latencies,
|
|
63
|
+
* as well as Google Front End (GFE)/AFE metrics such as latency and connectivity errors.
|
|
64
|
+
*
|
|
65
|
+
* This class provides methods to record the start and completion of operations
|
|
66
|
+
* and attempts, extract GFE/AFE latency from response headers.
|
|
67
|
+
* It also handles setting of required Spanner metric attributes to
|
|
68
|
+
* be later consumed by the SpannerMetricsExporter.
|
|
69
|
+
*/
|
|
70
|
+
export declare class MetricsTracer {
|
|
71
|
+
private _instrumentAttemptCounter;
|
|
72
|
+
private _instrumentAttemptLatency;
|
|
73
|
+
private _instrumentOperationCounter;
|
|
74
|
+
private _instrumentOperationLatency;
|
|
75
|
+
private _instrumentGfeConnectivityErrorCount;
|
|
76
|
+
private _instrumentGfeLatency;
|
|
77
|
+
private _instrumentAfeConnectivityErrorCount;
|
|
78
|
+
private _instrumentAfeLatency;
|
|
79
|
+
enabled: boolean;
|
|
80
|
+
private _database;
|
|
81
|
+
private _instance;
|
|
82
|
+
private _methodName;
|
|
83
|
+
private _request;
|
|
84
|
+
/**
|
|
85
|
+
* The current MetricOperationTracer instance tracking the ongoing operation.
|
|
86
|
+
*/
|
|
87
|
+
currentOperation: MetricOperationTracer | null;
|
|
88
|
+
/**
|
|
89
|
+
* Stores client and resource attributes for labeling metrics.
|
|
90
|
+
*/
|
|
91
|
+
private _clientAttributes;
|
|
92
|
+
gfeLatency: number | null;
|
|
93
|
+
afeLatency: number | null;
|
|
94
|
+
/**
|
|
95
|
+
* Constructs a new MetricsTracer.
|
|
96
|
+
*
|
|
97
|
+
* @param _instrumentAttemptCounter Counter for attempt count metrics.
|
|
98
|
+
* @param _instrumentAttemptLatency Histogram for attempt latency metrics.
|
|
99
|
+
* @param _instrumentOperationCounter Counter for operation count metrics.
|
|
100
|
+
* @param _instrumentOperationLatency Histogram for operation latency metrics.
|
|
101
|
+
* @param _instrumentGfeConnectivityErrorCount Counter for GFE connectivity errors.
|
|
102
|
+
* @param _instrumentGfeLatency Histogram for GFE latency metrics.
|
|
103
|
+
* @param _instrumentAfeConnectivityErrorCount Counter for AFE connectivity errors.
|
|
104
|
+
* @param _instrumentAfeLatency Histogram for AFE latency metrics.
|
|
105
|
+
* @param enabled Whether metrics recording is enabled.
|
|
106
|
+
*/
|
|
107
|
+
constructor(_instrumentAttemptCounter: Counter | null, _instrumentAttemptLatency: Histogram | null, _instrumentOperationCounter: Counter | null, _instrumentOperationLatency: Histogram | null, _instrumentGfeConnectivityErrorCount: Counter | null, _instrumentGfeLatency: Histogram | null, _instrumentAfeConnectivityErrorCount: Counter | null, _instrumentAfeLatency: Histogram | null, enabled: boolean, _database: string, _instance: string, _methodName: string, _request: string);
|
|
108
|
+
/**
|
|
109
|
+
* Returns the difference in milliseconds between two Date objects.
|
|
110
|
+
* @param start The start time.
|
|
111
|
+
* @param end The end time.
|
|
112
|
+
* @returns The time difference in milliseconds.
|
|
113
|
+
*/
|
|
114
|
+
private _getMillisecondTimeDifference;
|
|
115
|
+
/**
|
|
116
|
+
* Gets the current client and resource attributes for metrics.
|
|
117
|
+
*/
|
|
118
|
+
get clientAttributes(): {
|
|
119
|
+
[key: string]: string;
|
|
120
|
+
};
|
|
121
|
+
/**
|
|
122
|
+
* Gets the attempt counter OTEL instrument.
|
|
123
|
+
*/
|
|
124
|
+
get instrumentAttemptCounter(): Counter<import("@opentelemetry/api").Attributes> | null;
|
|
125
|
+
/**
|
|
126
|
+
* Gets the attempt latency histogram OTEL instrument.
|
|
127
|
+
*/
|
|
128
|
+
get instrumentAttemptLatency(): Histogram<import("@opentelemetry/api").Attributes> | null;
|
|
129
|
+
/**
|
|
130
|
+
* Gets the operation counter OTEL instrument.
|
|
131
|
+
*/
|
|
132
|
+
get instrumentOperationCounter(): Counter<import("@opentelemetry/api").Attributes> | null;
|
|
133
|
+
/**
|
|
134
|
+
* Gets the operation latency histogram OTEL instrument.
|
|
135
|
+
*/
|
|
136
|
+
get instrumentOperationLatency(): Histogram<import("@opentelemetry/api").Attributes> | null;
|
|
137
|
+
/**
|
|
138
|
+
* Records the start of a new attempt within the current operation.
|
|
139
|
+
* Increments the attempt count and creates a new MetricAttemptTracer.
|
|
140
|
+
*/
|
|
141
|
+
recordAttemptStart(): void;
|
|
142
|
+
/**
|
|
143
|
+
* Records the completion of the current attempt, including its status and latency.
|
|
144
|
+
* These statuses code are defined in grpc.status
|
|
145
|
+
* @param status The status code of the attempt (default: Status.OK).
|
|
146
|
+
*/
|
|
147
|
+
recordAttemptCompletion(statusCode?: Status): void;
|
|
148
|
+
/**
|
|
149
|
+
* Records the start of a new operation, resetting the operation tracer and start time.
|
|
150
|
+
*/
|
|
151
|
+
recordOperationStart(): void;
|
|
152
|
+
/**
|
|
153
|
+
* Records the completion of the current operation, including its status,
|
|
154
|
+
* latency, and attempt count. Also clears the current tracer from the factory.
|
|
155
|
+
*/
|
|
156
|
+
recordOperationCompletion(): void;
|
|
157
|
+
/**
|
|
158
|
+
* Extracts the GFE latency value (in milliseconds) from a 'server-timing' header string.
|
|
159
|
+
* Returns null if the header is missing or does not contain a valid latency value.
|
|
160
|
+
*
|
|
161
|
+
* @param header The 'server-timing' header string.
|
|
162
|
+
* @returns The extracted GFE latency in milliseconds, or null if not found.
|
|
163
|
+
*/
|
|
164
|
+
extractGfeLatency(header: string): number | null;
|
|
165
|
+
/**
|
|
166
|
+
* Extracts the AFE latency value (in milliseconds) from a 'server-timing' header string.
|
|
167
|
+
* Returns null if the header is missing or does not contain a valid latency value.
|
|
168
|
+
*
|
|
169
|
+
* @param header The 'server-timing' header string.
|
|
170
|
+
* @returns The extracted AFE latency in milliseconds, or null if not found.
|
|
171
|
+
*/
|
|
172
|
+
extractAfeLatency(header: string): number | null;
|
|
173
|
+
/**
|
|
174
|
+
* Records the provided GFE latency.
|
|
175
|
+
* @param latency The GFE latency in milliseconds.
|
|
176
|
+
*/
|
|
177
|
+
recordGfeLatency(statusCode: Status): void;
|
|
178
|
+
/**
|
|
179
|
+
* Increments the GFE connectivity error count metric.
|
|
180
|
+
*/
|
|
181
|
+
recordGfeConnectivityErrorCount(statusCode: Status): void;
|
|
182
|
+
/**
|
|
183
|
+
* Increments the AFE connectivity error count metric.
|
|
184
|
+
*/
|
|
185
|
+
recordAfeConnectivityErrorCount(statusCode: Status): void;
|
|
186
|
+
/**
|
|
187
|
+
* Records the provided AFE latency.
|
|
188
|
+
* @param latency The AFE latency in milliseconds.
|
|
189
|
+
*/
|
|
190
|
+
recordAfeLatency(statusCode: Status): void;
|
|
191
|
+
/**
|
|
192
|
+
* Creates and returns a set of OTEL attributes for operation-level metrics.
|
|
193
|
+
* @returns The operation attributes object.
|
|
194
|
+
*/
|
|
195
|
+
private _createOperationOtelAttributes;
|
|
196
|
+
/**
|
|
197
|
+
* Creates and returns a set of OTEL attributes for attempt-level metrics.
|
|
198
|
+
* The overall operation status is set at this time based on the last
|
|
199
|
+
* attempt's status.
|
|
200
|
+
* @returns The attempt attributes object.
|
|
201
|
+
*/
|
|
202
|
+
private _createAttemptOtelAttributes;
|
|
203
|
+
}
|
|
204
|
+
export {};
|