@google-cloud/spanner 9.0.0 → 9.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/README.md +3 -16
  2. package/build/src/backup.js.map +1 -0
  3. package/build/src/batch-transaction.js +15 -12
  4. package/build/src/batch-transaction.js.map +1 -0
  5. package/build/src/codec.d.ts +6 -0
  6. package/build/src/codec.js +99 -34
  7. package/build/src/codec.js.map +1 -0
  8. package/build/src/common-grpc/service-object.js.map +1 -0
  9. package/build/src/common-grpc/service.js.map +1 -0
  10. package/build/src/common.d.ts +14 -0
  11. package/build/src/common.js +27 -1
  12. package/build/src/common.js.map +1 -0
  13. package/build/src/database.d.ts +31 -41
  14. package/build/src/database.js +122 -313
  15. package/build/src/database.js.map +1 -0
  16. package/build/src/helper.d.ts +12 -0
  17. package/build/src/helper.js +44 -0
  18. package/build/src/helper.js.map +1 -0
  19. package/build/src/index.d.ts +33 -8
  20. package/build/src/index.js +338 -134
  21. package/build/src/index.js.map +1 -0
  22. package/build/src/instance-config.js.map +1 -0
  23. package/build/src/instance.d.ts +15 -2
  24. package/build/src/instance.js +11 -2
  25. package/build/src/instance.js.map +1 -0
  26. package/build/src/instrument.d.ts +12 -1
  27. package/build/src/instrument.js +13 -0
  28. package/build/src/instrument.js.map +1 -0
  29. package/build/src/metrics/constants.d.ts +6 -0
  30. package/build/src/metrics/constants.js +6 -1
  31. package/build/src/metrics/constants.js.map +1 -0
  32. package/build/src/metrics/external-types.d.ts +9 -1
  33. package/build/src/metrics/external-types.js.map +1 -0
  34. package/build/src/metrics/interceptor.js +32 -28
  35. package/build/src/metrics/interceptor.js.map +1 -0
  36. package/build/src/metrics/metrics-tracer-factory.d.ts +24 -18
  37. package/build/src/metrics/metrics-tracer-factory.js +94 -77
  38. package/build/src/metrics/metrics-tracer-factory.js.map +1 -0
  39. package/build/src/metrics/metrics-tracer.d.ts +19 -6
  40. package/build/src/metrics/metrics-tracer.js +147 -55
  41. package/build/src/metrics/metrics-tracer.js.map +1 -0
  42. package/build/src/metrics/spanner-metrics-exporter.d.ts +49 -1
  43. package/build/src/metrics/spanner-metrics-exporter.js +207 -4
  44. package/build/src/metrics/spanner-metrics-exporter.js.map +1 -0
  45. package/build/src/metrics/transform.d.ts +2 -2
  46. package/build/src/metrics/transform.js +7 -7
  47. package/build/src/metrics/transform.js.map +1 -0
  48. package/build/src/multiplexed-session.d.ts +13 -2
  49. package/build/src/multiplexed-session.js +20 -4
  50. package/build/src/multiplexed-session.js.map +1 -0
  51. package/build/src/partial-result-stream.d.ts +26 -33
  52. package/build/src/partial-result-stream.js +263 -283
  53. package/build/src/partial-result-stream.js.map +1 -0
  54. package/build/src/protos.js.map +1 -0
  55. package/build/src/request-stream-coordinator.d.ts +88 -0
  56. package/build/src/request-stream-coordinator.js +229 -0
  57. package/build/src/request-stream-coordinator.js.map +1 -0
  58. package/build/src/request_id_header.d.ts +6 -4
  59. package/build/src/request_id_header.js +24 -24
  60. package/build/src/request_id_header.js.map +1 -0
  61. package/build/src/session-factory.d.ts +52 -63
  62. package/build/src/session-factory.js +41 -92
  63. package/build/src/session-factory.js.map +1 -0
  64. package/build/src/session-pool.d.ts +97 -227
  65. package/build/src/session-pool.js +74 -547
  66. package/build/src/session-pool.js.map +1 -0
  67. package/build/src/session.js +1 -1
  68. package/build/src/session.js.map +1 -0
  69. package/build/src/table.js.map +1 -0
  70. package/build/src/transaction-runner.js +1 -12
  71. package/build/src/transaction-runner.js.map +1 -0
  72. package/build/src/transaction.d.ts +5 -5
  73. package/build/src/transaction.js +72 -112
  74. package/build/src/transaction.js.map +1 -0
  75. package/build/src/v1/index.js.map +1 -0
  76. package/package.json +25 -27
@@ -15,9 +15,8 @@
15
15
  Object.defineProperty(exports, "__esModule", { value: true });
16
16
  exports.MetricsTracer = void 0;
17
17
  const grpc_js_1 = require("@grpc/grpc-js");
18
- const metrics_tracer_factory_1 = require("./metrics-tracer-factory");
19
18
  const constants_1 = require("./constants");
