@google-cloud/spanner 7.18.0 → 7.18.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 (82) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/README.md +1 -0
  3. package/build/protos/google/spanner/admin/database/v1/backup.proto +757 -0
  4. package/build/protos/google/spanner/admin/database/v1/backup_schedule.proto +230 -0
  5. package/build/protos/google/spanner/admin/database/v1/common.proto +132 -0
  6. package/build/protos/google/spanner/admin/database/v1/spanner_database_admin.proto +1209 -0
  7. package/build/protos/google/spanner/admin/instance/v1/common.proto +64 -0
  8. package/build/protos/google/spanner/admin/instance/v1/spanner_instance_admin.proto +2110 -0
  9. package/build/protos/google/spanner/executor/v1/cloud_executor.proto +1520 -0
  10. package/build/protos/google/spanner/v1/commit_response.proto +59 -0
  11. package/build/protos/google/spanner/v1/keys.proto +163 -0
  12. package/build/protos/google/spanner/v1/mutation.proto +107 -0
  13. package/build/protos/google/spanner/v1/query_plan.proto +128 -0
  14. package/build/protos/google/spanner/v1/result_set.proto +237 -0
  15. package/build/protos/google/spanner/v1/spanner.proto +1389 -0
  16. package/build/protos/google/spanner/v1/transaction.proto +575 -0
  17. package/build/protos/google/spanner/v1/type.proto +214 -0
  18. package/build/protos/protos.d.ts +39317 -0
  19. package/build/protos/protos.js +100360 -0
  20. package/build/protos/protos.json +10271 -0
  21. package/build/src/backup.d.ts +349 -0
  22. package/build/src/backup.js +246 -0
  23. package/build/src/batch-transaction.d.ts +247 -0
  24. package/build/src/batch-transaction.js +384 -0
  25. package/build/src/codec.d.ts +362 -0
  26. package/build/src/codec.js +791 -0
  27. package/build/src/common-grpc/service-object.d.ts +80 -0
  28. package/build/src/common-grpc/service-object.js +101 -0
  29. package/build/src/common-grpc/service.d.ts +445 -0
  30. package/build/src/common-grpc/service.js +826 -0
  31. package/build/src/common.d.ts +66 -0
  32. package/build/src/common.js +54 -0
  33. package/build/src/database.d.ts +2103 -0
  34. package/build/src/database.js +1655 -0
  35. package/build/src/extra_proto_list.json +1 -0
  36. package/build/src/helper.d.ts +45 -0
  37. package/build/src/helper.js +71 -0
  38. package/build/src/index.d.ts +1195 -0
  39. package/build/src/index.js +1059 -0
  40. package/build/src/instance-config.d.ts +294 -0
  41. package/build/src/instance-config.js +216 -0
  42. package/build/src/instance.d.ts +832 -0
  43. package/build/src/instance.js +781 -0
  44. package/build/src/instrument.d.ts +85 -0
  45. package/build/src/instrument.js +215 -0
  46. package/build/src/multiplexed-session.d.ts +136 -0
  47. package/build/src/multiplexed-session.js +197 -0
  48. package/build/src/partial-result-stream.d.ts +253 -0
  49. package/build/src/partial-result-stream.js +400 -0
  50. package/build/src/session-factory.d.ts +100 -0
  51. package/build/src/session-factory.js +93 -0
  52. package/build/src/session-pool.d.ts +471 -0
  53. package/build/src/session-pool.js +754 -0
  54. package/build/src/session.d.ts +258 -0
  55. package/build/src/session.js +348 -0
  56. package/build/src/spanner_grpc_config.json +92 -0
  57. package/build/src/table.d.ts +831 -0
  58. package/build/src/table.js +277 -0
  59. package/build/src/transaction-runner.d.ts +185 -0
  60. package/build/src/transaction-runner.js +282 -0
  61. package/build/src/transaction.d.ts +1691 -0
  62. package/build/src/transaction.js +2004 -0
  63. package/build/src/v1/database_admin_client.d.ts +2301 -0
  64. package/build/src/v1/database_admin_client.js +2286 -0
  65. package/build/src/v1/database_admin_client_config.json +160 -0
  66. package/build/src/v1/database_admin_proto_list.json +6 -0
  67. package/build/src/v1/gapic_metadata.json +27 -0
  68. package/build/src/v1/index.d.ts +4 -0
  69. package/build/src/v1/index.js +29 -0
  70. package/build/src/v1/instance_admin_client.d.ts +1985 -0
  71. package/build/src/v1/instance_admin_client.js +1768 -0
  72. package/build/src/v1/instance_admin_client_config.json +129 -0
  73. package/build/src/v1/instance_admin_proto_list.json +4 -0
  74. package/build/src/v1/spanner_client.d.ts +1250 -0
  75. package/build/src/v1/spanner_client.js +1086 -0
  76. package/build/src/v1/spanner_client_config.json +119 -0
  77. package/build/src/v1/spanner_executor_proxy_client.d.ts +418 -0
  78. package/build/src/v1/spanner_executor_proxy_client.js +706 -0
  79. package/build/src/v1/spanner_executor_proxy_client_config.json +30 -0
  80. package/build/src/v1/spanner_executor_proxy_proto_list.json +14 -0
  81. package/build/src/v1/spanner_proto_list.json +10 -0
  82. package/package.json +1 -1
