@google-cloud/spanner 8.13.0 → 9.0.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.
@@ -338,41 +338,21 @@ export interface Type {
338
338
  interface FieldType extends Type {
339
339
  name: string;
340
340
  }
341
- /**
342
- * @typedef {ParamType} StructField
343
- * @property {string} name The name of the field.
344
- */
345
- /**
346
- * @typedef {object} ParamType
347
- * @property {string} type The param type. Must be one of the following:
348
- * - uuid
349
- * - float32
350
- * - float64
351
- * - int64
352
- * - numeric
353
- * - bool
354
- * - string
355
- * - bytes
356
- * - json
357
- * - interval
358
- * - proto
359
- * - enum
360
- * - timestamp
361
- * - date
362
- * - struct
363
- * - array
364
- * @property {StructField[]} [fields] **For struct types only**. Type
365
- * definitions for the individual fields.
366
- * @property {string|ParamType} [child] **For array types only**. The array
367
- * element type.
368
- */
341
+ declare function _resetUuidUntypedFlagWarnedForTest(): void;
342
+ declare function isUuidUntypedEnv(): boolean;
369
343
  /**
370
344
  * Get the corresponding Spanner data type for the provided value.
371
345
  *
346
+ * NOTE: This function is internal and not exposed in the public API.
347
+ * Parameterless types return shared, frozen singletons to eliminate allocation
348
+ * and GC overhead. Callers must treat the returned Type descriptor as read-only.
349
+ *
372
350
  * @private
373
351
  *
374
352
  * @param {*} value - The value.
375
- * @returns {object}
353
+ * @param {boolean} [enableUuidAsUntyped] - Whether UUID strings should be
354
+ * typed as unspecified.
355
+ * @returns {Type}
376
356
  *
377
357
  * @example
378
358
  * ```
@@ -380,7 +360,7 @@ interface FieldType extends Type {
380
360
  * // {type: 'float64'}
381
361
  * ```
382
362
  */
383
- declare function getType(value: Value): Type;
363
+ declare function getType(value: Value, enableUuidAsUntyped?: boolean): Type;
384
364
  /**
385
365
  * Converts a value to google.protobuf.ListValue
386
366
  *
@@ -439,5 +419,7 @@ export declare const codec: {
439
419
  encode: typeof encode;
440
420
  getType: typeof getType;
441
421
  Struct: typeof Struct;
422
+ _resetUuidUntypedFlagWarnedForTest: typeof _resetUuidUntypedFlagWarnedForTest;
423
+ isUuidUntypedEnv: typeof isUuidUntypedEnv;
442
424
  };
443
425
  export {};
@@ -55,7 +55,6 @@ function isValidTimestamp(year, month, day, hours, minutes, seconds, millisecond
55
55
  }
56
56
  return isValidDate(year, month, day);
57
57
  }
58
- let uuidUntypedFlagWarned = false;
59
58
  /**
60
59
  * Date-like object used to represent Cloud Spanner Dates. DATE types represent
61
60
  * a logical calendar date, independent of time zone. DATE values do not
@@ -1093,12 +1092,30 @@ const TypeCode = {
1093
1092
  bytes: 'BYTES',
1094
1093
  json: 'JSON',
1095
1094
  jsonb: 'JSON',
1095
+ pgJsonb: 'JSON',
1096
1096
  interval: 'INTERVAL',
1097
1097
  proto: 'PROTO',
1098
1098
  enum: 'ENUM',
1099
1099
  array: 'ARRAY',
1100
1100
  struct: 'STRUCT',
1101
1101
  };
1102
+ // Parameterless type singletons. These are frozen and reused across `getType`
1103
+ // calls to eliminate heap allocations and GC pressure during parameter encoding.
1104
+ const TYPE_STRING = Object.freeze({ type: 'string' });
1105
+ const TYPE_BOOL = Object.freeze({ type: 'bool' });
1106
+ const TYPE_INT64 = Object.freeze({ type: 'int64' });
1107
+ const TYPE_FLOAT64 = Object.freeze({ type: 'float64' });
1108
+ const TYPE_FLOAT32 = Object.freeze({ type: 'float32' });
1109
+ const TYPE_NUMERIC = Object.freeze({ type: 'numeric' });
1110
+ const TYPE_PG_NUMERIC = Object.freeze({ type: 'pgNumeric' });
1111
+ const TYPE_PG_JSONB = Object.freeze({ type: 'pgJsonb' });
1112
+ const TYPE_PG_OID = Object.freeze({ type: 'pgOid' });
1113
+ const TYPE_INTERVAL = Object.freeze({ type: 'interval' });
1114
+ const TYPE_BYTES = Object.freeze({ type: 'bytes' });
1115
+ const TYPE_DATE = Object.freeze({ type: 'date' });
1116
+ const TYPE_TIMESTAMP = Object.freeze({ type: 'timestamp' });
1117
+ const TYPE_JSON = Object.freeze({ type: 'json' });
1118
+ const TYPE_UNSPECIFIED = Object.freeze({ type: 'unspecified' });
1102
1119
  /**
1103
1120
  * @typedef {ParamType} StructField
1104
1121
  * @property {string} name The name of the field.
@@ -1111,6 +1128,9 @@ const TypeCode = {
1111
1128
  * - float64
1112
1129
  * - int64
1113
1130
  * - numeric
1131
+ * - pgNumeric
1132
+ * - pgJsonb
1133
+ * - pgOid
1114
1134
  * - bool
1115
1135
  * - string
1116
1136
  * - bytes
@@ -1122,18 +1142,39 @@ const TypeCode = {
1122
1142
  * - date
1123
1143
  * - struct
1124
1144
  * - array
1145
+ * - unspecified
1125
1146
  * @property {StructField[]} [fields] **For struct types only**. Type
1126
1147
  * definitions for the individual fields.
1127
1148
  * @property {string|ParamType} [child] **For array types only**. The array
1128
1149
  * element type.
1129
1150
  */
1151
+ let uuidUntypedFlagWarned = false;
1152
+ function _resetUuidUntypedFlagWarnedForTest() {
1153
+ uuidUntypedFlagWarned = false;
1154
+ }
1155
+ function isUuidUntypedEnv() {
1156
+ if (process.env['SPANNER_ENABLE_UUID_AS_UNTYPED']?.toLowerCase() === 'true') {
1157
+ if (!uuidUntypedFlagWarned) {
1158
+ process.emitWarning('SPANNER_ENABLE_UUID_AS_UNTYPED environment variable is deprecated and will be removed in a future release.', 'DeprecationWarning');
1159
+ uuidUntypedFlagWarned = true;
1160
+ }
1161
+ return true;
1162
+ }
1163
+ return false;
1164
+ }
1130
1165
  /**
1131
1166
  * Get the corresponding Spanner data type for the provided value.
1132
1167
  *
1168
+ * NOTE: This function is internal and not exposed in the public API.
1169
+ * Parameterless types return shared, frozen singletons to eliminate allocation
1170
+ * and GC overhead. Callers must treat the returned Type descriptor as read-only.
1171
+ *
1133
1172
  * @private
1134
1173
  *
1135
1174
  * @param {*} value - The value.
1136
- * @returns {object}
1175
+ * @param {boolean} [enableUuidAsUntyped] - Whether UUID strings should be
1176
+ * typed as unspecified.
1177
+ * @returns {Type}
1137
1178
  *
1138
1179
  * @example
1139
1180
  * ```
@@ -1141,31 +1182,55 @@ const TypeCode = {
1141
1182
  * // {type: 'float64'}
1142
1183
  * ```
1143
1184
  */
1144
- function getType(value) {
1145
- const isSpecialNumber = (0, helper_1.isInfinite)(value) || ((0, helper_1.isNumber)(value) && isNaN(value));
1146
- if (value instanceof Float32) {
1147
- return { type: 'float32' };
1185
+ function getType(value, enableUuidAsUntyped) {
1186
+ if (value === null || value === undefined) {
1187
+ return TYPE_UNSPECIFIED;
1188
+ }
1189
+ if (typeof value === 'string') {
1190
+ const isUuidUntyped = enableUuidAsUntyped ?? isUuidUntypedEnv();
1191
+ if (isUuidUntyped && (0, helper_1.isUuid)(value)) {
1192
+ return TYPE_UNSPECIFIED;
1193
+ }
1194
+ return TYPE_STRING;
1195
+ }
1196
+ if (typeof value === 'number') {
1197
+ return Number.isInteger(value) ? TYPE_INT64 : TYPE_FLOAT64;
1198
+ }
1199
+ if (typeof value === 'boolean') {
1200
+ return TYPE_BOOL;
1201
+ }
1202
+ if (Buffer.isBuffer(value)) {
1203
+ return TYPE_BYTES;
1204
+ }
1205
+ if (value instanceof SpannerDate) {
1206
+ return TYPE_DATE;
1148
1207
  }
1149
- if ((0, helper_1.isDecimal)(value) || isSpecialNumber || value instanceof Float) {
1150
- return { type: 'float64' };
1208
+ if (value instanceof Date || (0, helper_1.isDate)(value)) {
1209
+ return TYPE_TIMESTAMP;
1151
1210
  }
1152
- if ((0, helper_1.isNumber)(value) || value instanceof Int) {
1153
- return { type: 'int64' };
1211
+ if (value instanceof Int) {
1212
+ return TYPE_INT64;
1213
+ }
1214
+ if (value instanceof Float) {
1215
+ return TYPE_FLOAT64;
1216
+ }
1217
+ if (value instanceof Float32) {
1218
+ return TYPE_FLOAT32;
1154
1219
  }
1155
1220
  if (value instanceof Numeric) {
1156
- return { type: 'numeric' };
1221
+ return TYPE_NUMERIC;
1157
1222
  }
1158
1223
  if (value instanceof PGNumeric) {
1159
- return { type: 'pgNumeric' };
1224
+ return TYPE_PG_NUMERIC;
1160
1225
  }
1161
1226
  if (value instanceof PGJsonb) {
1162
- return { type: 'pgJsonb' };
1227
+ return TYPE_PG_JSONB;
1163
1228
  }
1164
1229
  if (value instanceof PGOid) {
1165
- return { type: 'pgOid' };
1230
+ return TYPE_PG_OID;
1166
1231
  }
1167
1232
  if (value instanceof Interval) {
1168
- return { type: 'interval' };
1233
+ return TYPE_INTERVAL;
1169
1234
  }
1170
1235
  if (value instanceof ProtoMessage) {
1171
1236
  return { type: 'proto', fullName: value.fullName };
@@ -1173,39 +1238,16 @@ function getType(value) {
1173
1238
  if (value instanceof ProtoEnum) {
1174
1239
  return { type: 'enum', fullName: value.fullName };
1175
1240
  }
1176
- if ((0, helper_1.isBoolean)(value)) {
1177
- return { type: 'bool' };
1178
- }
1179
- if (process.env['SPANNER_ENABLE_UUID_AS_UNTYPED'] === 'true') {
1180
- if (!uuidUntypedFlagWarned) {
1181
- process.emitWarning('SPANNER_ENABLE_UUID_AS_UNTYPED environment variable is deprecated and will be removed in a future release.', 'DeprecationWarning');
1182
- uuidUntypedFlagWarned = true;
1183
- }
1184
- if ((0, helper_1.isUuid)(value)) {
1185
- return { type: 'unspecified' };
1186
- }
1187
- }
1188
- if ((0, helper_1.isString)(value)) {
1189
- return { type: 'string' };
1190
- }
1191
- if (Buffer.isBuffer(value)) {
1192
- return { type: 'bytes' };
1193
- }
1194
- if (value instanceof SpannerDate) {
1195
- return { type: 'date' };
1196
- }
1197
- if ((0, helper_1.isDate)(value)) {
1198
- return { type: 'timestamp' };
1199
- }
1200
1241
  if (value instanceof Struct) {
1242
+ const isUuidUntyped = enableUuidAsUntyped ?? isUuidUntypedEnv();
1201
1243
  return {
1202
1244
  type: 'struct',
1203
1245
  fields: Array.from(value).map(({ name, value }) => {
1204
- return Object.assign({ name }, getType(value));
1246
+ return Object.assign({ name }, getType(value, isUuidUntyped));
1205
1247
  }),
1206
1248
  };
1207
1249
  }
1208
- if ((0, helper_1.isArray)(value)) {
1250
+ if (Array.isArray(value)) {
1209
1251
  let child;
1210
1252
  for (let i = 0; i < value.length; i++) {
1211
1253
  child = value[i];
@@ -1215,13 +1257,22 @@ function getType(value) {
1215
1257
  }
1216
1258
  return {
1217
1259
  type: 'array',
1218
- child: getType(child),
1260
+ child: getType(child, enableUuidAsUntyped),
1219
1261
  };
1220
1262
  }
1263
+ if (value instanceof String) {
1264
+ return TYPE_STRING;
1265
+ }
1266
+ if (value instanceof Number) {
1267
+ return Number.isInteger(value.valueOf()) ? TYPE_INT64 : TYPE_FLOAT64;
1268
+ }
1269
+ if (value instanceof Boolean) {
1270
+ return TYPE_BOOL;
1271
+ }
1221
1272
  if ((0, helper_1.isObject)(value)) {
1222
- return { type: 'json' };
1273
+ return TYPE_JSON;
1223
1274
  }
1224
- return { type: 'unspecified' };
1275
+ return TYPE_UNSPECIFIED;
1225
1276
  }
1226
1277
  /**
1227
1278
  * Converts a value to google.protobuf.ListValue
@@ -1299,7 +1350,7 @@ function createTypeObject(friendlyType) {
1299
1350
  type.typeAnnotation =
1300
1351
  spannerClient.spanner.v1.TypeAnnotationCode.PG_NUMERIC;
1301
1352
  }
1302
- else if (friendlyType.type === 'jsonb') {
1353
+ else if (friendlyType.type === 'jsonb' || friendlyType.type === 'pgJsonb') {
1303
1354
  type.typeAnnotation = spannerClient.spanner.v1.TypeAnnotationCode.PG_JSONB;
1304
1355
  }
1305
1356
  else if (friendlyType.type === 'pgOid') {
@@ -1329,5 +1380,7 @@ exports.codec = {
1329
1380
  encode,
1330
1381
  getType,
1331
1382
  Struct,
1383
+ _resetUuidUntypedFlagWarnedForTest,
1384
+ isUuidUntypedEnv,
1332
1385
  };
1333
1386
  //# sourceMappingURL=codec.js.map
@@ -18,7 +18,6 @@ Object.defineProperty(exports, "__esModule", { value: true });
18
18
  exports.AFE_SERVER_TIMING_HEADER = exports.END_TO_END_TRACING_HEADER = exports.LEADER_AWARE_ROUTING_HEADER = exports.CLOUD_RESOURCE_HEADER = void 0;
19
19
  exports.addLeaderAwareRoutingHeader = addLeaderAwareRoutingHeader;
20
20
  exports.getCommonHeaders = getCommonHeaders;
21
- const _1 = require(".");
22
21
  /*!
23
22
  * HTTP header for the resource prefix to improve routing
24
23
  * by the backend.
@@ -49,11 +48,11 @@ function addLeaderAwareRoutingHeader(headers) {
49
48
  */
50
49
  function getCommonHeaders(resourceName, enableTracing) {
51
50
  const headers = {};
52
- if (process.env.SPANNER_ENABLE_END_TO_END_TRACING === 'true' ||
51
+ if (process.env.SPANNER_ENABLE_END_TO_END_TRACING?.toLowerCase() === 'true' ||
53
52
  enableTracing) {
54
53
  headers[exports.END_TO_END_TRACING_HEADER] = 'true';
55
54
  }
56
- if (_1.Spanner.isAFEServerTimingEnabled()) {
55
+ if (process.env.SPANNER_DISABLE_AFE_SERVER_TIMING?.toLowerCase() !== 'true') {
57
56
  headers[exports.AFE_SERVER_TIMING_HEADER] = 'true';
58
57
  }
59
58
  headers[exports.CLOUD_RESOURCE_HEADER] = resourceName;
@@ -844,7 +844,7 @@ class Database extends common.GrpcServiceObject {
844
844
  }
845
845
  makePooledRequest_(config, callback) {
846
846
  const sessionFactory_ = this.sessionFactory_;
847
- sessionFactory_.getSessionForReadWrite((err, session) => {
847
+ const onSession = (err, session) => {
848
848
  if (err) {
849
849
  callback(err, null);
850
850
  return;
@@ -856,7 +856,15 @@ class Database extends common.GrpcServiceObject {
856
856
  sessionFactory_.release(session);
857
857
  callback(err, ...args);
858
858
  });
859
- });
859
+ };
860
+ const session = sessionFactory_.isMultiplexedEnabledForRW?.()
861
+ ? sessionFactory_.getSessionSync?.()
862
+ : null;
863
+ if (session) {
864
+ onSession(null, session);
865
+ return;
866
+ }
867
+ sessionFactory_.getSessionForReadWrite(onSession);
860
868
  }
861
869
  /**
862
870
  * Make an API request as a stream, first assuring an active session is used.
@@ -1034,15 +1042,28 @@ class Database extends common.GrpcServiceObject {
1034
1042
  runSpan.end();
1035
1043
  callback(error, rows, stats, metadata);
1036
1044
  };
1037
- this.sessionFactory_.getSession((error, session) => {
1045
+ const onSession = (error, session) => {
1038
1046
  if (error) {
1039
1047
  complete(error);
1040
1048
  return;
1041
1049
  }
1042
1050
  streamSpan.addEvent('Using Session', { 'session.id': session?.id });
1043
- snapshot = session.snapshot(options, this.queryOptions_);
1044
- this._runOnSnapshot(snapshot, session, query, complete);
1045
- });
1051
+ try {
1052
+ snapshot = session.snapshot(options, this.queryOptions_);
1053
+ this._runOnSnapshot(snapshot, session, query, complete);
1054
+ }
1055
+ catch (syncError) {
1056
+ // Defer error delivery via nextTick so callback callers never experience
1057
+ // synchronous callback execution (Zalgo) when getSessionSync() returns synchronously.
1058
+ process.nextTick(() => complete(syncError));
1059
+ }
1060
+ };
1061
+ const session = this.sessionFactory_.getSessionSync?.();
1062
+ if (session) {
1063
+ onSession(null, session);
1064
+ return;
1065
+ }
1066
+ this.sessionFactory_.getSession(onSession);
1046
1067
  }
1047
1068
  /**
1048
1069
  * Executes the query on the snapshot and binds session release to snapshot end.
@@ -1071,7 +1092,9 @@ class Database extends common.GrpcServiceObject {
1071
1092
  }
1072
1093
  }
1073
1094
  catch (syncError) {
1074
- callback(syncError);
1095
+ // Defer error delivery via nextTick so callback callers never experience
1096
+ // synchronous callback execution (Zalgo) when getSessionSync() returns synchronously.
1097
+ process.nextTick(() => callback(syncError));
1075
1098
  }
1076
1099
  }
1077
1100
  runPartitionedUpdate(query, callback) {
@@ -57,6 +57,8 @@ export type GetInstanceConfigOperationsCallback = PagedCallback<IOperation, inst
57
57
  * DirectedReadOptions won't be set for readWrite transactions"
58
58
  * @property {ObservabilityOptions} [observabilityOptions] Sets the observability options to be used for OpenTelemetry tracing
59
59
  * @property {boolean} [disableBuiltInMetrics=True] If set to true, built-in metrics will be disabled.
60
+ * @property {number} ['grpc.enable_channelz'=0] Whether to enable gRPC Channelz service tracking.
61
+ * Defaults to 0 (disabled) to eliminate per-RPC tracking and allocation overhead. Set to 1 to enable.
60
62
  */
61
63
  export interface SpannerOptions extends GrpcClientOptions {
62
64
  apiEndpoint?: string;
@@ -83,6 +85,12 @@ export interface SpannerOptions extends GrpcClientOptions {
83
85
  */
84
86
  universe_domain?: string;
85
87
  universeDomain?: string;
88
+ /**
89
+ * Whether to enable gRPC Channelz service tracking.
90
+ * Defaults to `0` (disabled) to eliminate per-RPC allocation and tracking overhead.
91
+ * Set to `1` if live connection introspection via gRPC Channelz (e.g. grpcdebug) is required.
92
+ */
93
+ 'grpc.enable_channelz'?: number;
86
94
  }
87
95
  export interface RequestConfig {
88
96
  client: string;
@@ -246,6 +246,8 @@ class Spanner extends service_1.GrpcService {
246
246
  scopes,
247
247
  // Add grpc keep alive setting
248
248
  'grpc.keepalive_time_ms': 120000,
249
+ // Disable Channelz by default to reduce per-RPC tracking and allocation overhead
250
+ 'grpc.enable_channelz': 0,
249
251
  // Enable grpc-gcp support
250
252
  'grpc.callInvocationTransformer': grpcGcp.gcpCallInvocationTransformer,
251
253
  'grpc.channelFactoryOverride': grpcGcp.gcpChannelFactoryOverride,
@@ -334,7 +336,7 @@ class Spanner extends service_1.GrpcService {
334
336
  getInstanceAdminClient() {
335
337
  const clientName = 'InstanceAdminClient';
336
338
  if (!this.clients_.has(clientName)) {
337
- this.clients_.set(clientName, new v1[clientName](this.options));
339
+ this.clients_.set(clientName, new v1.InstanceAdminClient(this.options));
338
340
  }
339
341
  return this.clients_.get(clientName);
340
342
  }
@@ -354,7 +356,7 @@ class Spanner extends service_1.GrpcService {
354
356
  getDatabaseAdminClient() {
355
357
  const clientName = 'DatabaseAdminClient';
356
358
  if (!this.clients_.has(clientName)) {
357
- this.clients_.set(clientName, new v1[clientName](this.options));
359
+ this.clients_.set(clientName, new v1.DatabaseAdminClient(this.options));
358
360
  }
359
361
  return this.clients_.get(clientName);
360
362
  }
@@ -391,11 +393,12 @@ class Spanner extends service_1.GrpcService {
391
393
  const res = performTeardown();
392
394
  if (callback) {
393
395
  // process.nextTick prevents Unhandled Promise Rejections if callback throws
394
- res.then(() => process.nextTick(() => callback(null)), err => process.nextTick(() => callback(err)));
395
- }
396
- else {
397
- return res;
396
+ res
397
+ .then(() => process.nextTick(() => callback(null)))
398
+ .catch(err => process.nextTick(() => callback(err)));
399
+ return;
398
400
  }
401
+ return res;
399
402
  }
400
403
  createInstance(name, config, callback) {
401
404
  if (!name) {
@@ -817,28 +820,39 @@ class Spanner extends service_1.GrpcService {
817
820
  !metricsExplicitlyDisabled && !this._isInSecureCredentials;
818
821
  metrics_tracer_factory_1.MetricsTracerFactory.enabled = this._metricsEnabled;
819
822
  if (this._metricsEnabled) {
820
- try {
821
- this.auth.getProjectId((err, projectId) => {
822
- if (err || !projectId) {
823
- console.error('Unable to get Project Id for client side metrics, will skip exporting client' +
824
- ' side metrics' +
825
- err);
826
- return;
827
- }
828
- this.projectId_ = projectId;
829
- const factory = metrics_tracer_factory_1.MetricsTracerFactory.getInstance(projectId);
830
- const periodicReader = new sdk_metrics_1.PeriodicExportingMetricReader({
831
- exporter: new spanner_metrics_exporter_1.CloudMonitoringMetricsExporter({ auth: this.auth }, projectId),
832
- exportIntervalMillis: 60000,
823
+ const initializeMetrics = (projectId) => {
824
+ this.projectId_ = projectId;
825
+ const factory = metrics_tracer_factory_1.MetricsTracerFactory.getInstance(projectId);
826
+ if (factory && !factory.hasMetricReaders()) {
827
+ api_1.context.with(api_1.ROOT_CONTEXT, () => {
828
+ const periodicReader = new sdk_metrics_1.PeriodicExportingMetricReader({
829
+ exporter: new spanner_metrics_exporter_1.CloudMonitoringMetricsExporter({ auth: this.auth }, projectId),
830
+ exportIntervalMillis: 60000,
831
+ });
832
+ factory.getMeterProvider([periodicReader]);
833
833
  });
834
- // Retrieve the MeterProvider to trigger construction
835
- factory.getMeterProvider([periodicReader]);
836
- });
834
+ }
835
+ };
836
+ if (this.projectId_ && this.projectId_ !== '{{projectId}}') {
837
+ initializeMetrics(this.projectId_);
837
838
  }
838
- catch (err) {
839
- console.error('Unable to configure client side metrics, will skip exporting client' +
840
- ' side metrics' +
841
- err);
839
+ else {
840
+ try {
841
+ this.auth.getProjectId((err, projectId) => {
842
+ if (err || !projectId) {
843
+ console.error('Unable to get Project Id for client side metrics, will skip exporting client' +
844
+ ' side metrics' +
845
+ err);
846
+ return;
847
+ }
848
+ initializeMetrics(projectId);
849
+ });
850
+ }
851
+ catch (err) {
852
+ console.error('Unable to configure client side metrics, will skip exporting client' +
853
+ ' side metrics' +
854
+ err);
855
+ }
842
856
  }
843
857
  }
844
858
  }
@@ -909,46 +923,65 @@ class Spanner extends service_1.GrpcService {
909
923
  },
910
924
  },
911
925
  }));
912
- // Wrap requestFn to inject the spanner request id into every returned error.
913
- const wrappedRequestFn = (...args) => {
914
- const hasCallback = args &&
915
- args.length > 0 &&
916
- typeof args[args.length - 1] === 'function';
917
- switch (hasCallback) {
918
- case true: {
919
- const cb = args[args.length - 1];
920
- const priorArgs = args.slice(0, args.length - 1);
921
- requestFn(...priorArgs, (...results) => {
922
- if (results && results.length > 0) {
923
- const err = results[0];
924
- (0, request_id_header_1.injectRequestIDIntoError)(config, err);
926
+ // Extract a lightweight config reference containing only headers so error
927
+ // enrichment is decoupled from the caller's mutable config object.
928
+ const errorConfig = { headers: config?.headers };
929
+ // Wrap requestFn to inject the Spanner request ID (x-goog-spanner-request-id)
930
+ // into any error returned via callback, rejected promise, stream event, or
931
+ // synchronous exception.
932
+ //
933
+ // Because reqOpts and gaxOpts are already pre-bound to requestFn, wrappedRequestFn
934
+ // receives at most one argument: an optional callback.
935
+ const wrappedRequestFn = (callback) => {
936
+ // Callback mode: invoke requestFn with an intercepted callback to enrich
937
+ // the error parameter before delegating to the caller's callback.
938
+ if (typeof callback === 'function') {
939
+ try {
940
+ requestFn((...results) => {
941
+ if (results[0]) {
942
+ (0, request_id_header_1.injectRequestIDIntoError)(errorConfig, results[0]);
925
943
  }
926
- cb(...results);
944
+ callback(...results);
927
945
  });
928
- return;
929
946
  }
930
- case false: {
931
- const res = requestFn(...args);
932
- const stream = res;
933
- if (stream) {
934
- stream.on('error', err => {
935
- (0, request_id_header_1.injectRequestIDIntoError)(config, err);
936
- });
937
- }
938
- const originallyPromise = res instanceof Promise;
939
- if (!originallyPromise) {
940
- return res;
941
- }
942
- return new Promise((resolve, reject) => {
943
- requestFn(...args)
944
- .then(resolve)
945
- .catch(err => {
946
- (0, request_id_header_1.injectRequestIDIntoError)(config, err);
947
- reject(err);
948
- });
949
- });
947
+ catch (err) {
948
+ (0, request_id_header_1.injectRequestIDIntoError)(errorConfig, err);
949
+ throw err;
950
950
  }
951
+ return;
952
+ }
953
+ // Non-callback mode: invoke requestFn() for Promise or Stream callers.
954
+ let res;
955
+ try {
956
+ res = requestFn();
957
+ }
958
+ catch (err) {
959
+ (0, request_id_header_1.injectRequestIDIntoError)(errorConfig, err);
960
+ throw err;
961
+ }
962
+ // Handle Promise / Thenable return values (e.g. unary requests).
963
+ // Attach a rejection handler to inject the request ID into rejected errors.
964
+ // If the promise is cancellable (e.g. google-gax CancellablePromise), preserve
965
+ // its .cancel() method so callers can cancel the underlying operation.
966
+ if (res && typeof res.then === 'function') {
967
+ const chained = res.then(null, err => {
968
+ (0, request_id_header_1.injectRequestIDIntoError)(errorConfig, err);
969
+ throw err;
970
+ });
971
+ if (typeof res.cancel === 'function') {
972
+ chained.cancel = res.cancel.bind(res);
973
+ }
974
+ return chained;
975
+ }
976
+ // Handle Stream return values (e.g. streaming reads or queries).
977
+ // Listen for 'error' events to enrich the emitted error with the request ID.
978
+ const stream = res;
979
+ if (stream && typeof stream.on === 'function') {
980
+ stream.on('error', err => {
981
+ (0, request_id_header_1.injectRequestIDIntoError)(errorConfig, err);
982
+ });
951
983
  }
984
+ return res;
952
985
  };
953
986
  callback(null, wrappedRequestFn);
954
987
  });
@@ -969,7 +1002,8 @@ class Spanner extends service_1.GrpcService {
969
1002
  let metricsTracer = null;
970
1003
  if (this._metricsEnabled &&
971
1004
  config.client === 'SpannerClient' &&
972
- this.projectId_) {
1005
+ this.projectId_ &&
1006
+ this.projectId_ !== '{{projectId}}') {
973
1007
  metricsTracer =
974
1008
  metrics_tracer_factory_1.MetricsTracerFactory?.getInstance(this.projectId_)?.createMetricsTracer(config.method, config.reqOpts.database ?? config.reqOpts.session, config.headers['x-goog-spanner-request-id']) ?? null;
975
1009
  }
@@ -1003,6 +1037,7 @@ class Spanner extends service_1.GrpcService {
1003
1037
  .then(val => {
1004
1038
  metricsTracer?.recordOperationCompletion();
1005
1039
  resolve(val);
1040
+ return val;
1006
1041
  })
1007
1042
  .catch(error => {
1008
1043
  metricsTracer?.recordOperationCompletion();
@@ -1034,7 +1069,8 @@ class Spanner extends service_1.GrpcService {
1034
1069
  let metricsTracer = null;
1035
1070
  if (this._metricsEnabled &&
1036
1071
  config.client === 'SpannerClient' &&
1037
- this.projectId_) {
1072
+ this.projectId_ &&
1073
+ this.projectId_ !== '{{projectId}}') {
1038
1074
  metricsTracer =
1039
1075
  metrics_tracer_factory_1.MetricsTracerFactory?.getInstance(this.projectId_)?.createMetricsTracer(config.method, config.reqOpts.session ?? config.reqOpts.database, config.headers['x-goog-spanner-request-id']) ?? null;
1040
1076
  }