20
- const __1 = require("..");
19
+ const common_1 = require("../common");
21
20
  /**
22
21
  * MetricAttemptTracer tracks the start time and status of a single gRPC attempt.
23
22
  *
@@ -93,6 +92,76 @@ class MetricOperationTracer {
93
92
  this._currentAttempt = new MetricAttemptTracer();
94
93
  }
95
94
  }
95
+ const GFE_METRIC_PREFIX = 'gfet4t7; dur=';
96
+ const AFE_METRIC_PREFIX = 'afe; dur=';
97
+ /**
98
+ * Checks whether a character code represents an entry delimiter or whitespace in a
99
+ * 'server-timing' header (start of string, space, comma, or tab).
100
+ *
101
+ * @param charCode The character code to check.
102
+ * @returns True if the character code is a valid entry separator or whitespace.
103
+ */
104
+ function isEntryDelimiter(charCode) {
105
+ return (charCode === 32 /* ' ' */ ||
106
+ charCode === 44 /* ',' */ ||
107
+ charCode === 9 /* '\t' */);
108
+ }
109
+ /**
110
+ * Parses consecutive ASCII digit characters into an integer starting from the given index.
111
+ * Returns null if the character at startIndex is not a digit (e.g. non-numeric, negative, or empty).
112
+ * Parsing stops at the first non-digit (e.g. ',', ';', or decimal point), matching the legacy
113
+ * regex `([0-9]+)` behavior without intermediate string slice allocations.
114
+ *
115
+ * @param header The 'server-timing' header string.
116
+ * @param startIndex The index where numeric digits are expected to begin.
117
+ * @returns The parsed non-negative integer, or null if no valid digits were found.
118
+ */
119
+ function parseConsecutiveDigits(header, startIndex) {
120
+ if (startIndex >= header.length) {
121
+ return null;
122
+ }
123
+ const firstCharCode = header.charCodeAt(startIndex);
124
+ if (firstCharCode < 48 || firstCharCode > 57) {
125
+ return null;
126
+ }
127
+ let value = firstCharCode - 48;
128
+ for (let index = startIndex + 1; index < header.length; index++) {
129
+ const code = header.charCodeAt(index);
130
+ if (code >= 48 && code <= 57) {
131
+ value = value * 10 + (code - 48);
132
+ }
133
+ else {
134
+ break;
135
+ }
136
+ }
137
+ return value;
138
+ }
139
+ /**
140
+ * Extracts a numeric latency value in milliseconds for a given metric prefix from a
141
+ * 'server-timing' header string without regex allocations or intermediate substring slices.
142
+ *
143
+ * @param header The 'server-timing' header string.
144
+ * @param prefix The metric prefix (e.g. 'gfet4t7; dur=').
145
+ * @returns The extracted latency in milliseconds, or null if not found.
146
+ */
147
+ function extractServerTimingLatency(header, prefix) {
148
+ if (!header || typeof header !== 'string') {
149
+ return null;
150
+ }
151
+ let prefixIndex = header.indexOf(prefix);
152
+ while (prefixIndex !== -1) {
153
+ // Ensure prefix is not part of a longer metric name (e.g., 'safe; dur=' matching 'afe; dur=')
154
+ if (prefixIndex === 0 ||
155
+ isEntryDelimiter(header.charCodeAt(prefixIndex - 1))) {
156
+ const latency = parseConsecutiveDigits(header, prefixIndex + prefix.length);
157
+ if (latency !== null) {
158
+ return latency;
159
+ }
160
+ }
161
+ prefixIndex = header.indexOf(prefix, prefixIndex + 1);
162
+ }
163
+ return null;
164
+ }
96
165
  /**
97
166
  * MetricsTracer is responsible for recording and managing metrics related to
98
167
  * gRPC Spanner operations and attempts counters, and latencies,
@@ -126,6 +195,11 @@ class MetricsTracer {
126
195
  * Stores client and resource attributes for labeling metrics.
127
196
  */
128
197
  _clientAttributes = {};
198
+ /**
199
+ * Cached OTel attribute objects keyed by status name, avoiding repeated
200
+ * object allocations on every metric recording call.
201
+ */
202
+ _attributesByStatus;
129
203
  /*
130
204
  * The current GFE latency associated with this tracer.
131
205
  */
