@firebase/data-connect 0.5.0 → 0.6.0-20260408221811
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/dist/index.cjs.js +1165 -143
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.esm.js +1164 -144
- package/dist/index.esm.js.map +1 -1
- package/dist/index.node.cjs.js +1231 -190
- package/dist/index.node.cjs.js.map +1 -1
- package/dist/internal.d.ts +133 -12
- package/dist/node-esm/index.node.esm.js +1230 -191
- package/dist/node-esm/index.node.esm.js.map +1 -1
- package/dist/node-esm/src/api/Mutation.d.ts +2 -2
- package/dist/node-esm/src/api/query.d.ts +1 -1
- package/dist/node-esm/src/core/query/QueryManager.d.ts +22 -3
- package/dist/node-esm/src/network/index.d.ts +1 -1
- package/dist/node-esm/src/network/manager.d.ts +61 -0
- package/dist/node-esm/src/network/{fetch.d.ts → rest/fetch.d.ts} +9 -4
- package/dist/node-esm/src/network/rest/index.d.ts +18 -0
- package/dist/node-esm/src/network/rest/restTransport.d.ts +33 -0
- package/dist/node-esm/src/network/stream/streamTransport.d.ts +241 -0
- package/dist/node-esm/src/network/stream/websocket.d.ts +90 -0
- package/dist/node-esm/src/network/stream/wire.d.ts +138 -0
- package/dist/node-esm/src/network/transport.d.ts +179 -0
- package/dist/node-esm/src/util/url.d.ts +3 -1
- package/dist/private.d.ts +29 -7
- package/dist/public.d.ts +3 -1
- package/dist/src/api/Mutation.d.ts +2 -2
- package/dist/src/api/query.d.ts +1 -1
- package/dist/src/core/query/QueryManager.d.ts +22 -3
- package/dist/src/network/index.d.ts +1 -1
- package/dist/src/network/manager.d.ts +61 -0
- package/dist/src/network/{fetch.d.ts → rest/fetch.d.ts} +9 -4
- package/dist/src/network/rest/index.d.ts +18 -0
- package/dist/src/network/rest/restTransport.d.ts +33 -0
- package/dist/src/network/stream/streamTransport.d.ts +241 -0
- package/dist/src/network/stream/websocket.d.ts +90 -0
- package/dist/src/network/stream/wire.d.ts +138 -0
- package/dist/src/network/transport.d.ts +179 -0
- package/dist/src/util/url.d.ts +3 -1
- package/package.json +1 -1
- package/dist/node-esm/src/network/transport/index.d.ts +0 -81
- package/dist/node-esm/src/network/transport/rest.d.ts +0 -49
- package/dist/src/network/transport/index.d.ts +0 -81
- package/dist/src/network/transport/rest.d.ts +0 -49
package/dist/index.cjs.js
CHANGED
|
@@ -8,7 +8,7 @@ var util = require('@firebase/util');
|
|
|
8
8
|
var logger$1 = require('@firebase/logger');
|
|
9
9
|
|
|
10
10
|
const name = "@firebase/data-connect";
|
|
11
|
-
const version = "0.
|
|
11
|
+
const version = "0.6.0-20260408221811";
|
|
12
12
|
|
|
13
13
|
/**
|
|
14
14
|
* @license
|
|
@@ -920,6 +920,10 @@ class QueryManager {
|
|
|
920
920
|
this.dc = dc;
|
|
921
921
|
this.cache = cache;
|
|
922
922
|
this.callbacks = new Map();
|
|
923
|
+
/**
|
|
924
|
+
* Map of serialized query keys to most recent Query Result. Used as a simple fallback cache
|
|
925
|
+
* for subsciptions if caching is not enabled.
|
|
926
|
+
*/
|
|
923
927
|
this.subscriptionCache = new Map();
|
|
924
928
|
this.queue = [];
|
|
925
929
|
}
|
|
@@ -965,7 +969,12 @@ class QueryManager {
|
|
|
965
969
|
const unsubscribe = () => {
|
|
966
970
|
if (this.callbacks.has(key)) {
|
|
967
971
|
const callbackList = this.callbacks.get(key);
|
|
968
|
-
|
|
972
|
+
const newList = callbackList.filter(callback => callback !== subscription);
|
|
973
|
+
this.callbacks.set(key, newList);
|
|
974
|
+
if (newList.length === 0) {
|
|
975
|
+
this.callbacks.delete(key);
|
|
976
|
+
this.transport.invokeUnsubscribe(queryRef.name, queryRef.variables);
|
|
977
|
+
}
|
|
969
978
|
onCompleteCallback?.();
|
|
970
979
|
}
|
|
971
980
|
};
|
|
@@ -980,12 +989,18 @@ class QueryManager {
|
|
|
980
989
|
const promise = this.preferCacheResults(queryRef, /*allowStale=*/ true);
|
|
981
990
|
// We want to ignore the error and let subscriptions handle it
|
|
982
991
|
promise.then(undefined, err => { });
|
|
983
|
-
if (
|
|
984
|
-
this.callbacks
|
|
992
|
+
if (this.callbacks.has(key)) {
|
|
993
|
+
this.callbacks
|
|
994
|
+
.get(key)
|
|
995
|
+
.push(subscription);
|
|
996
|
+
}
|
|
997
|
+
else {
|
|
998
|
+
this.callbacks.set(key, [
|
|
999
|
+
subscription
|
|
1000
|
+
]);
|
|
1001
|
+
// only invoke subscription if we don't already have an active subscription
|
|
1002
|
+
this.transport.invokeSubscribe(this.makeSubscribeObserver(queryRef), queryRef.name, queryRef.variables);
|
|
985
1003
|
}
|
|
986
|
-
this.callbacks
|
|
987
|
-
.get(key)
|
|
988
|
-
.push(subscription);
|
|
989
1004
|
return unsubscribe;
|
|
990
1005
|
}
|
|
991
1006
|
async fetchServerResults(queryRef) {
|
|
@@ -1008,8 +1023,7 @@ class QueryManager {
|
|
|
1008
1023
|
extensions: getDataConnectExtensionsWithoutMaxAge(originalExtensions),
|
|
1009
1024
|
toJSON: getRefSerializer(queryRef, result.data, SOURCE_SERVER, fetchTime)
|
|
1010
1025
|
};
|
|
1011
|
-
|
|
1012
|
-
updatedKeys = await this.updateCache(queryResult, originalExtensions?.dataConnect);
|
|
1026
|
+
const updatedKeys = await this.updateCache(queryResult, originalExtensions?.dataConnect);
|
|
1013
1027
|
this.publishDataToSubscribers(key, queryResult);
|
|
1014
1028
|
if (this.cache) {
|
|
1015
1029
|
await this.publishCacheResultsToSubscribers(updatedKeys, fetchTime);
|
|
@@ -1110,6 +1124,7 @@ class QueryManager {
|
|
|
1110
1124
|
result.toJSON = getRefSerializer(result.ref, result.data, SOURCE_CACHE, result.fetchTime);
|
|
1111
1125
|
return result;
|
|
1112
1126
|
}
|
|
1127
|
+
/** Call the registered onNext callbacks for the given key */
|
|
1113
1128
|
publishDataToSubscribers(key, queryResult) {
|
|
1114
1129
|
if (!this.callbacks.has(key)) {
|
|
1115
1130
|
return;
|
|
@@ -1150,6 +1165,80 @@ class QueryManager {
|
|
|
1150
1165
|
enableEmulator(host, port) {
|
|
1151
1166
|
this.transport.useEmulator(host, port);
|
|
1152
1167
|
}
|
|
1168
|
+
/**
|
|
1169
|
+
* Create a new {@link SubscribeObserver} for the given QueryRef. This will be passed to
|
|
1170
|
+
* {@link DataConnectTransportInterface.invokeSubscribe | invokeSubscribe()} to notify the query
|
|
1171
|
+
* layer of data update notifications or if the stream disconnected.
|
|
1172
|
+
*/
|
|
1173
|
+
makeSubscribeObserver(queryRef) {
|
|
1174
|
+
const key = encoderImpl({
|
|
1175
|
+
name: queryRef.name,
|
|
1176
|
+
variables: queryRef.variables,
|
|
1177
|
+
refType: QUERY_STR
|
|
1178
|
+
});
|
|
1179
|
+
return {
|
|
1180
|
+
onData: async (response) => {
|
|
1181
|
+
await this.handleStreamNotification(key, response, queryRef);
|
|
1182
|
+
},
|
|
1183
|
+
onDisconnect: (code, reason) => {
|
|
1184
|
+
this.handleStreamDisconnect(key, code, reason);
|
|
1185
|
+
},
|
|
1186
|
+
onError: error => {
|
|
1187
|
+
this.publishErrorToSubscribers(key, error);
|
|
1188
|
+
}
|
|
1189
|
+
};
|
|
1190
|
+
}
|
|
1191
|
+
/**
|
|
1192
|
+
* Handle a data update notification from the stream. Notify subscribers of results/errors, and
|
|
1193
|
+
* update the cache.
|
|
1194
|
+
*/
|
|
1195
|
+
async handleStreamNotification(key, response, queryRef) {
|
|
1196
|
+
if (response.errors && response.errors.length > 0) {
|
|
1197
|
+
const stringified = JSON.stringify(response.errors.map(e => {
|
|
1198
|
+
if (e && typeof e === 'object') {
|
|
1199
|
+
return {
|
|
1200
|
+
message: e.message,
|
|
1201
|
+
code: e.code
|
|
1202
|
+
};
|
|
1203
|
+
}
|
|
1204
|
+
return e;
|
|
1205
|
+
}));
|
|
1206
|
+
const failureResponse = {
|
|
1207
|
+
errors: response.errors,
|
|
1208
|
+
data: response.data
|
|
1209
|
+
};
|
|
1210
|
+
const error = new DataConnectOperationError('DataConnect error received from subscribe notification: ' +
|
|
1211
|
+
stringified, failureResponse);
|
|
1212
|
+
this.publishErrorToSubscribers(key, error);
|
|
1213
|
+
return;
|
|
1214
|
+
}
|
|
1215
|
+
const fetchTime = Date.now().toString();
|
|
1216
|
+
const queryResult = {
|
|
1217
|
+
ref: queryRef,
|
|
1218
|
+
source: SOURCE_SERVER,
|
|
1219
|
+
fetchTime,
|
|
1220
|
+
data: response.data,
|
|
1221
|
+
extensions: getDataConnectExtensionsWithoutMaxAge(response.extensions),
|
|
1222
|
+
toJSON: getRefSerializer(queryRef, response.data, SOURCE_SERVER, fetchTime)
|
|
1223
|
+
};
|
|
1224
|
+
const updatedKeys = await this.updateCache(queryResult, response.extensions?.dataConnect);
|
|
1225
|
+
this.publishDataToSubscribers(key, queryResult);
|
|
1226
|
+
if (this.cache) {
|
|
1227
|
+
await this.publishCacheResultsToSubscribers(updatedKeys, fetchTime);
|
|
1228
|
+
}
|
|
1229
|
+
}
|
|
1230
|
+
/**
|
|
1231
|
+
* Handle a disconnect from the stream. Unsubscribe all callbacks for the given key.
|
|
1232
|
+
*/
|
|
1233
|
+
handleStreamDisconnect(key, code, reason) {
|
|
1234
|
+
const error = new DataConnectError(code, reason);
|
|
1235
|
+
this.publishErrorToSubscribers(key, error);
|
|
1236
|
+
const callbacks = this.callbacks.get(key);
|
|
1237
|
+
if (callbacks) {
|
|
1238
|
+
[...callbacks].forEach(cb => cb.unsubscribe());
|
|
1239
|
+
}
|
|
1240
|
+
return;
|
|
1241
|
+
}
|
|
1153
1242
|
}
|
|
1154
1243
|
function getMaxAgeFromExtensions(extensions) {
|
|
1155
1244
|
if (!extensions) {
|
|
@@ -1195,46 +1284,137 @@ const CallerSdkTypeEnum = {
|
|
|
1195
1284
|
TanstackAngularCore: 'TanstackAngularCore', // Tanstack non-generated Angular SDK
|
|
1196
1285
|
GeneratedAngular: 'GeneratedAngular' // Generated Angular SDK
|
|
1197
1286
|
};
|
|
1198
|
-
|
|
1199
1287
|
/**
|
|
1200
|
-
*
|
|
1201
|
-
*
|
|
1202
|
-
*
|
|
1203
|
-
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
1204
|
-
* you may not use this file except in compliance with the License.
|
|
1205
|
-
* You may obtain a copy of the License at
|
|
1206
|
-
*
|
|
1207
|
-
* http://www.apache.org/licenses/LICENSE-2.0
|
|
1208
|
-
*
|
|
1209
|
-
* Unless required by applicable law or agreed to in writing, software
|
|
1210
|
-
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
1211
|
-
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
1212
|
-
* See the License for the specific language governing permissions and
|
|
1213
|
-
* limitations under the License.
|
|
1288
|
+
* Constructs the value for the X-Goog-Api-Client header
|
|
1289
|
+
* @internal
|
|
1214
1290
|
*/
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
const realHost = host || PROD_HOST;
|
|
1221
|
-
let baseUrl = `${protocol}://${realHost}`;
|
|
1222
|
-
if (typeof port === 'number') {
|
|
1223
|
-
baseUrl += `:${port}`;
|
|
1291
|
+
function getGoogApiClientValue$1(isUsingGen, callerSdkType) {
|
|
1292
|
+
let str = 'gl-js/ fire/' + SDK_VERSION;
|
|
1293
|
+
if (callerSdkType !== CallerSdkTypeEnum.Base &&
|
|
1294
|
+
callerSdkType !== CallerSdkTypeEnum.Generated) {
|
|
1295
|
+
str += ' js/' + callerSdkType.toLowerCase();
|
|
1224
1296
|
}
|
|
1225
|
-
else if (
|
|
1226
|
-
|
|
1227
|
-
throw new DataConnectError(Code.INVALID_ARGUMENT, 'Incorrect type for port passed in!');
|
|
1297
|
+
else if (isUsingGen || callerSdkType === CallerSdkTypeEnum.Generated) {
|
|
1298
|
+
str += ' js/gen';
|
|
1228
1299
|
}
|
|
1229
|
-
return
|
|
1300
|
+
return str;
|
|
1230
1301
|
}
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1302
|
+
/**
|
|
1303
|
+
* The base class for all DataConnectTransportInterface implementations. Handles common logic such as
|
|
1304
|
+
* URL construction, auth token management, and emulator usage. Concrete transport implementations
|
|
1305
|
+
* should extend this class and implement the abstract {@link DataConnectTransportInterface} methods.
|
|
1306
|
+
* @internal
|
|
1307
|
+
*/
|
|
1308
|
+
class AbstractDataConnectTransport {
|
|
1309
|
+
constructor(options, apiKey, appId, authProvider, appCheckProvider, transportOptions, _isUsingGen = false, _callerSdkType = CallerSdkTypeEnum.Base) {
|
|
1310
|
+
this.apiKey = apiKey;
|
|
1311
|
+
this.appId = appId;
|
|
1312
|
+
this.authProvider = authProvider;
|
|
1313
|
+
this.appCheckProvider = appCheckProvider;
|
|
1314
|
+
this._isUsingGen = _isUsingGen;
|
|
1315
|
+
this._callerSdkType = _callerSdkType;
|
|
1316
|
+
this._host = '';
|
|
1317
|
+
this._location = 'l';
|
|
1318
|
+
this._connectorName = '';
|
|
1319
|
+
this._secure = true;
|
|
1320
|
+
this._project = 'p';
|
|
1321
|
+
this._authToken = null;
|
|
1322
|
+
this._appCheckToken = null;
|
|
1323
|
+
this._lastToken = null;
|
|
1324
|
+
this._isUsingEmulator = false;
|
|
1325
|
+
if (transportOptions) {
|
|
1326
|
+
if (typeof transportOptions.port === 'number') {
|
|
1327
|
+
this._port = transportOptions.port;
|
|
1328
|
+
}
|
|
1329
|
+
if (typeof transportOptions.sslEnabled !== 'undefined') {
|
|
1330
|
+
this._secure = transportOptions.sslEnabled;
|
|
1331
|
+
}
|
|
1332
|
+
this._host = transportOptions.host;
|
|
1333
|
+
}
|
|
1334
|
+
const { location, projectId: project, connector, service } = options;
|
|
1335
|
+
if (location) {
|
|
1336
|
+
this._location = location;
|
|
1337
|
+
}
|
|
1338
|
+
if (project) {
|
|
1339
|
+
this._project = project;
|
|
1340
|
+
}
|
|
1341
|
+
this._serviceName = service;
|
|
1342
|
+
if (!connector) {
|
|
1343
|
+
throw new DataConnectError(Code.INVALID_ARGUMENT, 'Connector Name required!');
|
|
1344
|
+
}
|
|
1345
|
+
this._connectorName = connector;
|
|
1346
|
+
this._connectorResourcePath = `projects/${this._project}/locations/${this._location}/services/${this._serviceName}/connectors/${this._connectorName}`;
|
|
1347
|
+
this.authProvider?.addTokenChangeListener(token => {
|
|
1348
|
+
logDebug(`New Token Available: ${token}`);
|
|
1349
|
+
this.onAuthTokenChanged(token);
|
|
1350
|
+
});
|
|
1351
|
+
this.appCheckProvider?.addTokenChangeListener(result => {
|
|
1352
|
+
const { token } = result;
|
|
1353
|
+
logDebug(`New App Check Token Available: ${token}`);
|
|
1354
|
+
this._appCheckToken = token;
|
|
1355
|
+
});
|
|
1356
|
+
}
|
|
1357
|
+
useEmulator(host, port, isSecure) {
|
|
1358
|
+
this._host = host;
|
|
1359
|
+
this._isUsingEmulator = true;
|
|
1360
|
+
if (typeof port === 'number') {
|
|
1361
|
+
this._port = port;
|
|
1362
|
+
}
|
|
1363
|
+
if (typeof isSecure !== 'undefined') {
|
|
1364
|
+
this._secure = isSecure;
|
|
1365
|
+
}
|
|
1366
|
+
}
|
|
1367
|
+
async getWithAuth(forceToken = false) {
|
|
1368
|
+
let starterPromise = new Promise(resolve => resolve(this._authToken));
|
|
1369
|
+
if (this.appCheckProvider) {
|
|
1370
|
+
const appCheckToken = await this.appCheckProvider.getToken();
|
|
1371
|
+
if (appCheckToken) {
|
|
1372
|
+
this._appCheckToken = appCheckToken.token;
|
|
1373
|
+
}
|
|
1374
|
+
}
|
|
1375
|
+
if (this.authProvider) {
|
|
1376
|
+
starterPromise = this.authProvider
|
|
1377
|
+
.getToken(/*forceToken=*/ forceToken)
|
|
1378
|
+
.then(data => {
|
|
1379
|
+
if (!data) {
|
|
1380
|
+
return null;
|
|
1381
|
+
}
|
|
1382
|
+
this._authToken = data.accessToken;
|
|
1383
|
+
return this._authToken;
|
|
1384
|
+
});
|
|
1385
|
+
}
|
|
1386
|
+
else {
|
|
1387
|
+
starterPromise = new Promise(resolve => resolve(''));
|
|
1388
|
+
}
|
|
1389
|
+
return starterPromise;
|
|
1390
|
+
}
|
|
1391
|
+
async withRetry(promiseFactory, retry = false) {
|
|
1392
|
+
let isNewToken = false;
|
|
1393
|
+
return this.getWithAuth(retry)
|
|
1394
|
+
.then(res => {
|
|
1395
|
+
isNewToken = this._lastToken !== res;
|
|
1396
|
+
this._lastToken = res;
|
|
1397
|
+
return res;
|
|
1398
|
+
})
|
|
1399
|
+
.then(promiseFactory)
|
|
1400
|
+
.catch(err => {
|
|
1401
|
+
// Only retry if the result is unauthorized and the last token isn't the same as the new one.
|
|
1402
|
+
if ('code' in err &&
|
|
1403
|
+
err.code === Code.UNAUTHORIZED &&
|
|
1404
|
+
!retry &&
|
|
1405
|
+
isNewToken) {
|
|
1406
|
+
logDebug('Retrying due to unauthorized');
|
|
1407
|
+
return this.withRetry(promiseFactory, true);
|
|
1408
|
+
}
|
|
1409
|
+
throw err;
|
|
1410
|
+
});
|
|
1411
|
+
}
|
|
1412
|
+
_setLastToken(lastToken) {
|
|
1413
|
+
this._lastToken = lastToken;
|
|
1414
|
+
}
|
|
1415
|
+
_setCallerSdkType(callerSdkType) {
|
|
1416
|
+
this._callerSdkType = callerSdkType;
|
|
1234
1417
|
}
|
|
1235
|
-
const newUrl = new URL(url);
|
|
1236
|
-
newUrl.searchParams.append('key', apiKey);
|
|
1237
|
-
return newUrl.toString();
|
|
1238
1418
|
}
|
|
1239
1419
|
|
|
1240
1420
|
/**
|
|
@@ -1253,6 +1433,7 @@ function addToken(url, apiKey) {
|
|
|
1253
1433
|
* See the License for the specific language governing permissions and
|
|
1254
1434
|
* limitations under the License.
|
|
1255
1435
|
*/
|
|
1436
|
+
/** The fetch implementation to be used by the {@link RESTTransport}. */
|
|
1256
1437
|
let connectFetch = globalThis.fetch;
|
|
1257
1438
|
function getGoogApiClientValue(_isUsingGen, _callerSdkType) {
|
|
1258
1439
|
let str = 'gl-js/ fire/' + SDK_VERSION;
|
|
@@ -1297,14 +1478,20 @@ async function dcFetch(url, body, { signal }, appId, accessToken, appCheckToken,
|
|
|
1297
1478
|
response = await connectFetch(url, fetchOptions);
|
|
1298
1479
|
}
|
|
1299
1480
|
catch (err) {
|
|
1300
|
-
|
|
1481
|
+
const message = err && typeof err === 'object' && 'message' in err
|
|
1482
|
+
? err['message']
|
|
1483
|
+
: String(err);
|
|
1484
|
+
throw new DataConnectError(Code.OTHER, 'Failed to fetch: ' + message);
|
|
1301
1485
|
}
|
|
1302
1486
|
let jsonResponse;
|
|
1303
1487
|
try {
|
|
1304
1488
|
jsonResponse = await response.json();
|
|
1305
1489
|
}
|
|
1306
1490
|
catch (e) {
|
|
1307
|
-
|
|
1491
|
+
const message = e && typeof e === 'object' && 'message' in e
|
|
1492
|
+
? e['message']
|
|
1493
|
+
: String(e);
|
|
1494
|
+
throw new DataConnectError(Code.OTHER, 'Failed to parse JSON response: ' + message);
|
|
1308
1495
|
}
|
|
1309
1496
|
const message = getErrorMessage(jsonResponse);
|
|
1310
1497
|
if (response.status >= 400) {
|
|
@@ -1352,147 +1539,980 @@ function getErrorMessage(obj) {
|
|
|
1352
1539
|
* See the License for the specific language governing permissions and
|
|
1353
1540
|
* limitations under the License.
|
|
1354
1541
|
*/
|
|
1355
|
-
|
|
1542
|
+
const PROD_HOST = 'firebasedataconnect.googleapis.com';
|
|
1543
|
+
const WEBSOCKET_PATH = 'ws/google.firebase.dataconnect.v1.ConnectorStreamService';
|
|
1544
|
+
function restUrlBuilder(projectConfig, transportOptions) {
|
|
1545
|
+
const { connector, location, projectId: project, service } = projectConfig;
|
|
1546
|
+
const { host, sslEnabled, port } = transportOptions;
|
|
1547
|
+
const protocol = sslEnabled ? 'https' : 'http';
|
|
1548
|
+
const realHost = host || PROD_HOST;
|
|
1549
|
+
let baseUrl = `${protocol}://${realHost}`;
|
|
1550
|
+
if (typeof port === 'number') {
|
|
1551
|
+
baseUrl += `:${port}`;
|
|
1552
|
+
}
|
|
1553
|
+
else if (typeof port !== 'undefined') {
|
|
1554
|
+
logError('Port type is of an invalid type');
|
|
1555
|
+
throw new DataConnectError(Code.INVALID_ARGUMENT, 'Incorrect type for port passed in!');
|
|
1556
|
+
}
|
|
1557
|
+
return `${baseUrl}/v1/projects/${project}/locations/${location}/services/${service}/connectors/${connector}`;
|
|
1558
|
+
}
|
|
1559
|
+
function websocketUrlBuilder(projectConfig, transportOptions) {
|
|
1560
|
+
const { location } = projectConfig;
|
|
1561
|
+
const { host, sslEnabled, port } = transportOptions;
|
|
1562
|
+
const protocol = sslEnabled ? 'wss' : 'ws';
|
|
1563
|
+
const realHost = host || PROD_HOST;
|
|
1564
|
+
let baseUrl = `${protocol}://${realHost}`;
|
|
1565
|
+
if (typeof port === 'number') {
|
|
1566
|
+
baseUrl += `:${port}`;
|
|
1567
|
+
}
|
|
1568
|
+
else if (typeof port !== 'undefined') {
|
|
1569
|
+
logError('Port type is of an invalid type');
|
|
1570
|
+
throw new DataConnectError(Code.INVALID_ARGUMENT, 'Incorrect type for port passed in!');
|
|
1571
|
+
}
|
|
1572
|
+
return `${baseUrl}/${WEBSOCKET_PATH}/Connect/locations/${location}`;
|
|
1573
|
+
}
|
|
1574
|
+
function addToken(url, apiKey) {
|
|
1575
|
+
if (!apiKey) {
|
|
1576
|
+
return url;
|
|
1577
|
+
}
|
|
1578
|
+
const newUrl = new URL(url);
|
|
1579
|
+
newUrl.searchParams.append('key', apiKey);
|
|
1580
|
+
return newUrl.toString();
|
|
1581
|
+
}
|
|
1582
|
+
|
|
1583
|
+
/**
|
|
1584
|
+
* @license
|
|
1585
|
+
* Copyright 2024 Google LLC
|
|
1586
|
+
*
|
|
1587
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
1588
|
+
* you may not use this file except in compliance with the License.
|
|
1589
|
+
* You may obtain a copy of the License at
|
|
1590
|
+
*
|
|
1591
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
1592
|
+
*
|
|
1593
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
1594
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
1595
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
1596
|
+
* See the License for the specific language governing permissions and
|
|
1597
|
+
* limitations under the License.
|
|
1598
|
+
*/
|
|
1599
|
+
/**
|
|
1600
|
+
* Fetch-based REST implementation of {@link AbstractDataConnectTransport}.
|
|
1601
|
+
* @internal
|
|
1602
|
+
*/
|
|
1603
|
+
class RESTTransport extends AbstractDataConnectTransport {
|
|
1356
1604
|
constructor(options, apiKey, appId, authProvider, appCheckProvider, transportOptions, _isUsingGen = false, _callerSdkType = CallerSdkTypeEnum.Base) {
|
|
1357
|
-
|
|
1358
|
-
this.appId = appId;
|
|
1359
|
-
this.authProvider = authProvider;
|
|
1360
|
-
this.appCheckProvider = appCheckProvider;
|
|
1361
|
-
this._isUsingGen = _isUsingGen;
|
|
1362
|
-
this._callerSdkType = _callerSdkType;
|
|
1363
|
-
this._host = '';
|
|
1364
|
-
this._location = 'l';
|
|
1365
|
-
this._connectorName = '';
|
|
1366
|
-
this._secure = true;
|
|
1367
|
-
this._project = 'p';
|
|
1368
|
-
this._accessToken = null;
|
|
1369
|
-
this._appCheckToken = null;
|
|
1370
|
-
this._lastToken = null;
|
|
1371
|
-
this._isUsingEmulator = false;
|
|
1372
|
-
// TODO(mtewani): Update U to include shape of body defined in line 13.
|
|
1605
|
+
super(options, apiKey, appId, authProvider, appCheckProvider, transportOptions, _isUsingGen, _callerSdkType);
|
|
1373
1606
|
this.invokeQuery = (queryName, body) => {
|
|
1374
1607
|
const abortController = new AbortController();
|
|
1375
1608
|
// TODO(mtewani): Update to proper value
|
|
1376
1609
|
const withAuth = this.withRetry(() => dcFetch(addToken(`${this.endpointUrl}:executeQuery`, this.apiKey), {
|
|
1377
|
-
name:
|
|
1610
|
+
name: this._connectorResourcePath,
|
|
1378
1611
|
operationName: queryName,
|
|
1379
1612
|
variables: body
|
|
1380
|
-
}, abortController, this.appId, this.
|
|
1613
|
+
}, abortController, this.appId, this._authToken, this._appCheckToken, this._isUsingGen, this._callerSdkType, this._isUsingEmulator));
|
|
1381
1614
|
return withAuth;
|
|
1382
1615
|
};
|
|
1383
1616
|
this.invokeMutation = (mutationName, body) => {
|
|
1384
1617
|
const abortController = new AbortController();
|
|
1385
1618
|
const taskResult = this.withRetry(() => {
|
|
1386
1619
|
return dcFetch(addToken(`${this.endpointUrl}:executeMutation`, this.apiKey), {
|
|
1387
|
-
name:
|
|
1620
|
+
name: this._connectorResourcePath,
|
|
1388
1621
|
operationName: mutationName,
|
|
1389
1622
|
variables: body
|
|
1390
|
-
}, abortController, this.appId, this.
|
|
1623
|
+
}, abortController, this.appId, this._authToken, this._appCheckToken, this._isUsingGen, this._callerSdkType, this._isUsingEmulator);
|
|
1391
1624
|
});
|
|
1392
1625
|
return taskResult;
|
|
1393
1626
|
};
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
|
|
1397
|
-
|
|
1398
|
-
|
|
1399
|
-
|
|
1400
|
-
|
|
1401
|
-
|
|
1402
|
-
|
|
1403
|
-
|
|
1404
|
-
|
|
1405
|
-
|
|
1627
|
+
}
|
|
1628
|
+
get endpointUrl() {
|
|
1629
|
+
return restUrlBuilder({
|
|
1630
|
+
connector: this._connectorName,
|
|
1631
|
+
location: this._location,
|
|
1632
|
+
projectId: this._project,
|
|
1633
|
+
service: this._serviceName
|
|
1634
|
+
}, {
|
|
1635
|
+
host: this._host,
|
|
1636
|
+
sslEnabled: this._secure,
|
|
1637
|
+
port: this._port
|
|
1638
|
+
});
|
|
1639
|
+
}
|
|
1640
|
+
invokeSubscribe(observer, queryName, body) {
|
|
1641
|
+
throw new DataConnectError(Code.NOT_SUPPORTED, 'Subscriptions are not supported using REST!');
|
|
1642
|
+
}
|
|
1643
|
+
invokeUnsubscribe(queryName, body) {
|
|
1644
|
+
throw new DataConnectError(Code.NOT_SUPPORTED, 'Unsubscriptions are not supported using REST!');
|
|
1645
|
+
}
|
|
1646
|
+
onAuthTokenChanged(newToken) {
|
|
1647
|
+
this._authToken = newToken;
|
|
1648
|
+
}
|
|
1649
|
+
}
|
|
1650
|
+
|
|
1651
|
+
/**
|
|
1652
|
+
* @license
|
|
1653
|
+
* Copyright 2026 Google LLC
|
|
1654
|
+
*
|
|
1655
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
1656
|
+
* you may not use this file except in compliance with the License.
|
|
1657
|
+
* You may obtain a copy of the License at
|
|
1658
|
+
*
|
|
1659
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
1660
|
+
*
|
|
1661
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
1662
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
1663
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
1664
|
+
* See the License for the specific language governing permissions and
|
|
1665
|
+
* limitations under the License.
|
|
1666
|
+
*/
|
|
1667
|
+
/** The request id of the first request over the stream */
|
|
1668
|
+
const FIRST_REQUEST_ID = 1;
|
|
1669
|
+
/** Time to wait before closing an idle connection (no active subscriptions) */
|
|
1670
|
+
const IDLE_CONNECTION_TIMEOUT_MS = 60 * 1000; // 1 minute
|
|
1671
|
+
/**
|
|
1672
|
+
* The base class for all {@link DataConnectStreamTransport | Stream Transport} implementations.
|
|
1673
|
+
* Handles management of logical streams (requests), authentication, data routing to query layer, etc.
|
|
1674
|
+
* @internal
|
|
1675
|
+
*/
|
|
1676
|
+
class AbstractDataConnectStreamTransport extends AbstractDataConnectTransport {
|
|
1677
|
+
constructor() {
|
|
1678
|
+
super(...arguments);
|
|
1679
|
+
this.pendingClose = false;
|
|
1680
|
+
/** True if the transport is unable to connect to the server */
|
|
1681
|
+
this.isUnableToConnect = false;
|
|
1682
|
+
/** The request ID of the next message to be sent. Monotonically increasing sequence number. */
|
|
1683
|
+
this.requestNumber = FIRST_REQUEST_ID;
|
|
1684
|
+
/**
|
|
1685
|
+
* Map of query/variables to their active execute/resume request bodies.
|
|
1686
|
+
*/
|
|
1687
|
+
this.activeQueryExecuteRequests = new Map();
|
|
1688
|
+
/**
|
|
1689
|
+
* Map of mutation/variables to their active execute request bodies.
|
|
1690
|
+
*/
|
|
1691
|
+
this.activeMutationExecuteRequests = new Map();
|
|
1692
|
+
/**
|
|
1693
|
+
* Map of query/variables to their active subscribe request bodies.
|
|
1694
|
+
*/
|
|
1695
|
+
this.activeSubscribeRequests = new Map();
|
|
1696
|
+
/**
|
|
1697
|
+
* Map of active execution RequestIds and their corresponding Promises and resolvers.
|
|
1698
|
+
*/
|
|
1699
|
+
this.executeRequestPromises = new Map();
|
|
1700
|
+
/**
|
|
1701
|
+
* Map of active subscription RequestIds and their corresponding observers.
|
|
1702
|
+
*/
|
|
1703
|
+
this.subscribeObservers = new Map();
|
|
1704
|
+
/** current close timeout from setTimeout(), if any */
|
|
1705
|
+
this.closeTimeout = null;
|
|
1706
|
+
/** has the close timeout finished? */
|
|
1707
|
+
this.closeTimeoutFinished = false;
|
|
1708
|
+
/**
|
|
1709
|
+
* Tracks if the next message to be sent is the first message of the stream.
|
|
1710
|
+
*/
|
|
1711
|
+
this.isFirstStreamMessage = true;
|
|
1712
|
+
/**
|
|
1713
|
+
* Tracks the last auth token sent to the server.
|
|
1714
|
+
* Used to detect if the token has changed and needs to be resent.
|
|
1715
|
+
*/
|
|
1716
|
+
this.lastSentAuthToken = null;
|
|
1717
|
+
}
|
|
1718
|
+
/** Is the stream currently waiting to close connection? */
|
|
1719
|
+
get isPendingClose() {
|
|
1720
|
+
return this.pendingClose;
|
|
1721
|
+
}
|
|
1722
|
+
/** True if there are active subscriptions on the stream */
|
|
1723
|
+
get hasActiveSubscriptions() {
|
|
1724
|
+
return this.activeSubscribeRequests.size > 0;
|
|
1725
|
+
}
|
|
1726
|
+
/** True if there are active execute or mutation requests on the stream */
|
|
1727
|
+
get hasActiveExecuteRequests() {
|
|
1728
|
+
return (this.activeQueryExecuteRequests.size > 0 ||
|
|
1729
|
+
this.activeMutationExecuteRequests.size > 0);
|
|
1730
|
+
}
|
|
1731
|
+
/**
|
|
1732
|
+
* Generates and returns the next request ID.
|
|
1733
|
+
*/
|
|
1734
|
+
nextRequestId() {
|
|
1735
|
+
return (this.requestNumber++).toString();
|
|
1736
|
+
}
|
|
1737
|
+
/**
|
|
1738
|
+
* Tracks a query execution request, storing the request body and creating and storing a promise that
|
|
1739
|
+
* will be resolved when the response is received.
|
|
1740
|
+
* @returns The reject function and the response promise.
|
|
1741
|
+
*
|
|
1742
|
+
* @remarks
|
|
1743
|
+
* This method returns a promise, but is synchronous.
|
|
1744
|
+
*/
|
|
1745
|
+
trackQueryExecuteRequest(requestId, mapKey, executeBody) {
|
|
1746
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
1747
|
+
let resolveFn;
|
|
1748
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
1749
|
+
let rejectFn;
|
|
1750
|
+
const responsePromise = new Promise((resolve, reject) => {
|
|
1751
|
+
resolveFn = resolve;
|
|
1752
|
+
rejectFn = reject;
|
|
1753
|
+
});
|
|
1754
|
+
const executeRequestPromise = {
|
|
1755
|
+
responsePromise,
|
|
1756
|
+
resolveFn: resolveFn,
|
|
1757
|
+
rejectFn: rejectFn
|
|
1758
|
+
};
|
|
1759
|
+
this.activeQueryExecuteRequests.set(mapKey, executeBody);
|
|
1760
|
+
this.executeRequestPromises.set(requestId, executeRequestPromise);
|
|
1761
|
+
return executeRequestPromise;
|
|
1762
|
+
}
|
|
1763
|
+
/**
|
|
1764
|
+
* Tracks a mutation execution request, storing the request body and creating and storing a promise
|
|
1765
|
+
* that will be resolved when the response is received.
|
|
1766
|
+
* @returns The reject function and the response promise.
|
|
1767
|
+
*
|
|
1768
|
+
* @remarks
|
|
1769
|
+
* This method returns a promise, but is synchronous.
|
|
1770
|
+
*/
|
|
1771
|
+
trackMutationExecuteRequest(requestId, mapKey, executeBody) {
|
|
1772
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
1773
|
+
let resolveFn;
|
|
1774
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
1775
|
+
let rejectFn;
|
|
1776
|
+
const responsePromise = new Promise((resolve, reject) => {
|
|
1777
|
+
resolveFn = resolve;
|
|
1778
|
+
rejectFn = reject;
|
|
1779
|
+
});
|
|
1780
|
+
const executeRequestPromise = {
|
|
1781
|
+
responsePromise,
|
|
1782
|
+
resolveFn: resolveFn,
|
|
1783
|
+
rejectFn: rejectFn
|
|
1784
|
+
};
|
|
1785
|
+
const activeRequests = this.activeMutationExecuteRequests.get(mapKey) || [];
|
|
1786
|
+
activeRequests.push(executeBody);
|
|
1787
|
+
this.activeMutationExecuteRequests.set(mapKey, activeRequests);
|
|
1788
|
+
this.executeRequestPromises.set(requestId, executeRequestPromise);
|
|
1789
|
+
return executeRequestPromise;
|
|
1790
|
+
}
|
|
1791
|
+
/**
|
|
1792
|
+
* Tracks a subscribe request, storing the request body and the notification observer.
|
|
1793
|
+
* @remarks
|
|
1794
|
+
* This method is synchronous.
|
|
1795
|
+
*/
|
|
1796
|
+
trackSubscribeRequest(requestId, mapKey, subscribeBody, observer) {
|
|
1797
|
+
this.activeSubscribeRequests.set(mapKey, subscribeBody);
|
|
1798
|
+
this.subscribeObservers.set(requestId, observer);
|
|
1799
|
+
}
|
|
1800
|
+
/**
|
|
1801
|
+
* Cleans up the query execute request tracking data structures, deleting the tracked request and
|
|
1802
|
+
* it's associated promise.
|
|
1803
|
+
*/
|
|
1804
|
+
cleanupQueryExecuteRequest(requestId, mapKey) {
|
|
1805
|
+
this.activeQueryExecuteRequests.delete(mapKey);
|
|
1806
|
+
this.executeRequestPromises.delete(requestId);
|
|
1807
|
+
}
|
|
1808
|
+
/**
|
|
1809
|
+
* Cleans up the mutation execute request tracking data structures, deleting the tracked request and
|
|
1810
|
+
* it's associated promise.
|
|
1811
|
+
*/
|
|
1812
|
+
cleanupMutationExecuteRequest(requestId, mapKey) {
|
|
1813
|
+
const executeRequests = this.activeMutationExecuteRequests.get(mapKey);
|
|
1814
|
+
if (executeRequests) {
|
|
1815
|
+
const updatedRequests = executeRequests.filter(req => req.requestId !== requestId);
|
|
1816
|
+
if (updatedRequests.length > 0) {
|
|
1817
|
+
this.activeMutationExecuteRequests.set(mapKey, updatedRequests);
|
|
1818
|
+
}
|
|
1819
|
+
else {
|
|
1820
|
+
this.activeMutationExecuteRequests.delete(mapKey);
|
|
1821
|
+
}
|
|
1406
1822
|
}
|
|
1407
|
-
|
|
1408
|
-
|
|
1823
|
+
this.executeRequestPromises.delete(requestId);
|
|
1824
|
+
}
|
|
1825
|
+
/**
|
|
1826
|
+
* Cleans up the subscribe request tracking data structures, deleting the tracked request and
|
|
1827
|
+
* it's associated promise.
|
|
1828
|
+
*/
|
|
1829
|
+
cleanupSubscribeRequest(requestId, mapKey) {
|
|
1830
|
+
this.activeSubscribeRequests.delete(mapKey);
|
|
1831
|
+
this.subscribeObservers.delete(requestId);
|
|
1832
|
+
}
|
|
1833
|
+
/**
|
|
1834
|
+
* Indicates whether we should include the auth token in the next message.
|
|
1835
|
+
* Only true if there is an auth token and it is different from the last sent auth token, or this
|
|
1836
|
+
* is the first message.
|
|
1837
|
+
*/
|
|
1838
|
+
get shouldIncludeAuth() {
|
|
1839
|
+
return (this.isFirstStreamMessage ||
|
|
1840
|
+
(!!this._authToken && this._authToken !== this.lastSentAuthToken));
|
|
1841
|
+
}
|
|
1842
|
+
/**
|
|
1843
|
+
* Called by the concrete transport implementation when the physical connection is ready.
|
|
1844
|
+
*/
|
|
1845
|
+
onConnectionReady() {
|
|
1846
|
+
this.isFirstStreamMessage = true;
|
|
1847
|
+
this.lastSentAuthToken = null;
|
|
1848
|
+
}
|
|
1849
|
+
/**
|
|
1850
|
+
* Attempt to close the connection. Will only close if there are no active requests preventing it
|
|
1851
|
+
* from doing so.
|
|
1852
|
+
*/
|
|
1853
|
+
async attemptClose() {
|
|
1854
|
+
if (this.hasActiveSubscriptions || this.hasActiveExecuteRequests) {
|
|
1855
|
+
return;
|
|
1409
1856
|
}
|
|
1410
|
-
this.
|
|
1411
|
-
|
|
1412
|
-
|
|
1857
|
+
this.cancelClose();
|
|
1858
|
+
await this.closeConnection();
|
|
1859
|
+
this.onGracefulStreamClose?.();
|
|
1860
|
+
}
|
|
1861
|
+
/**
|
|
1862
|
+
* Begin closing the connection. Waits for and cleans up all active requests, and waits for
|
|
1863
|
+
* {@link IDLE_CONNECTION_TIMEOUT_MS}. This is a graceful close - it will be called when there are
|
|
1864
|
+
* no more active subscriptions, so there's no need to cleanup.
|
|
1865
|
+
*/
|
|
1866
|
+
prepareToCloseGracefully() {
|
|
1867
|
+
if (this.pendingClose) {
|
|
1868
|
+
return;
|
|
1413
1869
|
}
|
|
1414
|
-
this.
|
|
1415
|
-
this.
|
|
1416
|
-
|
|
1417
|
-
this.
|
|
1870
|
+
this.pendingClose = true;
|
|
1871
|
+
this.closeTimeoutFinished = false;
|
|
1872
|
+
this.closeTimeout = setTimeout(() => {
|
|
1873
|
+
this.closeTimeoutFinished = true;
|
|
1874
|
+
void this.attemptClose();
|
|
1875
|
+
}, IDLE_CONNECTION_TIMEOUT_MS);
|
|
1876
|
+
}
|
|
1877
|
+
/**
|
|
1878
|
+
* Cancel closing the connection.
|
|
1879
|
+
*/
|
|
1880
|
+
cancelClose() {
|
|
1881
|
+
if (this.closeTimeout) {
|
|
1882
|
+
clearTimeout(this.closeTimeout);
|
|
1883
|
+
}
|
|
1884
|
+
this.pendingClose = false;
|
|
1885
|
+
this.closeTimeoutFinished = false;
|
|
1886
|
+
}
|
|
1887
|
+
/**
|
|
1888
|
+
* Reject all active execute promises and notify all subscribe observers with the given error.
|
|
1889
|
+
* Clear active request tracking maps without cancelling or re-invoking any requests.
|
|
1890
|
+
*/
|
|
1891
|
+
rejectAllActiveRequests(code, reason) {
|
|
1892
|
+
this.activeQueryExecuteRequests.clear();
|
|
1893
|
+
this.activeMutationExecuteRequests.clear();
|
|
1894
|
+
this.activeSubscribeRequests.clear();
|
|
1895
|
+
const error = new DataConnectError(code, reason);
|
|
1896
|
+
for (const [requestId, { rejectFn }] of this.executeRequestPromises) {
|
|
1897
|
+
this.executeRequestPromises.delete(requestId);
|
|
1898
|
+
rejectFn(error);
|
|
1899
|
+
}
|
|
1900
|
+
for (const [requestId, observer] of this.subscribeObservers) {
|
|
1901
|
+
this.subscribeObservers.delete(requestId);
|
|
1902
|
+
observer.onDisconnect(code, reason);
|
|
1903
|
+
}
|
|
1904
|
+
}
|
|
1905
|
+
/**
|
|
1906
|
+
* Called by concrete implementations when the stream is successfully closed, gracefully or otherwise.
|
|
1907
|
+
*/
|
|
1908
|
+
onStreamClose(code, reason) {
|
|
1909
|
+
this.rejectAllActiveRequests(Code.OTHER, `Stream disconnected with code ${code}: ${reason}`);
|
|
1910
|
+
}
|
|
1911
|
+
/**
|
|
1912
|
+
* Prepares a stream request message by adding necessary headers and metadata.
|
|
1913
|
+
* If this is the first message on the stream, it includes the resource name, auth token, and App Check token.
|
|
1914
|
+
* If the auth token has refreshed since the last message, it includes the new auth token.
|
|
1915
|
+
*
|
|
1916
|
+
* This method is called by the concrete transport implementation before sending a message.
|
|
1917
|
+
*
|
|
1918
|
+
* @returns the requestBody, with attached headers and initial request fields
|
|
1919
|
+
*/
|
|
1920
|
+
prepareMessage(requestBody) {
|
|
1921
|
+
const preparedRequestBody = { ...requestBody };
|
|
1922
|
+
const headers = {};
|
|
1923
|
+
if (this.appId) {
|
|
1924
|
+
headers['x-firebase-gmpid'] = this.appId;
|
|
1925
|
+
}
|
|
1926
|
+
headers['X-Goog-Api-Client'] = getGoogApiClientValue$1(this._isUsingGen, this._callerSdkType);
|
|
1927
|
+
if (this.shouldIncludeAuth && this._authToken) {
|
|
1928
|
+
headers.authToken = this._authToken;
|
|
1929
|
+
this.lastSentAuthToken = this._authToken;
|
|
1930
|
+
}
|
|
1931
|
+
if (this.isFirstStreamMessage) {
|
|
1932
|
+
if (this._appCheckToken) {
|
|
1933
|
+
headers.appCheckToken = this._appCheckToken;
|
|
1934
|
+
}
|
|
1935
|
+
preparedRequestBody.name = this._connectorResourcePath;
|
|
1936
|
+
}
|
|
1937
|
+
preparedRequestBody.headers = headers;
|
|
1938
|
+
this.isFirstStreamMessage = false;
|
|
1939
|
+
return preparedRequestBody;
|
|
1940
|
+
}
|
|
1941
|
+
/**
|
|
1942
|
+
* Sends a request message to the server via the concrete implementation.
|
|
1943
|
+
* Ensures the connection is ready and prepares the message before sending.
|
|
1944
|
+
* @returns A promise that resolves when the request message has been sent.
|
|
1945
|
+
*/
|
|
1946
|
+
sendRequestMessage(requestBody) {
|
|
1947
|
+
if (this.streamIsReady) {
|
|
1948
|
+
const prepared = this.prepareMessage(requestBody);
|
|
1949
|
+
return this.sendMessage(prepared);
|
|
1950
|
+
}
|
|
1951
|
+
return this.ensureConnection().then(() => {
|
|
1952
|
+
const prepared = this.prepareMessage(requestBody);
|
|
1953
|
+
return this.sendMessage(prepared);
|
|
1418
1954
|
});
|
|
1419
|
-
|
|
1420
|
-
|
|
1421
|
-
|
|
1422
|
-
|
|
1955
|
+
}
|
|
1956
|
+
/**
|
|
1957
|
+
* Helper to generate a consistent string key for the tracking maps.
|
|
1958
|
+
*/
|
|
1959
|
+
getMapKey(operationName, variables) {
|
|
1960
|
+
const sortedVariables = this.sortObjectKeys(variables);
|
|
1961
|
+
return JSON.stringify({ operationName, variables: sortedVariables });
|
|
1962
|
+
}
|
|
1963
|
+
/**
|
|
1964
|
+
* Recursively sorts the keys of an object.
|
|
1965
|
+
*/
|
|
1966
|
+
sortObjectKeys(obj) {
|
|
1967
|
+
if (obj === null || typeof obj !== 'object' || Array.isArray(obj)) {
|
|
1968
|
+
return obj;
|
|
1969
|
+
}
|
|
1970
|
+
const sortedObj = {};
|
|
1971
|
+
Object.keys(obj)
|
|
1972
|
+
.sort()
|
|
1973
|
+
.forEach(key => {
|
|
1974
|
+
sortedObj[key] = this.sortObjectKeys(obj[key]);
|
|
1975
|
+
});
|
|
1976
|
+
return sortedObj;
|
|
1977
|
+
}
|
|
1978
|
+
/**
|
|
1979
|
+
* @inheritdoc
|
|
1980
|
+
* @remarks
|
|
1981
|
+
* This method synchronously updates the request tracking data structures before sending any message.
|
|
1982
|
+
* If any asynchronous functionality is added to this function, it MUST be done in a way that
|
|
1983
|
+
* preserves the synchronous update of the tracking data structures before the method returns.
|
|
1984
|
+
*/
|
|
1985
|
+
invokeQuery(queryName, variables) {
|
|
1986
|
+
const requestId = this.nextRequestId();
|
|
1987
|
+
const activeRequestKey = { operationName: queryName, variables };
|
|
1988
|
+
const mapKey = this.getMapKey(queryName, variables);
|
|
1989
|
+
const executeBody = {
|
|
1990
|
+
requestId,
|
|
1991
|
+
execute: activeRequestKey
|
|
1992
|
+
};
|
|
1993
|
+
let { responsePromise, rejectFn } = this.trackQueryExecuteRequest(requestId, mapKey, executeBody);
|
|
1994
|
+
responsePromise = responsePromise.finally(() => {
|
|
1995
|
+
this.cleanupQueryExecuteRequest(requestId, mapKey);
|
|
1996
|
+
if (!this.hasActiveSubscriptions &&
|
|
1997
|
+
!this.hasActiveExecuteRequests &&
|
|
1998
|
+
this.closeTimeoutFinished) {
|
|
1999
|
+
void this.attemptClose();
|
|
2000
|
+
}
|
|
2001
|
+
});
|
|
2002
|
+
// asynchronous, fire and forget
|
|
2003
|
+
this.sendRequestMessage(executeBody).catch(err => {
|
|
2004
|
+
rejectFn(err);
|
|
2005
|
+
});
|
|
2006
|
+
return responsePromise;
|
|
2007
|
+
}
|
|
2008
|
+
/**
|
|
2009
|
+
* @inheritdoc
|
|
2010
|
+
* @remarks
|
|
2011
|
+
* This method synchronously updates the request tracking data structures before sending any message.
|
|
2012
|
+
* If any asynchronous functionality is added to this function, it MUST be done in a way that
|
|
2013
|
+
* preserves the synchronous update of the tracking data structures before the method returns.
|
|
2014
|
+
*/
|
|
2015
|
+
invokeMutation(mutationName, variables) {
|
|
2016
|
+
const requestId = this.nextRequestId();
|
|
2017
|
+
const activeRequestKey = { operationName: mutationName, variables };
|
|
2018
|
+
const mapKey = this.getMapKey(mutationName, variables);
|
|
2019
|
+
const executeBody = {
|
|
2020
|
+
requestId,
|
|
2021
|
+
execute: activeRequestKey
|
|
2022
|
+
};
|
|
2023
|
+
let { responsePromise, rejectFn } = this.trackMutationExecuteRequest(requestId, mapKey, executeBody);
|
|
2024
|
+
responsePromise = responsePromise.finally(() => {
|
|
2025
|
+
this.cleanupMutationExecuteRequest(requestId, mapKey);
|
|
2026
|
+
if (!this.hasActiveSubscriptions &&
|
|
2027
|
+
!this.hasActiveExecuteRequests &&
|
|
2028
|
+
this.closeTimeoutFinished) {
|
|
2029
|
+
void this.attemptClose();
|
|
2030
|
+
}
|
|
2031
|
+
});
|
|
2032
|
+
// asynchronous, fire and forget
|
|
2033
|
+
this.sendRequestMessage(executeBody).catch(err => {
|
|
2034
|
+
rejectFn(err);
|
|
1423
2035
|
});
|
|
2036
|
+
return responsePromise;
|
|
2037
|
+
}
|
|
2038
|
+
/**
|
|
2039
|
+
* @inheritdoc
|
|
2040
|
+
* @remarks
|
|
2041
|
+
* This method synchronously updates the request tracking data structures before sending any message
|
|
2042
|
+
* or cancelling the closing of the stream. If any asynchronous functionality is added to this function,
|
|
2043
|
+
* it MUST be done in a way that preserves the synchronous update of the tracking data structures
|
|
2044
|
+
* before the method returns.
|
|
2045
|
+
*/
|
|
2046
|
+
invokeSubscribe(observer, queryName, variables) {
|
|
2047
|
+
// if we are waiting to close the stream, cancel closing!
|
|
2048
|
+
this.cancelClose();
|
|
2049
|
+
const requestId = this.nextRequestId();
|
|
2050
|
+
const activeRequestKey = { operationName: queryName, variables };
|
|
2051
|
+
const mapKey = this.getMapKey(queryName, variables);
|
|
2052
|
+
const subscribeBody = {
|
|
2053
|
+
requestId,
|
|
2054
|
+
subscribe: activeRequestKey
|
|
2055
|
+
};
|
|
2056
|
+
this.trackSubscribeRequest(requestId, mapKey, subscribeBody, observer);
|
|
2057
|
+
// asynchronous, fire and forget
|
|
2058
|
+
this.sendRequestMessage(subscribeBody).catch(err => {
|
|
2059
|
+
observer.onError(err instanceof Error ? err : new Error(String(err)));
|
|
2060
|
+
this.cleanupSubscribeRequest(requestId, mapKey);
|
|
2061
|
+
if (!this.hasActiveSubscriptions) {
|
|
2062
|
+
this.prepareToCloseGracefully();
|
|
2063
|
+
}
|
|
2064
|
+
});
|
|
2065
|
+
}
|
|
2066
|
+
/**
|
|
2067
|
+
* @inheritdoc
|
|
2068
|
+
* @remarks
|
|
2069
|
+
* This method synchronously updates the request tracking data structures before sending any message.
|
|
2070
|
+
* If any asynchronous functionality is added to this function, it MUST be done in a way that
|
|
2071
|
+
* preserves the synchronous update of the tracking data structures before the method returns.
|
|
2072
|
+
*/
|
|
2073
|
+
invokeUnsubscribe(queryName, variables) {
|
|
2074
|
+
const mapKey = this.getMapKey(queryName, variables);
|
|
2075
|
+
const subscribeRequest = this.activeSubscribeRequests.get(mapKey);
|
|
2076
|
+
if (!subscribeRequest) {
|
|
2077
|
+
return;
|
|
2078
|
+
}
|
|
2079
|
+
const requestId = subscribeRequest.requestId;
|
|
2080
|
+
const cancelBody = {
|
|
2081
|
+
requestId,
|
|
2082
|
+
cancel: {}
|
|
2083
|
+
};
|
|
2084
|
+
this.cleanupSubscribeRequest(requestId, mapKey);
|
|
2085
|
+
// asynchronous, fire and forget
|
|
2086
|
+
this.sendRequestMessage(cancelBody).catch(err => {
|
|
2087
|
+
logError(`Stream Transport failed to send unsubscribe message: ${err}`);
|
|
2088
|
+
});
|
|
2089
|
+
if (!this.hasActiveSubscriptions) {
|
|
2090
|
+
this.prepareToCloseGracefully();
|
|
2091
|
+
}
|
|
2092
|
+
}
|
|
2093
|
+
onAuthTokenChanged(newToken) {
|
|
2094
|
+
const oldAuthToken = this._authToken;
|
|
2095
|
+
this._authToken = newToken;
|
|
2096
|
+
const oldAuthUid = this.authUid;
|
|
2097
|
+
const newAuthUid = this.authProvider?.getAuth()?.getUid();
|
|
2098
|
+
this.authUid = newAuthUid;
|
|
2099
|
+
// onAuthTokenChanged gets called by the auth provider once it initializes, so we must make sure
|
|
2100
|
+
// we don't prematurely disconnect the stream if this is the initial call.
|
|
2101
|
+
const isInitialAuth = oldAuthUid === undefined;
|
|
2102
|
+
if (isInitialAuth) {
|
|
2103
|
+
return;
|
|
2104
|
+
}
|
|
2105
|
+
if ((oldAuthToken && newToken === null) || // user logged out
|
|
2106
|
+
(!oldAuthUid && newAuthUid) || // user logged in
|
|
2107
|
+
(oldAuthUid && newAuthUid !== oldAuthUid) // logged in user changed
|
|
2108
|
+
) {
|
|
2109
|
+
this.rejectAllActiveRequests(Code.UNAUTHORIZED, 'Stream disconnected due to auth change.');
|
|
2110
|
+
void this.attemptClose();
|
|
2111
|
+
}
|
|
2112
|
+
}
|
|
2113
|
+
/**
|
|
2114
|
+
* Handle a response message from the server. Called by the connection-specific implementation after
|
|
2115
|
+
* it's transformed a message from the server into a {@link DataConnectResponse}.
|
|
2116
|
+
* @param requestId the requestId associated with this response.
|
|
2117
|
+
* @param response the response from the server.
|
|
2118
|
+
*/
|
|
2119
|
+
async handleResponse(requestId, response) {
|
|
2120
|
+
if (this.executeRequestPromises.has(requestId)) {
|
|
2121
|
+
// don't clean up the tracking maps here, they're handled automatically when the execute promise settles
|
|
2122
|
+
const { resolveFn, rejectFn } = this.executeRequestPromises.get(requestId);
|
|
2123
|
+
if (response.errors && response.errors.length) {
|
|
2124
|
+
const failureResponse = {
|
|
2125
|
+
errors: response.errors,
|
|
2126
|
+
data: response.data
|
|
2127
|
+
};
|
|
2128
|
+
const stringified = JSON.stringify(response.errors);
|
|
2129
|
+
rejectFn(new DataConnectOperationError('DataConnect error while performing request: ' + stringified, failureResponse));
|
|
2130
|
+
}
|
|
2131
|
+
else {
|
|
2132
|
+
resolveFn(response);
|
|
2133
|
+
}
|
|
2134
|
+
}
|
|
2135
|
+
else if (this.subscribeObservers.has(requestId)) {
|
|
2136
|
+
const observer = this.subscribeObservers.get(requestId);
|
|
2137
|
+
await observer.onData(response);
|
|
2138
|
+
}
|
|
2139
|
+
else {
|
|
2140
|
+
throw new DataConnectError(Code.OTHER, `Stream response contained unrecognized requestId '${requestId}'`);
|
|
2141
|
+
}
|
|
1424
2142
|
}
|
|
2143
|
+
}
|
|
2144
|
+
|
|
2145
|
+
/**
|
|
2146
|
+
* @license
|
|
2147
|
+
* Copyright 2026 Google LLC
|
|
2148
|
+
*
|
|
2149
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
2150
|
+
* you may not use this file except in compliance with the License.
|
|
2151
|
+
* You may obtain a copy of the License at
|
|
2152
|
+
*
|
|
2153
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
2154
|
+
*
|
|
2155
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
2156
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
2157
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
2158
|
+
* See the License for the specific language governing permissions and
|
|
2159
|
+
* limitations under the License.
|
|
2160
|
+
*/
|
|
2161
|
+
/** The WebSocket implementation to be used by the {@link WebSocketTransport}. */
|
|
2162
|
+
let connectWebSocket = globalThis.WebSocket;
|
|
2163
|
+
/**
|
|
2164
|
+
* The code used to close the WebSocket connection.
|
|
2165
|
+
* This is a protocol-level code, and is not the same as the {@link Code | DataConnect error code}.
|
|
2166
|
+
* @internal
|
|
2167
|
+
*/
|
|
2168
|
+
const WEBSOCKET_CLOSE_CODE = 1000;
|
|
2169
|
+
/**
|
|
2170
|
+
* An {@link AbstractDataConnectStreamTransport | Stream Transport} implementation that uses {@link WebSocket | WebSockets} to stream requests and responses.
|
|
2171
|
+
* This class handles the lifecycle of the WebSocket connection, including automatic
|
|
2172
|
+
* reconnection and request correlation.
|
|
2173
|
+
* @internal
|
|
2174
|
+
*/
|
|
2175
|
+
class WebSocketTransport extends AbstractDataConnectStreamTransport {
|
|
1425
2176
|
get endpointUrl() {
|
|
1426
|
-
return
|
|
2177
|
+
return websocketUrlBuilder({
|
|
1427
2178
|
connector: this._connectorName,
|
|
1428
2179
|
location: this._location,
|
|
1429
2180
|
projectId: this._project,
|
|
1430
2181
|
service: this._serviceName
|
|
1431
|
-
}, {
|
|
2182
|
+
}, {
|
|
2183
|
+
host: this._host,
|
|
2184
|
+
sslEnabled: this._secure,
|
|
2185
|
+
port: this._port
|
|
2186
|
+
});
|
|
1432
2187
|
}
|
|
1433
|
-
|
|
1434
|
-
|
|
1435
|
-
|
|
1436
|
-
|
|
1437
|
-
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
this._secure = isSecure;
|
|
2188
|
+
/**
|
|
2189
|
+
* Decodes a WebSocket response from a Uint8Array to a JSON object.
|
|
2190
|
+
* Emulator does not send messages as Uint8Arrays, but prod does.
|
|
2191
|
+
*/
|
|
2192
|
+
decodeBinaryResponse(data) {
|
|
2193
|
+
if (!this.decoder) {
|
|
2194
|
+
this.decoder = new TextDecoder('utf-8');
|
|
1441
2195
|
}
|
|
2196
|
+
return this.decoder.decode(data);
|
|
1442
2197
|
}
|
|
1443
|
-
|
|
1444
|
-
this.
|
|
2198
|
+
get streamIsReady() {
|
|
2199
|
+
return this.connection?.readyState === WebSocket.OPEN;
|
|
1445
2200
|
}
|
|
1446
|
-
|
|
1447
|
-
|
|
1448
|
-
|
|
1449
|
-
|
|
1450
|
-
|
|
1451
|
-
|
|
2201
|
+
constructor(options, apiKey, appId, authProvider, appCheckProvider, transportOptions, _isUsingGen = false, _callerSdkType = CallerSdkTypeEnum.Base) {
|
|
2202
|
+
super(options, apiKey, appId, authProvider, appCheckProvider, transportOptions, _isUsingGen, _callerSdkType);
|
|
2203
|
+
this.apiKey = apiKey;
|
|
2204
|
+
this.appId = appId;
|
|
2205
|
+
this.authProvider = authProvider;
|
|
2206
|
+
this.appCheckProvider = appCheckProvider;
|
|
2207
|
+
this._isUsingGen = _isUsingGen;
|
|
2208
|
+
this._callerSdkType = _callerSdkType;
|
|
2209
|
+
/** Decodes binary WebSocket responses to strings */
|
|
2210
|
+
this.decoder = undefined;
|
|
2211
|
+
/** The current connection to the server. Undefined if disconnected. */
|
|
2212
|
+
this.connection = undefined;
|
|
2213
|
+
/**
|
|
2214
|
+
* Current connection attempt. If null, we are not currently attemping to connect (not connected,
|
|
2215
|
+
* or already connected). Will be resolved or rejected when the connection is opened or fails to open.
|
|
2216
|
+
*/
|
|
2217
|
+
this.connectionAttempt = null;
|
|
2218
|
+
}
|
|
2219
|
+
ensureConnection() {
|
|
2220
|
+
try {
|
|
2221
|
+
if (this.streamIsReady) {
|
|
2222
|
+
return Promise.resolve();
|
|
1452
2223
|
}
|
|
1453
|
-
|
|
1454
|
-
|
|
1455
|
-
|
|
1456
|
-
|
|
1457
|
-
|
|
1458
|
-
|
|
1459
|
-
return null;
|
|
2224
|
+
if (this.connectionAttempt) {
|
|
2225
|
+
return this.connectionAttempt;
|
|
2226
|
+
}
|
|
2227
|
+
this.connectionAttempt = new Promise((resolve, reject) => {
|
|
2228
|
+
if (!connectWebSocket) {
|
|
2229
|
+
throw new DataConnectError(Code.OTHER, 'No WebSocket Implementation detected!');
|
|
1460
2230
|
}
|
|
1461
|
-
|
|
1462
|
-
|
|
2231
|
+
const ws = new connectWebSocket(this.endpointUrl);
|
|
2232
|
+
this.connection = ws;
|
|
2233
|
+
this.connection.binaryType = 'arraybuffer';
|
|
2234
|
+
ws.onopen = () => {
|
|
2235
|
+
this.isUnableToConnect = false;
|
|
2236
|
+
this.onConnectionReady();
|
|
2237
|
+
resolve();
|
|
2238
|
+
};
|
|
2239
|
+
ws.onerror = event => {
|
|
2240
|
+
this.connectionAttempt = null;
|
|
2241
|
+
this.isUnableToConnect = true;
|
|
2242
|
+
const error = new DataConnectError(Code.OTHER, `Error using WebSocket connection, closing WebSocket`);
|
|
2243
|
+
this.handleError(error);
|
|
2244
|
+
reject(error);
|
|
2245
|
+
};
|
|
2246
|
+
ws.onmessage = ev => this.handleWebSocketMessage(ev).catch(async (reason) => {
|
|
2247
|
+
this.handleError(reason);
|
|
2248
|
+
});
|
|
2249
|
+
ws.onclose = ev => this.handleWebsocketDisconnect(ev);
|
|
1463
2250
|
});
|
|
2251
|
+
return this.connectionAttempt;
|
|
1464
2252
|
}
|
|
1465
|
-
|
|
1466
|
-
|
|
2253
|
+
catch (error) {
|
|
2254
|
+
this.handleError(error);
|
|
2255
|
+
throw error;
|
|
1467
2256
|
}
|
|
1468
|
-
return starterPromise;
|
|
1469
2257
|
}
|
|
1470
|
-
|
|
1471
|
-
this.
|
|
2258
|
+
openConnection() {
|
|
2259
|
+
return this.ensureConnection().catch(err => {
|
|
2260
|
+
throw new DataConnectError(Code.OTHER, `Failed to open connection: ${err}`);
|
|
2261
|
+
});
|
|
1472
2262
|
}
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
|
|
1476
|
-
.
|
|
1477
|
-
|
|
1478
|
-
|
|
1479
|
-
|
|
1480
|
-
|
|
1481
|
-
|
|
1482
|
-
|
|
1483
|
-
|
|
1484
|
-
|
|
1485
|
-
|
|
1486
|
-
|
|
1487
|
-
|
|
1488
|
-
|
|
1489
|
-
|
|
2263
|
+
closeConnection(code, reason) {
|
|
2264
|
+
if (!this.connection) {
|
|
2265
|
+
this.connectionAttempt = null;
|
|
2266
|
+
return Promise.resolve();
|
|
2267
|
+
}
|
|
2268
|
+
let error;
|
|
2269
|
+
try {
|
|
2270
|
+
if (reason) {
|
|
2271
|
+
// reason string can be max 123 bytes (not characters, bytes)
|
|
2272
|
+
// https://developer.mozilla.org/en-US/docs/Web/API/WebSocketStream/close#parameters
|
|
2273
|
+
const MAX_BYTES = 123;
|
|
2274
|
+
const encoder = new TextEncoder();
|
|
2275
|
+
const bytes = encoder.encode(reason);
|
|
2276
|
+
if (bytes.length <= MAX_BYTES) {
|
|
2277
|
+
this.connection.close(code, reason);
|
|
2278
|
+
}
|
|
2279
|
+
else {
|
|
2280
|
+
const buf = new Uint8Array(MAX_BYTES);
|
|
2281
|
+
const { read } = encoder.encodeInto(reason, buf);
|
|
2282
|
+
const truncatedReason = reason.substring(0, read);
|
|
2283
|
+
this.connection.close(code, truncatedReason);
|
|
2284
|
+
}
|
|
2285
|
+
}
|
|
2286
|
+
else {
|
|
2287
|
+
this.connection.close(code);
|
|
2288
|
+
}
|
|
2289
|
+
}
|
|
2290
|
+
catch (e) {
|
|
2291
|
+
error = e;
|
|
2292
|
+
}
|
|
2293
|
+
finally {
|
|
2294
|
+
this.connection = undefined;
|
|
2295
|
+
this.connectionAttempt = null;
|
|
2296
|
+
}
|
|
2297
|
+
if (error) {
|
|
2298
|
+
return Promise.reject(error);
|
|
2299
|
+
}
|
|
2300
|
+
return Promise.resolve();
|
|
2301
|
+
}
|
|
2302
|
+
/**
|
|
2303
|
+
* Handle a disconnection from the server. Initiates graceful clean up and reconnection attempts.
|
|
2304
|
+
* @param ev the {@link CloseEvent} that closed the WebSocket.
|
|
2305
|
+
*/
|
|
2306
|
+
handleWebsocketDisconnect(ev) {
|
|
2307
|
+
this.connection = undefined;
|
|
2308
|
+
this.connectionAttempt = null;
|
|
2309
|
+
this.onStreamClose(ev.code, ev.reason);
|
|
2310
|
+
}
|
|
2311
|
+
/**
|
|
2312
|
+
* Handle an error that occurred on the WebSocket. Close the connection and reject all active requests.
|
|
2313
|
+
*/
|
|
2314
|
+
handleError(error) {
|
|
2315
|
+
logError(`DataConnect WebSocket error, closing stream: ${error}`);
|
|
2316
|
+
let reason = error ? String(error) : 'Unknown Error';
|
|
2317
|
+
if (error instanceof DataConnectError) {
|
|
2318
|
+
reason = error.message;
|
|
2319
|
+
}
|
|
2320
|
+
void this.closeConnection(WEBSOCKET_CLOSE_CODE, reason);
|
|
2321
|
+
}
|
|
2322
|
+
sendMessage(requestBody) {
|
|
2323
|
+
return this.ensureConnection().then(() => {
|
|
2324
|
+
try {
|
|
2325
|
+
this.connection.send(JSON.stringify(requestBody));
|
|
2326
|
+
return Promise.resolve();
|
|
2327
|
+
}
|
|
2328
|
+
catch (err) {
|
|
2329
|
+
this.handleError(err);
|
|
2330
|
+
throw new DataConnectError(Code.OTHER, `Failed to send message: ${String(err)}`);
|
|
1490
2331
|
}
|
|
1491
|
-
throw err;
|
|
1492
2332
|
});
|
|
1493
2333
|
}
|
|
2334
|
+
/**
|
|
2335
|
+
* Handles incoming WebSocket messages.
|
|
2336
|
+
* @param ev The {@link MessageEvent} from the WebSocket.
|
|
2337
|
+
*/
|
|
2338
|
+
async handleWebSocketMessage(ev) {
|
|
2339
|
+
const result = this.parseWebSocketData(ev.data);
|
|
2340
|
+
const requestId = result.requestId;
|
|
2341
|
+
const response = {
|
|
2342
|
+
data: result.data,
|
|
2343
|
+
errors: result.errors,
|
|
2344
|
+
extensions: result.extensions || { dataConnect: [] }
|
|
2345
|
+
};
|
|
2346
|
+
await this.handleResponse(requestId, response);
|
|
2347
|
+
}
|
|
2348
|
+
/**
|
|
2349
|
+
* Parse a response from the server. Assert that it has a {@link DataConnectStreamResponse.requestId | requestId}.
|
|
2350
|
+
* @param data the message from the server to be parsed
|
|
2351
|
+
* @returns the parsed message as a {@link DataConnectStreamResponse}
|
|
2352
|
+
* @throws {DataConnectError} if parsing fails or message is malformed.
|
|
2353
|
+
*/
|
|
2354
|
+
parseWebSocketData(
|
|
2355
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
2356
|
+
data) {
|
|
2357
|
+
const dataIsString = typeof data === 'string';
|
|
2358
|
+
/** raw websocket message */
|
|
2359
|
+
let webSocketMessage;
|
|
2360
|
+
/** object containing data, errors, and extensions */
|
|
2361
|
+
let result;
|
|
2362
|
+
try {
|
|
2363
|
+
if (dataIsString) {
|
|
2364
|
+
webSocketMessage = JSON.parse(data);
|
|
2365
|
+
}
|
|
2366
|
+
else {
|
|
2367
|
+
webSocketMessage = JSON.parse(this.decodeBinaryResponse(data));
|
|
2368
|
+
}
|
|
2369
|
+
}
|
|
2370
|
+
catch (err) {
|
|
2371
|
+
throw new DataConnectError(Code.OTHER, `Could not parse WebSocket message: ${err instanceof Error ? err.message : String(err)}`);
|
|
2372
|
+
}
|
|
2373
|
+
if (typeof webSocketMessage !== 'object' || webSocketMessage === null) {
|
|
2374
|
+
throw new DataConnectError(Code.OTHER, 'WebSocket message is not an object');
|
|
2375
|
+
}
|
|
2376
|
+
if (dataIsString) {
|
|
2377
|
+
if (!('result' in webSocketMessage)) {
|
|
2378
|
+
throw new DataConnectError(Code.OTHER, 'WebSocket message from emulator did not include result');
|
|
2379
|
+
}
|
|
2380
|
+
if (typeof webSocketMessage.result !== 'object' ||
|
|
2381
|
+
webSocketMessage.result === null) {
|
|
2382
|
+
throw new DataConnectError(Code.OTHER, 'WebSocket message result is not an object');
|
|
2383
|
+
}
|
|
2384
|
+
result = webSocketMessage.result;
|
|
2385
|
+
}
|
|
2386
|
+
else {
|
|
2387
|
+
result = webSocketMessage;
|
|
2388
|
+
}
|
|
2389
|
+
if (!('requestId' in result)) {
|
|
2390
|
+
throw new DataConnectError(Code.OTHER, 'WebSocket message did not include requestId');
|
|
2391
|
+
}
|
|
2392
|
+
return result;
|
|
2393
|
+
}
|
|
2394
|
+
}
|
|
2395
|
+
|
|
2396
|
+
/**
|
|
2397
|
+
* @license
|
|
2398
|
+
* Copyright 2026 Google LLC
|
|
2399
|
+
*
|
|
2400
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
2401
|
+
* you may not use this file except in compliance with the License.
|
|
2402
|
+
* You may obtain a copy of the License at
|
|
2403
|
+
*
|
|
2404
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
2405
|
+
*
|
|
2406
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
2407
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
2408
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
2409
|
+
* See the License for the specific language governing permissions and
|
|
2410
|
+
* limitations under the License.
|
|
2411
|
+
*/
|
|
2412
|
+
/**
|
|
2413
|
+
* Entry point for the transport layer. Manages routing between transport implementations.
|
|
2414
|
+
* @internal
|
|
2415
|
+
*/
|
|
2416
|
+
class DataConnectTransportManager {
|
|
2417
|
+
constructor(options, apiKey, appId, authProvider, appCheckProvider, transportOptions, _isUsingGen = false, _callerSdkType) {
|
|
2418
|
+
this.options = options;
|
|
2419
|
+
this.apiKey = apiKey;
|
|
2420
|
+
this.appId = appId;
|
|
2421
|
+
this.authProvider = authProvider;
|
|
2422
|
+
this.appCheckProvider = appCheckProvider;
|
|
2423
|
+
this.transportOptions = transportOptions;
|
|
2424
|
+
this._isUsingGen = _isUsingGen;
|
|
2425
|
+
this._callerSdkType = _callerSdkType;
|
|
2426
|
+
this.isUsingEmulator = false;
|
|
2427
|
+
this.restTransport = new RESTTransport(options, apiKey, appId, authProvider, appCheckProvider, transportOptions, _isUsingGen, _callerSdkType);
|
|
2428
|
+
}
|
|
2429
|
+
/**
|
|
2430
|
+
* Initializes the stream transport if it hasn't been already.
|
|
2431
|
+
*/
|
|
2432
|
+
initStreamTransport() {
|
|
2433
|
+
if (!this.streamTransport) {
|
|
2434
|
+
this.streamTransport = new WebSocketTransport(this.options, this.apiKey, this.appId, this.authProvider, this.appCheckProvider, this.transportOptions, this._isUsingGen, this._callerSdkType);
|
|
2435
|
+
if (this.isUsingEmulator && this.transportOptions) {
|
|
2436
|
+
this.streamTransport.useEmulator(this.transportOptions.host, this.transportOptions.port, this.transportOptions.sslEnabled);
|
|
2437
|
+
}
|
|
2438
|
+
this.streamTransport.onGracefulStreamClose = () => {
|
|
2439
|
+
this.streamTransport = undefined;
|
|
2440
|
+
};
|
|
2441
|
+
}
|
|
2442
|
+
return this.streamTransport;
|
|
2443
|
+
}
|
|
2444
|
+
/**
|
|
2445
|
+
* Returns true if the stream is in a healthy, ready connection state and has active subscriptions.
|
|
2446
|
+
*/
|
|
2447
|
+
executeShouldUseStream() {
|
|
2448
|
+
return (!!this.streamTransport &&
|
|
2449
|
+
!this.streamTransport.isPendingClose &&
|
|
2450
|
+
this.streamTransport.streamIsReady &&
|
|
2451
|
+
this.streamTransport.hasActiveSubscriptions &&
|
|
2452
|
+
!this.streamTransport.isUnableToConnect);
|
|
2453
|
+
}
|
|
2454
|
+
/**
|
|
2455
|
+
* Prefer to use Streaming Transport connection when one is available.
|
|
2456
|
+
* @inheritdoc
|
|
2457
|
+
*/
|
|
2458
|
+
invokeQuery(queryName, body) {
|
|
2459
|
+
if (this.executeShouldUseStream()) {
|
|
2460
|
+
return this.streamTransport.invokeQuery(queryName, body).catch(err => {
|
|
2461
|
+
if (this.executeShouldUseStream()) {
|
|
2462
|
+
throw err;
|
|
2463
|
+
}
|
|
2464
|
+
return this.restTransport.invokeQuery(queryName, body);
|
|
2465
|
+
});
|
|
2466
|
+
}
|
|
2467
|
+
return this.restTransport.invokeQuery(queryName, body);
|
|
2468
|
+
}
|
|
2469
|
+
/**
|
|
2470
|
+
* Prefer to use Streaming Transport connection when one is available.
|
|
2471
|
+
* @inheritdoc
|
|
2472
|
+
*/
|
|
2473
|
+
invokeMutation(queryName, body) {
|
|
2474
|
+
if (this.executeShouldUseStream()) {
|
|
2475
|
+
return this.streamTransport.invokeMutation(queryName, body).catch(err => {
|
|
2476
|
+
if (this.executeShouldUseStream()) {
|
|
2477
|
+
throw err;
|
|
2478
|
+
}
|
|
2479
|
+
return this.restTransport.invokeMutation(queryName, body);
|
|
2480
|
+
});
|
|
2481
|
+
}
|
|
2482
|
+
return this.restTransport.invokeMutation(queryName, body);
|
|
2483
|
+
}
|
|
2484
|
+
invokeSubscribe(observer, queryName, body) {
|
|
2485
|
+
const streamTransport = this.initStreamTransport();
|
|
2486
|
+
if (streamTransport.isUnableToConnect) {
|
|
2487
|
+
throw new DataConnectError(Code.OTHER, 'Unable to connect streaming connection to server. Subscriptions are unavailable.');
|
|
2488
|
+
}
|
|
2489
|
+
streamTransport.invokeSubscribe(observer, queryName, body);
|
|
2490
|
+
}
|
|
2491
|
+
invokeUnsubscribe(queryName, body) {
|
|
2492
|
+
if (this.streamTransport) {
|
|
2493
|
+
this.streamTransport.invokeUnsubscribe(queryName, body);
|
|
2494
|
+
}
|
|
2495
|
+
}
|
|
2496
|
+
useEmulator(host, port, sslEnabled) {
|
|
2497
|
+
this.isUsingEmulator = true;
|
|
2498
|
+
this.transportOptions = { host, port, sslEnabled };
|
|
2499
|
+
this.restTransport.useEmulator(host, port, sslEnabled);
|
|
2500
|
+
if (this.streamTransport) {
|
|
2501
|
+
this.streamTransport.useEmulator(host, port, sslEnabled);
|
|
2502
|
+
}
|
|
2503
|
+
}
|
|
2504
|
+
onAuthTokenChanged(token) {
|
|
2505
|
+
this.restTransport.onAuthTokenChanged(token);
|
|
2506
|
+
if (this.streamTransport) {
|
|
2507
|
+
this.streamTransport.onAuthTokenChanged(token);
|
|
2508
|
+
}
|
|
2509
|
+
}
|
|
1494
2510
|
_setCallerSdkType(callerSdkType) {
|
|
1495
2511
|
this._callerSdkType = callerSdkType;
|
|
2512
|
+
this.restTransport._setCallerSdkType(callerSdkType);
|
|
2513
|
+
if (this.streamTransport) {
|
|
2514
|
+
this.streamTransport._setCallerSdkType(callerSdkType);
|
|
2515
|
+
}
|
|
1496
2516
|
}
|
|
1497
2517
|
}
|
|
1498
2518
|
|
|
@@ -1658,8 +2678,8 @@ class DataConnect {
|
|
|
1658
2678
|
return;
|
|
1659
2679
|
}
|
|
1660
2680
|
if (this._transportClass === undefined) {
|
|
1661
|
-
logDebug('transportClass not provided. Defaulting to
|
|
1662
|
-
this._transportClass =
|
|
2681
|
+
logDebug('transportClass not provided. Defaulting to DataConnectTransportManager.');
|
|
2682
|
+
this._transportClass = DataConnectTransportManager;
|
|
1663
2683
|
}
|
|
1664
2684
|
this._authTokenProvider = new FirebaseAuthProvider(this.app.name, this.app.options, this._authProvider);
|
|
1665
2685
|
const connectorConfig = {
|
|
@@ -2092,6 +3112,7 @@ function subscribe(queryRefOrSerializedResult, observerOrOnNext, onError, onComp
|
|
|
2092
3112
|
*/
|
|
2093
3113
|
registerDataConnect();
|
|
2094
3114
|
|
|
3115
|
+
exports.AbstractDataConnectTransport = AbstractDataConnectTransport;
|
|
2095
3116
|
exports.CallerSdkTypeEnum = CallerSdkTypeEnum;
|
|
2096
3117
|
exports.Code = Code;
|
|
2097
3118
|
exports.DataConnect = DataConnect;
|
|
@@ -2109,6 +3130,7 @@ exports.connectDataConnectEmulator = connectDataConnectEmulator;
|
|
|
2109
3130
|
exports.executeMutation = executeMutation;
|
|
2110
3131
|
exports.executeQuery = executeQuery;
|
|
2111
3132
|
exports.getDataConnect = getDataConnect;
|
|
3133
|
+
exports.getGoogApiClientValue = getGoogApiClientValue$1;
|
|
2112
3134
|
exports.makeMemoryCacheProvider = makeMemoryCacheProvider;
|
|
2113
3135
|
exports.mutationRef = mutationRef;
|
|
2114
3136
|
exports.parseOptions = parseOptions;
|