@@ -0,0 +1,85 @@
1
+ /*!
2
+ * Copyright 2024 Google LLC. All Rights Reserved.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ import { Span, TracerProvider } from '@opentelemetry/api';
17
+ interface SQLStatement {
18
+ sql: string;
19
+ }
20
+ interface ObservabilityOptions {
21
+ tracerProvider: TracerProvider;
22
+ enableExtendedTracing?: boolean;
23
+ enableEndToEndTracing?: boolean;
24
+ }
25
+ export type { ObservabilityOptions };
26
+ export type { Span };
27
+ declare const TRACER_NAME = "cloud.google.com/nodejs/spanner";
28
+ declare const TRACER_VERSION: any;
29
+ export { TRACER_NAME, TRACER_VERSION };
30
+ /**
31
+ * getTracer fetches the tracer from the provided tracerProvider.
32
+ * @param {TracerProvider} [tracerProvider] optional custom tracer provider
33
+ * to use for fetching the tracer. If not provided, the global provider will be used.
34
+ *
35
+ * @returns {Tracer} The tracer instance associated with the provided or global provider.
36
+ */
37
+ export declare function getTracer(tracerProvider?: TracerProvider): import("@opentelemetry/api").Tracer;
38
+ interface traceConfig {
39
+ sql?: string | SQLStatement;
40
+ tableName?: string;
41
+ dbName?: string;
42
+ opts?: ObservabilityOptions;
43
+ }
44
+ declare const SPAN_NAMESPACE_PREFIX = "CloudSpanner";
45
+ export { SPAN_NAMESPACE_PREFIX, traceConfig };
46
+ declare function ensureInitialContextManagerSet(): void;
47
+ export { ensureInitialContextManagerSet };
48
+ /**
49
+ * startTrace begins an active span in the current active context
50
+ * and passes it back to the set callback function. Each span will
51
+ * be prefixed with "cloud.google.com/nodejs/spanner". It is the
52
+ * responsibility of the caller to invoke [span.end] when finished tracing.
53
+ *
54
+ * @returns {Span} The created span.
55
+ */
56
+ export declare function startTrace<T>(spanNameSuffix: string, config: traceConfig | undefined, cb: (span: Span) => T): T;
57
+ /**
58
+ * Sets the span status with err, if non-null onto the span with
59
+ * status.code=ERROR and the message of err.toString()
60
+ *
61
+ * @returns {boolean} to signify if the status was set.
62
+ */
63
+ export declare function setSpanError(span: Span, err: Error | String): boolean;
64
+ /**
65
+ * Sets err, if non-null onto the span with
66
+ * status.code=ERROR and the message of err.toString()
67
+ * as well as recording an exception on the span.
68
+ * @param {Span} [span] the subject span
69
+ * @param {Error} [err] the error whose message to use to record
70
+ * the span error and the span exception.
71
+ *
72
+ * @returns {boolean} to signify if the status and exception were set.
73
+ */
74
+ export declare function setSpanErrorAndException(span: Span, err: Error | String): boolean;
75
+ /**
76
+ * getActiveOrNoopSpan queries the global tracer for the currently active
77
+ * span and returns it, otherwise if there is no active span available, it'll
78
+ * simply create a NoopSpan. This is important in the cases where we don't
79
+ * want to create a new span, such as in sensitive and frequently called code
80
+ * for which the new spans would be too many and thus pollute the trace,
81
+ * but yet we'd like to record an important annotation.
82
+ *
83
+ * @returns {Span} the non-null span.
84
+ */
85
+ export declare function getActiveOrNoopSpan(): Span;
@@ -0,0 +1,215 @@
1
+ "use strict";
2
+ /*!
3
+ * Copyright 2024 Google LLC. All Rights Reserved.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports.SPAN_NAMESPACE_PREFIX = exports.TRACER_VERSION = exports.TRACER_NAME = void 0;
19
+ exports.getTracer = getTracer;
20
+ exports.ensureInitialContextManagerSet = ensureInitialContextManagerSet;
21
+ exports.startTrace = startTrace;
22
+ exports.setSpanError = setSpanError;
23
+ exports.setSpanErrorAndException = setSpanErrorAndException;
24
+ exports.getActiveOrNoopSpan = getActiveOrNoopSpan;
25
+ const semantic_conventions_1 = require("@opentelemetry/semantic-conventions");
26
+ const api_1 = require("@opentelemetry/api");
27
+ const optedInPII = process.env.SPANNER_ENABLE_EXTENDED_TRACING === 'true';
28
+ const TRACER_NAME = 'cloud.google.com/nodejs/spanner';
29
+ exports.TRACER_NAME = TRACER_NAME;
30
+ const TRACER_VERSION = require('../../package.json').version;
31
+ exports.TRACER_VERSION = TRACER_VERSION;
32
+ /**
33
+ * getTracer fetches the tracer from the provided tracerProvider.
34
+ * @param {TracerProvider} [tracerProvider] optional custom tracer provider
35
+ * to use for fetching the tracer. If not provided, the global provider will be used.
36
+ *
37
+ * @returns {Tracer} The tracer instance associated with the provided or global provider.
38
+ */
39
+ function getTracer(tracerProvider) {
40
+ if (tracerProvider) {
41
+ return tracerProvider.getTracer(TRACER_NAME, TRACER_VERSION);
42
+ }
43
+ // Otherwise use the global tracer.
44
+ return api_1.trace.getTracer(TRACER_NAME, TRACER_VERSION);
45
+ }
46
+ const SPAN_NAMESPACE_PREFIX = 'CloudSpanner'; // TODO: discuss & standardize this prefix.
47
+ exports.SPAN_NAMESPACE_PREFIX = SPAN_NAMESPACE_PREFIX;
48
+ const { AsyncHooksContextManager, } = require('@opentelemetry/context-async-hooks');
49
+ /*
50
+ * This function ensures that async/await works correctly by
51
+ * checking if context.active() returns an invalid/unset context
52
+ * and if so, sets a global AsyncHooksContextManager otherwise
53
+ * spans resulting from async/await invocations won't be correctly
54
+ * associated in their respective hierarchies.
55
+ */
56
+ function ensureInitialContextManagerSet() {
57
+ if (api_1.context.active() === api_1.ROOT_CONTEXT) {
58
+ // If no active context was set previously, trace context propagation cannot
59
+ // function correctly with async/await for OpenTelemetry
60
+ // See {@link https://opentelemetry.io/docs/languages/js/context/#active-context}
61
+ api_1.context.disable(); // Disable any prior contextManager.
62
+ const contextManager = new AsyncHooksContextManager();
63
+ contextManager.enable();
64
+ api_1.context.setGlobalContextManager(contextManager);
65
+ }
66
+ }
67
+ /**
68
+ * startTrace begins an active span in the current active context
69
+ * and passes it back to the set callback function. Each span will
70
+ * be prefixed with "cloud.google.com/nodejs/spanner". It is the
71
+ * responsibility of the caller to invoke [span.end] when finished tracing.
72
+ *
73
+ * @returns {Span} The created span.
74
+ */
75
+ function startTrace(spanNameSuffix, config, cb) {
76
+ var _a;
77
+ if (!config) {
78
+ config = {};
79
+ }
80
+ return getTracer((_a = config.opts) === null || _a === void 0 ? void 0 : _a.tracerProvider).startActiveSpan(SPAN_NAMESPACE_PREFIX + '.' + spanNameSuffix, { kind: api_1.SpanKind.CLIENT }, span => {
81
+ var _a;
82
+ span.setAttribute(semantic_conventions_1.SEMATTRS_DB_SYSTEM, 'spanner');
83
+ span.setAttribute(semantic_conventions_1.ATTR_OTEL_SCOPE_NAME, TRACER_NAME);
84
+ span.setAttribute(semantic_conventions_1.ATTR_OTEL_SCOPE_VERSION, TRACER_VERSION);
85
+ span.setAttribute('gcp.client.service', 'spanner');
86
+ span.setAttribute('gcp.client.version', TRACER_VERSION);
87
+ span.setAttribute('gcp.client.repo', 'googleapis/nodejs-spanner');
88
+ if (config.tableName) {
89
+ span.setAttribute(semantic_conventions_1.SEMATTRS_DB_SQL_TABLE, config.tableName);
90
+ }
91
+ if (config.dbName) {
92
+ span.setAttribute(semantic_conventions_1.SEMATTRS_DB_NAME, config.dbName);
93
+ }
94
+ const allowExtendedTracing = optedInPII || ((_a = config.opts) === null || _a === void 0 ? void 0 : _a.enableExtendedTracing);
95
+ if (config.sql && allowExtendedTracing) {
96
+ const sql = config.sql;
97
+ if (typeof sql === 'string') {
98
+ span.setAttribute(semantic_conventions_1.SEMATTRS_DB_STATEMENT, sql);
99
+ }
100
+ else {
101
+ const stmt = sql;
102
+ span.setAttribute(semantic_conventions_1.SEMATTRS_DB_STATEMENT, stmt.sql);
103
+ }
104
+ }
105
+ // If at all the invoked function throws an exception,
106
+ // record the exception and then end this span.
107
+ try {
108
+ return cb(span);
109
+ }
110
+ catch (e) {
111
+ setSpanErrorAndException(span, e);
112
+ span.end();
113
+ // Finally re-throw the exception.
114
+ throw e;
115
+ }
116
+ });
117
+ }
118
+ /**
119
+ * Sets the span status with err, if non-null onto the span with
120
+ * status.code=ERROR and the message of err.toString()
121
+ *
122
+ * @returns {boolean} to signify if the status was set.
123
+ */
124
+ function setSpanError(span, err) {
125
+ if (!err || !span) {
126
+ return false;
127
+ }
128
+ let message = '';
129
+ if (typeof err === 'object' && 'message' in err) {
130
+ message = err.message;
131
+ }
132
+ else {
133
+ message = err.toString();
134
+ }
135
+ span.setStatus({
136
+ code: api_1.SpanStatusCode.ERROR,
137
+ message: message,
138
+ });
139
+ return true;
140
+ }
141
+ /**
142
+ * Sets err, if non-null onto the span with
143
+ * status.code=ERROR and the message of err.toString()
144
+ * as well as recording an exception on the span.
145
+ * @param {Span} [span] the subject span
146
+ * @param {Error} [err] the error whose message to use to record
147
+ * the span error and the span exception.
148
+ *
149
+ * @returns {boolean} to signify if the status and exception were set.
150
+ */
151
+ function setSpanErrorAndException(span, err) {
152
+ if (setSpanError(span, err)) {
153
+ span.recordException(err);
154
+ return true;
155
+ }
156
+ return false;
157
+ }
158
+ /**
159
+ * getActiveOrNoopSpan queries the global tracer for the currently active
160
+ * span and returns it, otherwise if there is no active span available, it'll
161
+ * simply create a NoopSpan. This is important in the cases where we don't
162
+ * want to create a new span, such as in sensitive and frequently called code
163
+ * for which the new spans would be too many and thus pollute the trace,
164
+ * but yet we'd like to record an important annotation.
165
+ *
166
+ * @returns {Span} the non-null span.
167
+ */
168
+ function getActiveOrNoopSpan() {
169
+ const span = api_1.trace.getActiveSpan();
170
+ if (span) {
171
+ return span;
172
+ }
173
+ return new noopSpan();
174
+ }
175
+ /**
176
+ * noopSpan is a pass-through Span that does nothing and shall not
177
+ * be exported, nor added into any context. It serves as a placeholder
178
+ * to allow calls in sensitive areas like sessionPools to transparently
179
+ * add attributes to spans without lots of ugly null checks.
180
+ *
181
+ * It exists because OpenTelemetry-JS does not seem to export the NoopSpan.
182
+ */
183
+ class noopSpan {
184
+ constructor() { }
185
+ spanContext() {
186
+ return api_1.INVALID_SPAN_CONTEXT;
187
+ }
188
+ setAttribute(key, value) {
189
+ return this;
190
+ }
191
+ setAttributes(attributes) {
192
+ return this;
193
+ }
194
+ addEvent(name, attributes) {
195
+ return this;
196
+ }
197
+ addLink(link) {
198
+ return this;
199
+ }
200
+ addLinks(links) {
201
+ return this;
202
+ }
203
+ setStatus(status) {
204
+ return this;
205
+ }
206
+ end(endTime) { }
207
+ isRecording() {
208
+ return false;
209
+ }
210
+ recordException(exc, timeAt) { }
211
+ updateName(name) {
212
+ return this;
213
+ }
214
+ }
215
+ //# sourceMappingURL=instrument.js.map
@@ -0,0 +1,136 @@
1
+ /*!
2
+ * Copyright 2024 Google LLC. All Rights Reserved.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ import { EventEmitter } from 'events';
17
+ import { Database } from './database';
18
+ import { Session } from './session';
19
+ import { GetSessionCallback } from './session-factory';
20
+ import { ObservabilityOptions } from './instrument';
21
+ export declare const MUX_SESSION_AVAILABLE = "mux-session-available";
22
+ export declare const MUX_SESSION_CREATE_ERROR = "mux-session-create-error";
23
+ /**
24
+ * Interface for implementing multiplexed session logic, it should extend the
25
+ * {@link https://nodejs.org/api/events.html|EventEmitter} class
26
+ *
27
+ * @interface MultiplexedSessionInterface
28
+ * @extends external:{@link https://nodejs.org/api/events.html|EventEmitter}
29
+ *
30
+ * @constructs MultiplexedSessionInterface
31
+ * @param {Database} database The database to create a multiplexed session for.
32
+ */
33
+ export interface MultiplexedSessionInterface extends EventEmitter {
34
+ /**
35
+ * When called creates a multiplexed session.
36
+ *
37
+ * @name MultiplexedSessionInterface#createSession
38
+ */
39
+ createSession(): void;
40
+ /**
41
+ * When called returns a multiplexed session.
42
+ *
43
+ * @name MultiplexedSessionInterface#getSession
44
+ * @param {GetSessionCallback} callback The callback function.
45
+ */
46
+ getSession(callback: GetSessionCallback): void;
47
+ }
48
+ /**
49
+ * Class used to manage connections to Spanner using multiplexed session.
50
+ *
51
+ * **You don't need to use this class directly, connections will be handled for
52
+ * you.**
53
+ *
54
+ * @class
55
+ * @extends {EventEmitter}
56
+ */
57
+ export declare class MultiplexedSession extends EventEmitter implements MultiplexedSessionInterface {
58
+ database: Database;
59
+ refreshRate: number;
60
+ isMultiplexedEnabled: boolean;
61
+ _multiplexedSession: Session | null;
62
+ _refreshHandle: NodeJS.Timer;
63
+ _observabilityOptions?: ObservabilityOptions;
64
+ constructor(database: Database);
65
+ /**
66
+ * Creates a new multiplexed session and manages its maintenance.
67
+ *
68
+ * This method initiates the session creation process by calling the `_createSession` method, which returns a Promise.
69
+ */
70
+ createSession(): void;
71
+ /**
72
+ * Creates a new multiplexed session.
73
+ *
74
+ * This method sends a request to the database to create a new session with multiplexing enabled.
75
+ * The response from the database would be an array, the first value of the array will be containing the multiplexed session.
76
+ *
77
+ * @returns {Promise<void>} A Promise that resolves when the session has been successfully created and assigned, an event
78
+ * `mux-session-available` will be emitted to signal that the session is ready.
79
+ *
80
+ * In case of error, an error will get emitted along with the error event.
81
+ *
82
+ * @private
83
+ */
84
+ _createSession(): Promise<void>;
85
+ /**
86
+ * Maintains the multiplexed session by periodically refreshing it.
87
+ *
88
+ * This method sets up a periodic refresh interval for maintaining the session. The interval duration
89
+ * is determined by the @param refreshRate option, which is provided in days.
90
+ * The default value is 7 days.
91
+ *
92
+ * @throws {Error} If the multiplexed session creation fails in `_createSession`, the error is caught
93
+ * and ignored. This is because the currently active multiplexed session has a 30-day expiry, providing
94
+ * the maintainer with four opportunities (one every 7 days) to refresh the active session.
95
+ *
96
+ * @returns {void} This method does not return any value.
97
+ *
98
+ */
99
+ _maintain(): void;
100
+ /**
101
+ * Retrieves a session asynchronously and invokes a callback with the session details.
102
+ *
103
+ * @param {GetSessionCallback} callback - The callback to be invoked once the session is acquired or an error occurs.
104
+ *
105
+ * @returns {void} This method does not return any value, as it operates asynchronously and relies on the callback.
106
+ *
107
+ */
108
+ getSession(callback: GetSessionCallback): void;
109
+ /**
110
+ * Acquires a session asynchronously, and prepares the transaction for the session.
111
+ *
112
+ * Once a session is successfully acquired, it returns the session object (which may be `null` if unsuccessful).
113
+ *
114
+ * @returns {Promise<Session | null>}
115
+ * A Promise that resolves with the acquired session (or `null` if no session is available after retries).
116
+ *
117
+ */
118
+ _acquire(): Promise<Session | null>;
119
+ /**
120
+ * Attempts to get a session, waiting for it to become available if necessary.
121
+ *
122
+ * Waits for the `MUX_SESSION_AVAILABLE` event or for the `MUX_SESSION_CREATE_ERROR`
123
+ * to be emitted if the multiplexed session is not yet available. The method listens
124
+ * for these events, and once `mux-session-available` is emitted, it resolves and returns
125
+ * the session.
126
+ *
127
+ * In case of an error, the promise will get rejected and the error will get bubble up to the parent method.
128
+ *
129
+ * @returns {Promise<Session | null>} A promise that resolves with the current multiplexed session if available,
130
+ * or `null` if the session is not available.
131
+ *
132
+ * @private
133
+ *
134
+ */
135
+ _getSession(): Promise<Session | null>;
136
+ }
@@ -0,0 +1,197 @@
1
+ "use strict";
2
+ /*!
3
+ * Copyright 2024 Google LLC. All Rights Reserved.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports.MultiplexedSession = exports.MUX_SESSION_CREATE_ERROR = exports.MUX_SESSION_AVAILABLE = void 0;
19
+ const events_1 = require("events");
20
+ const instrument_1 = require("./instrument");
21
+ exports.MUX_SESSION_AVAILABLE = 'mux-session-available';
22
+ exports.MUX_SESSION_CREATE_ERROR = 'mux-session-create-error';
23
+ /**
24
+ * Class used to manage connections to Spanner using multiplexed session.
25
+ *
26
+ * **You don't need to use this class directly, connections will be handled for
27
+ * you.**
28
+ *
29
+ * @class
30
+ * @extends {EventEmitter}
31
+ */
32
+ class MultiplexedSession extends events_1.EventEmitter {
33
+ constructor(database) {
34
+ super();
35
+ this.database = database;
36
+ // default frequency is 7 days
37
+ this.refreshRate = 7;
38
+ this._multiplexedSession = null;
39
+ this._observabilityOptions = database._observabilityOptions;
40
+ process.env.GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS === 'true'
41
+ ? (this.isMultiplexedEnabled = true)
42
+ : (this.isMultiplexedEnabled = false);
43
+ }
44
+ /**
45
+ * Creates a new multiplexed session and manages its maintenance.
46
+ *
47
+ * This method initiates the session creation process by calling the `_createSession` method, which returns a Promise.
48
+ */
49
+ createSession() {
50
+ this._createSession()
51
+ .then(() => {
52
+ this._maintain();
53
+ })
54
+ .catch(err => {
55
+ this.emit('error', err);
56
+ });
57
+ }
58
+ /**
59
+ * Creates a new multiplexed session.
60
+ *
61
+ * This method sends a request to the database to create a new session with multiplexing enabled.
62
+ * The response from the database would be an array, the first value of the array will be containing the multiplexed session.
63
+ *
64
+ * @returns {Promise<void>} A Promise that resolves when the session has been successfully created and assigned, an event
65
+ * `mux-session-available` will be emitted to signal that the session is ready.
66
+ *
67
+ * In case of error, an error will get emitted along with the error event.
68
+ *
69
+ * @private
70
+ */
71
+ async _createSession() {
72
+ const traceConfig = {
73
+ opts: this._observabilityOptions,
74
+ dbName: this.database.formattedName_,
75
+ };
76
+ return (0, instrument_1.startTrace)('MultiplexedSession.createSession', traceConfig, async (span) => {
77
+ span.addEvent('Requesting a multiplexed session');
78
+ try {
79
+ const [createSessionResponse] = await this.database.createSession({
80
+ multiplexed: true,
81
+ });
82
+ this._multiplexedSession = createSessionResponse;
83
+ span.addEvent(`Created multiplexed session ${this._multiplexedSession.id}`);
84
+ this.emit(exports.MUX_SESSION_AVAILABLE);
85
+ }
86
+ catch (e) {
87
+ (0, instrument_1.setSpanError)(span, e);
88
+ this.emit(exports.MUX_SESSION_CREATE_ERROR, e);
89
+ throw e;
90
+ }
91
+ finally {
92
+ span.end();
93
+ }
94
+ });
95
+ }
96
+ /**
97
+ * Maintains the multiplexed session by periodically refreshing it.
98
+ *
99
+ * This method sets up a periodic refresh interval for maintaining the session. The interval duration
100
+ * is determined by the @param refreshRate option, which is provided in days.
101
+ * The default value is 7 days.
102
+ *
103
+ * @throws {Error} If the multiplexed session creation fails in `_createSession`, the error is caught
104
+ * and ignored. This is because the currently active multiplexed session has a 30-day expiry, providing
105
+ * the maintainer with four opportunities (one every 7 days) to refresh the active session.
106
+ *
107
+ * @returns {void} This method does not return any value.
108
+ *
109
+ */
110
+ _maintain() {
111
+ const refreshRate = this.refreshRate * 24 * 60 * 60000;
112
+ this._refreshHandle = setInterval(async () => {
113
+ try {
114
+ await this._createSession();
115
+ }
116
+ catch (err) {
117
+ return;
118
+ }
119
+ }, refreshRate);
120
+ this._refreshHandle.unref();
121
+ }
122
+ /**
123
+ * Retrieves a session asynchronously and invokes a callback with the session details.
124
+ *
125
+ * @param {GetSessionCallback} callback - The callback to be invoked once the session is acquired or an error occurs.
126
+ *
127
+ * @returns {void} This method does not return any value, as it operates asynchronously and relies on the callback.
128
+ *
129
+ */
130
+ getSession(callback) {
131
+ this._acquire().then(session => callback(null, session, session === null || session === void 0 ? void 0 : session.txn), callback);
132
+ }
133
+ /**
134
+ * Acquires a session asynchronously, and prepares the transaction for the session.
135
+ *
136
+ * Once a session is successfully acquired, it returns the session object (which may be `null` if unsuccessful).
137
+ *
138
+ * @returns {Promise<Session | null>}
139
+ * A Promise that resolves with the acquired session (or `null` if no session is available after retries).
140
+ *
141
+ */
142
+ async _acquire() {
143
+ const session = await this._getSession();
144
+ // Prepare a transaction for a session
145
+ session.txn = session.transaction(session.parent.queryOptions_);
146
+ return session;
147
+ }
148
+ /**
149
+ * Attempts to get a session, waiting for it to become available if necessary.
150
+ *
151
+ * Waits for the `MUX_SESSION_AVAILABLE` event or for the `MUX_SESSION_CREATE_ERROR`
152
+ * to be emitted if the multiplexed session is not yet available. The method listens
153
+ * for these events, and once `mux-session-available` is emitted, it resolves and returns
154
+ * the session.
155
+ *
156
+ * In case of an error, the promise will get rejected and the error will get bubble up to the parent method.
157
+ *
158
+ * @returns {Promise<Session | null>} A promise that resolves with the current multiplexed session if available,
159
+ * or `null` if the session is not available.
160
+ *
161
+ * @private
162
+ *
163
+ */
164
+ async _getSession() {
165
+ const span = (0, instrument_1.getActiveOrNoopSpan)();
166
+ // Check if the multiplexed session is already available
167
+ if (this._multiplexedSession !== null) {
168
+ span.addEvent('Cache hit: has usable multiplexed session');
169
+ return this._multiplexedSession;
170
+ }
171
+ // Define event and promises to wait for the session to become available or for the error
172
+ span.addEvent('Waiting for a multiplexed session to become available');
173
+ let removeAvailableListener;
174
+ let removeErrorListener;
175
+ const promises = [
176
+ new Promise((_, reject) => {
177
+ this.once(exports.MUX_SESSION_CREATE_ERROR, reject);
178
+ removeErrorListener = this.removeListener.bind(this, exports.MUX_SESSION_CREATE_ERROR, reject);
179
+ }),
180
+ new Promise(resolve => {
181
+ this.once(exports.MUX_SESSION_AVAILABLE, resolve);
182
+ removeAvailableListener = this.removeListener.bind(this, exports.MUX_SESSION_AVAILABLE, resolve);
183
+ }),
184
+ ];
185
+ try {
186
+ await Promise.race(promises);
187
+ }
188
+ finally {
189
+ removeAvailableListener();
190
+ removeErrorListener();
191
+ }
192
+ // Return the multiplexed session after it becomes available
193
+ return this._multiplexedSession;
194
+ }
195
+ }
196
+ exports.MultiplexedSession = MultiplexedSession;
197
+ //# sourceMappingURL=multiplexed-session.js.map