@@ -147,7 +221,7 @@ class MetricsTracer {
147
221
  * @param _instrumentAfeLatency Histogram for AFE latency metrics.
148
222
  * @param enabled Whether metrics recording is enabled.
149
223
  */
150
- constructor(_instrumentAttemptCounter, _instrumentAttemptLatency, _instrumentOperationCounter, _instrumentOperationLatency, _instrumentGfeConnectivityErrorCount, _instrumentGfeLatency, _instrumentAfeConnectivityErrorCount, _instrumentAfeLatency, enabled, _database, _instance, _projectId, _methodName, _request) {
224
+ constructor(_instrumentAttemptCounter, _instrumentAttemptLatency, _instrumentOperationCounter, _instrumentOperationLatency, _instrumentGfeConnectivityErrorCount, _instrumentGfeLatency, _instrumentAfeConnectivityErrorCount, _instrumentAfeLatency, enabled, _database, _instance, _projectId, _methodName, _request, attributesCache) {
151
225
  this._instrumentAttemptCounter = _instrumentAttemptCounter;
152
226
  this._instrumentAttemptLatency = _instrumentAttemptLatency;
153
227
  this._instrumentOperationCounter = _instrumentOperationCounter;
@@ -165,6 +239,8 @@ class MetricsTracer {
165
239
  this._clientAttributes[constants_1.METRIC_LABEL_KEY_DATABASE] = _database;
166
240
  this._clientAttributes[constants_1.METRIC_LABEL_KEY_METHOD] = _methodName;
167
241
  this._clientAttributes[constants_1.MONITORED_RES_LABEL_KEY_INSTANCE] = _instance;
242
+ this._attributesByStatus =
243
+ attributesCache ?? new Map();
168
244
  }
169
245
  /**
170
246
  * Returns the difference in milliseconds between two times.
@@ -210,7 +286,7 @@ class MetricsTracer {
210
286
  * Increments the attempt count and creates a new MetricAttemptTracer.
211
287
  */
212
288
  recordAttemptStart() {
213
- if (!this.enabled)
289
+ if (!this.enabled || !this.currentOperation)
214
290
  return;
215
291
  this.currentOperation.createNewAttempt();
216
292
  }
@@ -220,12 +296,13 @@ class MetricsTracer {
220
296
  * @param status The status code of the attempt (default: Status.OK).
221
297
  */
222
298
  recordAttemptCompletion(statusCode = grpc_js_1.status.OK) {
223
- if (!this.enabled)
299
+ if (!this.enabled || !this.currentOperation?.currentAttempt)
224
300
  return;
225
- this.currentOperation.currentAttempt.status = grpc_js_1.status[statusCode];
301
+ const currentAttempt = this.currentOperation.currentAttempt;
302
+ currentAttempt.status = grpc_js_1.status[statusCode] ?? grpc_js_1.status[grpc_js_1.status.UNKNOWN];
226
303
  const attemptAttributes = this._createAttemptOtelAttributes();
227
304
  const endTime = performance.now();
228
- const attemptLatencyMilliseconds = this._getMillisecondTimeDifference(this.currentOperation.currentAttempt.startTime, endTime);
305
+ const attemptLatencyMilliseconds = this._getMillisecondTimeDifference(currentAttempt.startTime, endTime);
229
306
  this.instrumentAttemptLatency?.record(attemptLatencyMilliseconds, attemptAttributes);
230
307
  this.instrumentAttemptCounter?.add(1, attemptAttributes);
231
308
  }
@@ -252,7 +329,7 @@ class MetricsTracer {
252
329
  const operationLatencyMilliseconds = this._getMillisecondTimeDifference(this.currentOperation.startTime, endTime);
253
330
  this.instrumentOperationCounter?.add(1, operationAttributes);
254
331
  this.instrumentOperationLatency?.record(operationLatencyMilliseconds, operationAttributes);
255
- metrics_tracer_factory_1.MetricsTracerFactory.getInstance(this._projectId).clearCurrentTracer(this._request);
332
+ this.currentOperation = null;
256
333
  }
257
334
  /**
258
335
  * Extracts the GFE latency value (in milliseconds) from a 'server-timing' header string.
@@ -262,13 +339,7 @@ class MetricsTracer {
262
339
  * @returns The extracted GFE latency in milliseconds, or null if not found.
263
340
  */
264
341
  extractGfeLatency(header) {
265
- const regex = /gfet4t7; dur=([0-9]+).*/;
266
- if (header === undefined)
267
- return null;
268
- const match = header.match(regex);
269
- if (!match)
270
- return null;
271
- return Number(match[1]);
342
+ return extractServerTimingLatency(header, GFE_METRIC_PREFIX);
272
343
  }
273
344
  /**
274
345
  * Extracts the AFE latency value (in milliseconds) from a 'server-timing' header string.
@@ -278,66 +349,91 @@ class MetricsTracer {
278
349
  * @returns The extracted AFE latency in milliseconds, or null if not found.
279
350
  */
280
351
  extractAfeLatency(header) {
281
- if (!__1.Spanner.isAFEServerTimingEnabled())
352
+ if (!(0, common_1.isAFEServerTimingEnabled)())
282
353
  return null;
283
- const regex = /afe; dur=([0-9]+).*/;
284
- if (header === undefined)
285
- return null;
286
- const match = header.match(regex);
287
- if (!match)
288
- return null;
289
- return Number(match[1]);
354
+ return extractServerTimingLatency(header, AFE_METRIC_PREFIX);
290
355
  }
291
356
  /**
292
- * Records the provided GFE latency.
293
- * @param latency The GFE latency in milliseconds.
357
+ * Returns a cached set of OTEL attributes for the given status, avoiding
358
+ * repeated object cloning on every metric record/add call.
359
+ *
360
+ * @param status Optional status code (as numeric Status enum or status name string).
361
+ * @returns The cached attributes object.
362
+ */
363
+ _getAttributesForStatus(status) {
364
+ const statusString = typeof status === 'number'
365
+ ? (grpc_js_1.status[status] ?? grpc_js_1.status[grpc_js_1.status.UNKNOWN])
366
+ : typeof status === 'string'
367
+ ? status
368
+ : undefined;
369
+ const cacheKey = statusString ?? '';
370
+ let attributes = this._attributesByStatus.get(cacheKey);
371
+ if (!attributes) {
372
+ const newAttributes = { ...this._clientAttributes };
373
+ if (statusString !== undefined) {
374
+ newAttributes[constants_1.METRIC_LABEL_KEY_STATUS] = statusString;
375
+ }
376
+ attributes = Object.freeze(newAttributes);
377
+ this._attributesByStatus.set(cacheKey, attributes);
378
+ }
379
+ return attributes;
380
+ }
381
+ /**
382
+ * Records the GFE latency for this attempt.
383
+ * @param statusCode The gRPC status code of the attempt.
294
384
  */
295
385
  recordGfeLatency(statusCode) {
296
- if (!this.enabled)
386
+ if (!this.enabled || !this._instrumentGfeLatency)
297
387
  return;
298
- if (!this.gfeLatency) {
388
+ if (typeof this.gfeLatency !== 'number' ||
389
+ !Number.isFinite(this.gfeLatency) ||
390
+ this.gfeLatency < 0) {
299
391
  console.error('ERROR: Attempted to record GFE metric with no latency value.');
300
392
  return;
301
393
  }
302
- const attributes = { ...this._clientAttributes };
303
- attributes[constants_1.METRIC_LABEL_KEY_STATUS] = grpc_js_1.status[statusCode];
304
- this._instrumentGfeLatency?.record(this.gfeLatency, attributes);
394
+ const attributes = this._getAttributesForStatus(statusCode);
395
+ this._instrumentGfeLatency.record(this.gfeLatency, attributes);
305
396
  this.gfeLatency = null; // Reset latency value
306
397
  }
307
398
  /**
308
399
  * Increments the GFE connectivity error count metric.
309
400
  */
310
401
  recordGfeConnectivityErrorCount(statusCode) {
311
- if (!this.enabled)
402
+ if (!this.enabled || !this._instrumentGfeConnectivityErrorCount)
312
403
  return;
313
- const attributes = { ...this._clientAttributes };
314
- attributes[constants_1.METRIC_LABEL_KEY_STATUS] = grpc_js_1.status[statusCode];
315
- this._instrumentGfeConnectivityErrorCount?.add(1, attributes);
404
+ const attributes = this._getAttributesForStatus(statusCode);
405
+ this._instrumentGfeConnectivityErrorCount.add(1, attributes);
316
406
  }
317
407
  /**
318
408
  * Increments the AFE connectivity error count metric.
319
409
  */
320
410
  recordAfeConnectivityErrorCount(statusCode) {
321
- if (!this.enabled || !__1.Spanner.isAFEServerTimingEnabled())
411
+ if (!this.enabled ||
412
+ !this._instrumentAfeConnectivityErrorCount ||
413
+ !(0, common_1.isAFEServerTimingEnabled)()) {
322
414
  return;
323
- const attributes = { ...this._clientAttributes };
324
- attributes[constants_1.METRIC_LABEL_KEY_STATUS] = grpc_js_1.status[statusCode];
325
- this._instrumentAfeConnectivityErrorCount?.add(1, attributes);
415
+ }
416
+ const attributes = this._getAttributesForStatus(statusCode);
417
+ this._instrumentAfeConnectivityErrorCount.add(1, attributes);
326
418
  }
327
419
  /**
328
- * Records the provided AFE latency.
329
- * @param latency The AFE latency in milliseconds.
420
+ * Records the AFE latency for this attempt.
421
+ * @param statusCode The gRPC status code of the attempt.
330
422
  */
331
423
  recordAfeLatency(statusCode) {
332
- if (!this.enabled || !__1.Spanner.isAFEServerTimingEnabled())
424
+ if (!this.enabled ||
425
+ !this._instrumentAfeLatency ||
426
+ !(0, common_1.isAFEServerTimingEnabled)()) {
333
427
  return;
334
- if (!this.afeLatency) {
428
+ }
429
+ if (typeof this.afeLatency !== 'number' ||
430
+ !Number.isFinite(this.afeLatency) ||
431
+ this.afeLatency < 0) {
335
432
  console.error('ERROR: Attempted to record AFE metric with no latency value.');
336
433
  return;
337
434
  }
338
- const attributes = { ...this._clientAttributes };
339
- attributes[constants_1.METRIC_LABEL_KEY_STATUS] = grpc_js_1.status[statusCode];
340
- this._instrumentAfeLatency?.record(this.afeLatency, attributes);
435
+ const attributes = this._getAttributesForStatus(statusCode);
436
+ this._instrumentAfeLatency.record(this.afeLatency, attributes);
341
437
  this.afeLatency = null; // Reset latency value
342
438
  }
343
439
  /**
@@ -347,10 +443,8 @@ class MetricsTracer {
347
443
  _createOperationOtelAttributes() {
348
444
  if (!this.enabled)
349
445
  return {};
350
- const attributes = { ...this._clientAttributes };
351
- attributes[constants_1.METRIC_LABEL_KEY_STATUS] =
352
- this.currentOperation.currentAttempt?.status ?? grpc_js_1.status[grpc_js_1.status.UNKNOWN];
353
- return attributes;
446
+ const status = this.currentOperation?.currentAttempt?.status ?? grpc_js_1.status[grpc_js_1.status.UNKNOWN];
447
+ return this._getAttributesForStatus(status);
354
448
  }
355
449
  /**
356
450
  * Creates and returns a set of OTEL attributes for attempt-level metrics.
@@ -361,12 +455,10 @@ class MetricsTracer {
361
455
  _createAttemptOtelAttributes() {
362
456
  if (!this.enabled)
363
457
  return {};
364
- const attributes = { ...this._clientAttributes };
365
- if (this.currentOperation?.currentAttempt === null)
366
- return attributes;
367
- attributes[constants_1.METRIC_LABEL_KEY_STATUS] =
368
- this.currentOperation.currentAttempt.status;
369
- return attributes;
458
+ if (!this.currentOperation?.currentAttempt) {
459
+ return this._getAttributesForStatus();
460
+ }
461
+ return this._getAttributesForStatus(this.currentOperation.currentAttempt.status);
370
462
  }
371
463
  }
372
464
  exports.MetricsTracer = MetricsTracer;
@@ -0,0 +1 @@
1
+ {"version":3,"file":"metrics-tracer.js","sourceRoot":"","sources":["../../../src/metrics/metrics-tracer.ts"],"names":[],"mappings":";AAAA,4BAA4B;AAC5B,EAAE;AACF,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,kDAAkD;AAClD,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;;;AAEjC,2CAA+C;AAG/C,2CAKqB;AACrB,sCAAmD;AAEnD;;;;;;GAMG;AACH,MAAM,mBAAmB;IACf,UAAU,CAAS;IACpB,MAAM,CAAS;IAEtB;QACE,IAAI,CAAC,UAAU,GAAG,WAAW,CAAC,GAAG,EAAE,CAAC;QACpC,IAAI,CAAC,MAAM,GAAG,gBAAM,CAAC,gBAAM,CAAC,OAAO,CAAC,CAAC;IACvC,CAAC;IAED;;OAEG;IACH,IAAI,SAAS;Q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AK,CACX,8DAA8D,CAC/D,CAAC;YACF,OAAO;QACT,CAAC;QAED,MAAM,UAAU,GAAG,IAAI,CAAC,uBAAuB,CAAC,UAAU,CAAC,CAAC;QAE5D,IAAI,CAAC,qBAAqB,CAAC,MAAM,CAAC,IAAI,CAAC,UAAU,EAAE,UAAU,CAAC,CAAC;QAC/D,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,CAAC,sBAAsB;IAChD,CAAC;IAED;;;OAGG;IACK,8BAA8B;QACpC,IAAI,CAAC,IAAI,CAAC,OAAO;YAAE,OAAO,EAAE,CAAC;QAC7B,MAAM,MAAM,GACV,IAAI,CAAC,gBAAgB,EAAE,cAAc,EAAE,MAAM,IAAI,gBAAM,CAAC,gBAAM,CAAC,OAAO,CAAC,CAAC;QAC1E,OAAO,IAAI,CAAC,uBAAuB,CAAC,MAAM,CAAC,CAAC;IAC9C,CAAC;IAED;;;;;OAKG;IACK,4BAA4B;QAClC,IAAI,CAAC,IAAI,CAAC,OAAO;YAAE,OAAO,EAAE,CAAC;QAC7B,IAAI,CAAC,IAAI,CAAC,gBAAgB,EAAE,cAAc,EAAE,CAAC;YAC3C,OAAO,IAAI,CAAC,uBAAuB,EAAE,CAAC;QACxC,CAAC;QACD,OAAO,IAAI,CAAC,uBAAuB,CACjC,IAAI,CAAC,gBAAgB,CAAC,cAAc,CAAC,MAAM,CAC5C,CAAC;IACJ,CAAC;CACF;AAvUD,sCAuUC"}
@@ -2,6 +2,52 @@ import { PushMetricExporter, ResourceMetrics } from '@opentelemetry/sdk-metrics'
2
2
  import { ExportResult } from '@opentelemetry/core';
3
3
  import { ExporterOptions } from './external-types';
4
4
  export declare const MAX_BATCH_EXPORT_SIZE = 200;
5
+ /**
6
+ * Trims and validates a configured universe domain string.
7
+ *
8
+ * @param universeDomain The universe domain string to normalize.
9
+ * @returns The trimmed non-empty universe domain.
10
+ */
11
+ export declare function normalizeUniverseDomain(universeDomain: string): string;
12
+ /**
13
+ * Formats a parsed monitoring endpoint into a canonical `host` or `host:port` key.
14
+ *
15
+ * @param parsed Parsed endpoint containing `apiEndpoint` and optional `port`.
16
+ * @returns Canonical monitoring target key string.
17
+ */
18
+ export declare function formatMonitoringTargetKey(parsed: {
19
+ apiEndpoint: string;
20
+ port?: number;
21
+ }): string;
22
+ export interface ResolvedExporterConfig {
23
+ clientOptions: Record<string, unknown>;
24
+ universeDomain?: string;
25
+ monitoringEndpoint?: string;
26
+ }
27
+ /**
28
+ * Parses and validates a Cloud Monitoring endpoint string (`host`, `host:port`,
29
+ * `[ipv6]`, or `[ipv6]:port`) into separate `apiEndpoint` and optional `port`
30
+ * fields suitable for `MetricServiceClient` / `google-gax`.
31
+ *
32
+ * Brackets around IPv6 addresses are preserved on `apiEndpoint` because
33
+ * `google-gax` builds the gRPC target as `${servicePath}:${port}`.
34
+ *
35
+ * @param endpoint The monitoring endpoint string to parse.
36
+ * @returns Parsed `{apiEndpoint, port}` object.
37
+ */
38
+ export declare function parseMonitoringEndpoint(endpoint: string): {
39
+ apiEndpoint: string;
40
+ port?: number;
41
+ };
42
+ /**
43
+ * Resolves and validates Cloud Monitoring exporter options into
44
+ * `MetricServiceClient` options plus canonical `universeDomain` and
45
+ * `monitoringEndpoint` keys.
46
+ *
47
+ * @param options Exporter options passed by the caller or `Spanner`.
48
+ * @returns Resolved client options and normalized scope identifiers.
49
+ */
50
+ export declare function resolveExporterConfig(options: ExporterOptions): ResolvedExporterConfig;
5
51
  /**
6
52
  * Format and sends metrics information to Google Cloud Monitoring.
7
53
  */
@@ -9,8 +55,10 @@ export declare class CloudMonitoringMetricsExporter implements PushMetricExporte
9
55
  private _projectId;
10
56
  private _lastExported;
11
57
  private readonly _client;
58
+ private readonly _universeDomain?;
59
+ private readonly _monitoringEndpoint?;
12
60
  private _metricsExportFailureLogged;
13
- constructor({ auth }: ExporterOptions, projectId: string);
61
+ constructor(options: ExporterOptions, projectId: string, resolvedConfig?: ResolvedExporterConfig);
14
62
  /**
15
63
  * Implementation for {@link PushMetricExporter.export}.
16
64
  * Calls the async wrapper method {@link _exportAsync} and
@@ -14,6 +14,10 @@
14
14
  // limitations under the License.
15
15
  Object.defineProperty(exports, "__esModule", { value: true });
16
16
  exports.CloudMonitoringMetricsExporter = exports.MAX_BATCH_EXPORT_SIZE = void 0;
17
+ exports.normalizeUniverseDomain = normalizeUniverseDomain;
18
+ exports.formatMonitoringTargetKey = formatMonitoringTargetKey;
19
+ exports.parseMonitoringEndpoint = parseMonitoringEndpoint;
20
+ exports.resolveExporterConfig = resolveExporterConfig;
17
21
  const core_1 = require("@opentelemetry/core");
18
22
  const monitoring_1 = require("@google-cloud/monitoring");
19
23
  const transform_1 = require("./transform");
@@ -22,6 +26,182 @@ const constants_1 = require("./constants");
22
26
  // Stackdriver Monitoring v3 only accepts up to 200 TimeSeries per
23
27
  // CreateTimeSeries call.
24
28
  exports.MAX_BATCH_EXPORT_SIZE = 200;
29
+ /**
30
+ * Validates that a port number is an integer within the TCP/UDP range 1–65535.
31
+ *
32
+ * @param port The numeric port value to validate.
33
+ * @returns The validated port number.
34
+ */
35
+ function validatePort(port) {
36
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
37
+ throw new Error(`Invalid monitoring endpoint port: ${port}`);
38
+ }
39
+ return port;
40
+ }
41
+ /**
42
+ * Parses and validates a decimal port string within the TCP/UDP range 1–65535.
43
+ *
44
+ * @param portStr The port string extracted from a monitoring endpoint.
45
+ * @returns The validated numeric port.
46
+ */
47
+ function parsePortString(portStr) {
48
+ if (!/^\d+$/.test(portStr)) {
49
+ throw new Error(`Invalid monitoring endpoint port: ${portStr}`);
50
+ }
51
+ return validatePort(Number(portStr));
52
+ }
53
+ /**
54
+ * Trims and validates a configured universe domain string.
55
+ *
56
+ * @param universeDomain The universe domain string to normalize.
57
+ * @returns The trimmed non-empty universe domain.
58
+ */
59
+ function normalizeUniverseDomain(universeDomain) {
60
+ if (typeof universeDomain !== 'string' || universeDomain.trim() === '') {
61
+ throw new Error('universeDomain cannot be empty.');
62
+ }
63
+ return universeDomain.trim();
64
+ }
65
+ /**
66
+ * Formats a parsed monitoring endpoint into a canonical `host` or `host:port` key.
67
+ *
68
+ * @param parsed Parsed endpoint containing `apiEndpoint` and optional `port`.
69
+ * @returns Canonical monitoring target key string.
70
+ */
71
+ function formatMonitoringTargetKey(parsed) {
72
+ return parsed.port !== undefined
73
+ ? `${parsed.apiEndpoint}:${parsed.port}`
74
+ : parsed.apiEndpoint;
75
+ }
76
+ /**
77
+ * Parses and validates a Cloud Monitoring endpoint string (`host`, `host:port`,
78
+ * `[ipv6]`, or `[ipv6]:port`) into separate `apiEndpoint` and optional `port`
79
+ * fields suitable for `MetricServiceClient` / `google-gax`.
80
+ *
81
+ * Brackets around IPv6 addresses are preserved on `apiEndpoint` because
82
+ * `google-gax` builds the gRPC target as `${servicePath}:${port}`.
83
+ *
84
+ * @param endpoint The monitoring endpoint string to parse.
85
+ * @returns Parsed `{apiEndpoint, port}` object.
86
+ */
87
+ function parseMonitoringEndpoint(endpoint) {
88
+ if (typeof endpoint !== 'string' || endpoint.trim() === '') {
89
+ throw new Error('Monitoring endpoint cannot be empty.');
90
+ }
91
+ if (endpoint !== endpoint.trim() || /\s/.test(endpoint)) {
92
+ throw new Error('Monitoring endpoint must not contain whitespace.');
93
+ }
94
+ if (/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(endpoint) ||
95
+ endpoint.startsWith('http:') ||
96
+ endpoint.startsWith('https:')) {
97
+ throw new Error('Monitoring endpoint must not include a protocol scheme (http/https).');
98
+ }
99
+ if (endpoint.includes('/') ||
100
+ endpoint.includes('?') ||
101
+ endpoint.includes('#')) {
102
+ throw new Error('Monitoring endpoint must not contain path, query, or fragment components.');
103
+ }
104
+ let host;
105
+ let embeddedPort;
106
+ if (endpoint.startsWith('[')) {
107
+ const closeIdx = endpoint.indexOf(']');
108
+ if (closeIdx === -1) {
109
+ throw new Error('Monitoring endpoint has an unclosed IPv6 bracket.');
110
+ }
111
+ const innerHost = endpoint.slice(1, closeIdx);
112
+ if (innerHost.length === 0 ||
113
+ innerHost.includes('[') ||
114
+ innerHost.includes(']')) {
115
+ throw new Error('Monitoring endpoint has an invalid IPv6 host.');
116
+ }
117
+ // Preserve brackets so google-gax builds `[ipv6]:port`.
118
+ host = endpoint.slice(0, closeIdx + 1);
119
+ const remainder = endpoint.slice(closeIdx + 1);
120
+ if (remainder.length > 0) {
121
+ if (!remainder.startsWith(':')) {
122
+ throw new Error('Monitoring endpoint has unexpected characters after IPv6 bracket.');
123
+ }
124
+ const portStr = remainder.slice(1);
125
+ embeddedPort = parsePortString(portStr);
126
+ }
127
+ }
128
+ else {
129
+ if (endpoint.includes('[') || endpoint.includes(']')) {
130
+ throw new Error('Monitoring endpoint has malformed IPv6 brackets.');
131
+ }
132
+ const firstColon = endpoint.indexOf(':');
133
+ const lastColon = endpoint.lastIndexOf(':');
134
+ if (firstColon !== lastColon) {
135
+ throw new Error('IPv6 monitoring endpoints must be enclosed in brackets, e.g. [::1] or [::1]:443.');
136
+ }
137
+ if (firstColon !== -1) {
138
+ host = endpoint.slice(0, firstColon);
139
+ const portStr = endpoint.slice(firstColon + 1);
140
+ if (host.length === 0) {
141
+ throw new Error('Monitoring endpoint host cannot be empty.');
142
+ }
143
+ embeddedPort = parsePortString(portStr);
144
+ }
145
+ else {
146
+ host = endpoint;
147
+ }
148
+ }
149
+ return embeddedPort !== undefined
150
+ ? { apiEndpoint: host, port: embeddedPort }
151
+ : { apiEndpoint: host };
152
+ }
153
+ /**
154
+ * Resolves and validates Cloud Monitoring exporter options into
155
+ * `MetricServiceClient` options plus canonical `universeDomain` and
156
+ * `monitoringEndpoint` keys.
157
+ *
158
+ * @param options Exporter options passed by the caller or `Spanner`.
159
+ * @returns Resolved client options and normalized scope identifiers.
160
+ */
161
+ function resolveExporterConfig(options) {
162
+ const { auth, universeDomain, apiEndpoint } = options;
163
+ let resolvedUniverseDomain;
164
+ if (universeDomain !== undefined) {
165
+ resolvedUniverseDomain = normalizeUniverseDomain(universeDomain);
166
+ }
167
+ else {
168
+ const authUniverseDomain = auth?.clientOptions?.universeDomain;
169
+ if (typeof authUniverseDomain === 'string' &&
170
+ authUniverseDomain.trim() !== '') {
171
+ resolvedUniverseDomain = authUniverseDomain.trim();
172
+ }
173
+ }
174
+ const clientOptions = { auth };
175
+ if (resolvedUniverseDomain !== undefined) {
176
+ clientOptions.universeDomain = resolvedUniverseDomain;
177
+ }
178
+ // Only fall back to SPANNER_MONITORING_HOST when apiEndpoint was omitted;
179
+ // explicit `apiEndpoint: undefined` keeps the caller's synchronous snapshot.
180
+ const hasApiEndpointOption = Object.prototype.hasOwnProperty.call(options, 'apiEndpoint');
181
+ const rawEndpoint = hasApiEndpointOption
182
+ ? apiEndpoint
183
+ : typeof process === 'object'
184
+ ? process.env?.SPANNER_MONITORING_HOST?.trim() || undefined
185
+ : undefined;
186
+ let monitoringEndpoint;
187
+ if (rawEndpoint !== undefined) {
188
+ const parsed = parseMonitoringEndpoint(rawEndpoint);
189
+ clientOptions.apiEndpoint = parsed.apiEndpoint;
190
+ if (parsed.port !== undefined) {
191
+ clientOptions.port = parsed.port;
192
+ }
193
+ monitoringEndpoint = formatMonitoringTargetKey(parsed);
194
+ }
195
+ const effectiveUniverseDomain = resolvedUniverseDomain ??
196
+ (typeof process === 'object'
197
+ ? process.env?.GOOGLE_CLOUD_UNIVERSE_DOMAIN?.trim() || undefined
198
+ : undefined);
199
+ return {
200
+ clientOptions,
201
+ universeDomain: effectiveUniverseDomain,
202
+ monitoringEndpoint,
203
+ };
204
+ }
25
205
  /**
26
206
  * Format and sends metrics information to Google Cloud Monitoring.
27
207
  */
@@ -29,9 +209,15 @@ class CloudMonitoringMetricsExporter {
29
209
  _projectId;
30
210
  _lastExported = new Date(0);
31
211
  _client;
212
+ _universeDomain;
213
+ _monitoringEndpoint;
32
214
  _metricsExportFailureLogged = false;
33
- constructor({ auth }, projectId) {
34
- this._client = new monitoring_1.MetricServiceClient({ auth: auth });
215
+ constructor(options, projectId, resolvedConfig) {
216
+ const resolved = resolvedConfig ?? resolveExporterConfig(options);
217
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
218
+ this._client = new monitoring_1.MetricServiceClient(resolved.clientOptions);
219
+ this._universeDomain = resolved.universeDomain;
220
+ this._monitoringEndpoint = resolved.monitoringEndpoint;
35
221
  this._projectId = projectId;
36
222
  }
37
223
  /**
@@ -70,7 +256,7 @@ class CloudMonitoringMetricsExporter {
70
256
  if (resourceMetrics?.resource?.asyncAttributesPending) {
71
257
  await resourceMetrics.resource.waitForAsyncAttributes?.();
72
258
  }
73
- const timeSeriesList = (0, transform_1.transformResourceMetricToTimeSeriesArray)(resourceMetrics, this._projectId);
259
+ const timeSeriesList = (0, transform_1.transformResourceMetricToTimeSeriesArray)(resourceMetrics, this._projectId, this._universeDomain, this._monitoringEndpoint);
74
260
  let failure = {
75
261
  sendFailed: false,
76
262
  };
@@ -78,9 +264,15 @@ class CloudMonitoringMetricsExporter {
78
264
  if (!this._metricsExportFailureLogged) {
79
265
  const error = e;
80
266
  let msg = 'Send TimeSeries failed:';
81
- if (error.code === grpc_js_1.status.PERMISSION_DENIED) {
267
+ if (error?.code === grpc_js_1.status.PERMISSION_DENIED) {
82
268
  msg += ` 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`;
83
269
  }
270
+ else {
271
+ const errorMessage = sanitizeLogMessage(asError(e).message);
272
+ if (errorMessage) {
273
+ msg += ` ${errorMessage}`;
274
+ }
275
+ }
84
276
  console.warn(msg);
85
277
  this._metricsExportFailureLogged = true;
86
278
  }
@@ -115,4 +307,15 @@ exports.CloudMonitoringMetricsExporter = CloudMonitoringMetricsExporter;
115
307
  function asError(error) {
116
308
  return error instanceof Error ? error : new Error(String(error));
117
309
  }
310
+ /**
311
+ * Collapses ASCII control characters (including CR/LF/tabs) into single spaces
312
+ * so untrusted error messages cannot inject multi-line log entries.
313
+ *
314
+ * @param message Raw error message string.
315
+ * @returns Sanitized single-line message.
316
+ */
317
+ function sanitizeLogMessage(message) {
318
+ // eslint-disable-next-line no-control-regex
319
+ return message.replace(/[\x00-\x1f\x7f]+/g, ' ').trim();
320
+ }
118
321
  //# sourceMappingURL=spanner-metrics-exporter.js.map