@interopio/browser 4.1.2 → 4.1.4

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.
@@ -7738,7 +7738,7 @@ class IoC {
7738
7738
  }
7739
7739
  }
7740
7740
 
7741
- var version$1 = "4.1.2";
7741
+ var version$1 = "4.1.4";
7742
7742
 
7743
7743
  const setupGlobalSystem = (io, bridge) => {
7744
7744
  return {
@@ -8025,7 +8025,10 @@ function gw3 (connection, config) {
8025
8025
  type: "define",
8026
8026
  metrics: [rootStateMetric],
8027
8027
  };
8028
- session.send(defineRootMetricsMsg);
8028
+ session.sendFireAndForget(defineRootMetricsMsg)
8029
+ .catch((err) => {
8030
+ config.logger.warn(`Failed to send define for root state metric: ${JSON.stringify(err)}`);
8031
+ });
8029
8032
  if (reconnect) {
8030
8033
  replayRepo(repo);
8031
8034
  }
@@ -8073,7 +8076,10 @@ function gw3 (connection, config) {
8073
8076
  type: "define",
8074
8077
  metrics: [metric],
8075
8078
  };
8076
- session.send(createMetricsMsg);
8079
+ session.sendFireAndForget(createMetricsMsg)
8080
+ .catch((err) => {
8081
+ config.logger.warn(`Failed to send define for system state metric of ${system.name}: ${JSON.stringify(err)}`);
8082
+ });
8077
8083
  };
8078
8084
  const updateSystem = async (system, state) => {
8079
8085
  await joinPromise;
@@ -8088,7 +8094,10 @@ function gw3 (connection, config) {
8088
8094
  timestamp: Date.now(),
8089
8095
  }],
8090
8096
  };
8091
- session.send(shadowedUpdateMetric);
8097
+ session.sendFireAndForget(shadowedUpdateMetric)
8098
+ .catch((err) => {
8099
+ config.logger.warn(`Failed to send update for system state metric of ${system.name}: ${JSON.stringify(err)}`);
8100
+ });
8092
8101
  const stateObj = composeMsgForRootStateMetric(system);
8093
8102
  const rootMetric = {
8094
8103
  type: "publish",
@@ -8102,7 +8111,10 @@ function gw3 (connection, config) {
8102
8111
  timestamp: Date.now(),
8103
8112
  }],
8104
8113
  };
8105
- session.send(rootMetric);
8114
+ session.sendFireAndForget(rootMetric)
8115
+ .catch((err) => {
8116
+ config.logger.warn(`Failed to send update for root state metric of ${system.name}: ${JSON.stringify(err)}`);
8117
+ });
8106
8118
  };
8107
8119
  const createMetric = async (metric) => {
8108
8120
  const metricClone = cloneMetric(metric);
@@ -8112,7 +8124,10 @@ function gw3 (connection, config) {
8112
8124
  type: "define",
8113
8125
  metrics: [m],
8114
8126
  };
8115
- session.send(createMetricsMsg);
8127
+ session.sendFireAndForget(createMetricsMsg)
8128
+ .catch((err) => {
8129
+ config.logger.warn(`Failed to send define for metric ${metric.name}: ${JSON.stringify(err)}`);
8130
+ });
8116
8131
  if (typeof metricClone.value !== "undefined") {
8117
8132
  updateMetricCore(metricClone);
8118
8133
  }
@@ -8133,7 +8148,10 @@ function gw3 (connection, config) {
8133
8148
  timestamp: Date.now(),
8134
8149
  }],
8135
8150
  };
8136
- return session.sendFireAndForget(publishMetricsMsg);
8151
+ return session.sendFireAndForget(publishMetricsMsg)
8152
+ .catch((err) => {
8153
+ config.logger.warn(`Failed to publish metric ${metric.name}: ${JSON.stringify(err)}`);
8154
+ });
8137
8155
  }
8138
8156
  return Promise.resolve();
8139
8157
  };
@@ -9000,8 +9018,9 @@ class WS {
9000
9018
  const pw = new PromiseWrapper();
9001
9019
  this.logger.debug(`initiating ws to ${this.settings.ws}...`);
9002
9020
  this.ws = new WebSocketConstructor(this.settings.ws ?? "");
9021
+ let wasOpen = false;
9003
9022
  this.ws.onerror = (err) => {
9004
- let reason = "";
9023
+ let reason;
9005
9024
  try {
9006
9025
  reason = JSON.stringify(err);
9007
9026
  }
@@ -9020,17 +9039,26 @@ class WS {
9020
9039
  }
9021
9040
  this.logger.info(`ws error - reason: ${reason}`);
9022
9041
  pw.reject("error");
9042
+ if (wasOpen) {
9043
+ wasOpen = false;
9044
+ this.notifyForSocketState("error");
9045
+ }
9023
9046
  this.notifyStatusChanged(false, reason);
9024
9047
  };
9025
9048
  this.ws.onclose = (err) => {
9026
9049
  this.logger.info(`ws closed - code: ${err?.code} reason: ${err?.reason}`);
9027
9050
  pw.reject("closed");
9051
+ if (wasOpen) {
9052
+ wasOpen = false;
9053
+ this.notifyForSocketState("closed");
9054
+ }
9028
9055
  this.notifyStatusChanged(false);
9029
9056
  };
9030
9057
  this.ws.onopen = () => {
9031
9058
  this.startupTimer.mark("ws-opened");
9032
9059
  this.logger.info(`ws opened ${this.settings.identity?.application}`);
9033
9060
  pw.resolve();
9061
+ wasOpen = true;
9034
9062
  this.notifyStatusChanged(true);
9035
9063
  };
9036
9064
  this.ws.onmessage = (message) => {
@@ -9818,17 +9846,31 @@ function domainSession (domain, connection, logger, successMessages, errorMessag
9818
9846
  callbacks.execute("onJoined", wasReconnect);
9819
9847
  }
9820
9848
  function handleConnectionDisconnected() {
9821
- _connectionOn = false;
9822
9849
  logger.debug("connection is down");
9850
+ _connectionOn = false;
9823
9851
  isJoined = false;
9824
9852
  tryReconnecting = true;
9853
+ Object.keys(requestsMap).forEach(requestId => {
9854
+ const request = requestsMap[requestId];
9855
+ if (request) {
9856
+ logger.trace(`failing pending request ${requestId} due to connection lost`);
9857
+ request.error({
9858
+ err: "Connection lost - gateway connection was disconnected"
9859
+ });
9860
+ }
9861
+ });
9825
9862
  callbacks.execute("onLeft", { disconnected: true });
9826
9863
  }
9827
- function handleConnectionLoggedIn() {
9864
+ async function handleConnectionLoggedIn() {
9828
9865
  _connectionOn = true;
9829
9866
  if (tryReconnecting) {
9830
9867
  logger.debug("connection is now up - trying to reconnect...");
9831
- join(_latestOptions);
9868
+ try {
9869
+ await join(_latestOptions);
9870
+ }
9871
+ catch {
9872
+ logger.trace(`failed to reconnect`);
9873
+ }
9832
9874
  }
9833
9875
  }
9834
9876
  function onJoined(callback) {
@@ -9921,7 +9963,7 @@ function domainSession (domain, connection, logger, successMessages, errorMessag
9921
9963
  connection
9922
9964
  .send(msg, options)
9923
9965
  .catch((err) => {
9924
- requestsMap[requestId].error({ err });
9966
+ requestsMap[requestId]?.error({ err });
9925
9967
  });
9926
9968
  });
9927
9969
  }
@@ -10000,6 +10042,7 @@ class Connection {
10000
10042
  initialLogin = true;
10001
10043
  initialLoginAttempts = 3;
10002
10044
  loginConfig;
10045
+ loginRetryInProgress = false;
10003
10046
  constructor(settings, logger) {
10004
10047
  this.settings = settings;
10005
10048
  this.logger = logger;
@@ -10113,6 +10156,7 @@ class Connection {
10113
10156
  return this.registry.add("disconnected", callback);
10114
10157
  }
10115
10158
  async login(authRequest, reconnect) {
10159
+ this.logger.debug(`Login initiated - reconnect: ${reconnect}, transport: ${this.transport.name()}`);
10116
10160
  if (!this._defaultAuth) {
10117
10161
  this._defaultAuth = authRequest;
10118
10162
  }
@@ -10121,19 +10165,18 @@ class Connection {
10121
10165
  const newAuth = this.transportSwap();
10122
10166
  authRequest = newAuth ?? authRequest;
10123
10167
  }
10124
- this.logger.trace(`Starting login for transport: ${this.transport.name()} and auth ${JSON.stringify(authRequest)}`);
10125
10168
  try {
10126
10169
  await this.transport.open();
10127
- this.logger.trace(`Transport: ${this.transport.name()} opened, logging in`);
10170
+ this.logger.debug(`Transport: ${this.transport.name()} opened, logging in`);
10128
10171
  timer("connection").mark("transport-opened");
10129
10172
  const identity = await this.loginCore(authRequest, reconnect);
10130
- this.logger.trace(`Logged in with identity: ${JSON.stringify(identity)}`);
10173
+ this.logger.debug(`Logged in with identity: ${JSON.stringify(identity)}`);
10131
10174
  timer("connection").mark("protocol-logged-in");
10132
10175
  return identity;
10133
10176
  }
10134
10177
  catch (error) {
10135
10178
  if (this._switchInProgress) {
10136
- this.logger.trace("An error while logging in after a transport swap, preparing a default swap.");
10179
+ this.logger.debug("An error while logging in after a transport swap, preparing a default swap.");
10137
10180
  this.prepareDefaultSwap();
10138
10181
  }
10139
10182
  throw new Error(error);
@@ -10176,6 +10219,7 @@ class Connection {
10176
10219
  setLoggedIn(value) {
10177
10220
  this._isLoggedIn = value;
10178
10221
  if (this._isLoggedIn) {
10222
+ this.initialLogin = false;
10179
10223
  this.registry.execute("onLoggedIn");
10180
10224
  }
10181
10225
  }
@@ -10202,8 +10246,10 @@ class Connection {
10202
10246
  }
10203
10247
  handleConnectionChanged(connected) {
10204
10248
  if (this._connected === connected) {
10249
+ this.logger.trace("connection state unchanged, skipping");
10205
10250
  return;
10206
10251
  }
10252
+ this.logger.info(`connection state changed to ${connected ? "connected" : "disconnected"}`);
10207
10253
  this._connected = connected;
10208
10254
  if (connected) {
10209
10255
  if (this.settings?.replaySpecs?.length) {
@@ -10213,28 +10259,44 @@ class Connection {
10213
10259
  this.registry.execute("connected");
10214
10260
  }
10215
10261
  else {
10216
- this.handleDisconnected();
10262
+ this.setLoggedIn(false);
10263
+ if (this.shouldTryLogin) {
10264
+ this.attemptLoginWithRetry();
10265
+ }
10217
10266
  this.registry.execute("disconnected");
10218
10267
  }
10219
10268
  }
10220
- handleDisconnected() {
10221
- this.setLoggedIn(false);
10222
- const tryToLogin = this.shouldTryLogin;
10223
- if (tryToLogin && this.initialLogin) {
10269
+ async attemptLoginWithRetry() {
10270
+ if (!this.loginConfig) {
10271
+ throw new Error("no login info");
10272
+ }
10273
+ if (this.loginRetryInProgress) {
10274
+ this.logger.debug("login attempt already in progress, ignoring request...");
10275
+ return;
10276
+ }
10277
+ if (this._isLoggedIn) {
10278
+ this.logger.debug("already logged in, ignoring request...");
10279
+ return;
10280
+ }
10281
+ if (this.initialLogin) {
10282
+ this.logger.debug(`initial login attempt failed, ${this.initialLoginAttempts} attempts remaining...`);
10224
10283
  if (this.initialLoginAttempts <= 0) {
10284
+ this.logger.info("maximum initial login attempts reached, will not try to login again");
10225
10285
  return;
10226
10286
  }
10227
10287
  this.initialLoginAttempts--;
10228
10288
  }
10229
- this.logger.debug("disconnected - will try new login?" + this.shouldTryLogin);
10230
- if (this.shouldTryLogin) {
10231
- if (!this.loginConfig) {
10232
- throw new Error("no login info");
10233
- }
10234
- this.login(this.loginConfig, true)
10235
- .catch(() => {
10236
- setTimeout(this.handleDisconnected.bind(this), this.settings.reconnectInterval || 1000);
10237
- });
10289
+ try {
10290
+ this.logger.debug(`will try a new login... ${this.loginRetryInProgress}`);
10291
+ this.loginRetryInProgress = true;
10292
+ await this.login(this.loginConfig, true);
10293
+ }
10294
+ catch (e) {
10295
+ this.logger.error(`error trying to login: ${e?.message}`, e);
10296
+ setTimeout(this.attemptLoginWithRetry.bind(this), this.settings.reconnectInterval ?? 1000);
10297
+ }
10298
+ finally {
10299
+ this.loginRetryInProgress = false;
10238
10300
  }
10239
10301
  }
10240
10302
  handleTransportMessage(msg) {
@@ -10361,7 +10423,6 @@ class Connection {
10361
10423
  return message;
10362
10424
  }
10363
10425
  async loginCore(config, reconnect) {
10364
- this.logger.info("logging in...");
10365
10426
  this.loginConfig = config;
10366
10427
  if (!this.loginConfig) {
10367
10428
  this.loginConfig = { username: "", password: "" };
@@ -10376,11 +10437,13 @@ class Connection {
10376
10437
  if (config.sessionId) {
10377
10438
  helloMsg.request_id = config.sessionId;
10378
10439
  }
10379
- this.globalDomain = domainSession("global", this, this.logger.subLogger("global-domain"), [
10380
- "welcome",
10381
- "token",
10382
- "authentication-request"
10383
- ]);
10440
+ if (!this.globalDomain) {
10441
+ this.globalDomain = domainSession("global", this, this.logger.subLogger("global-domain"), [
10442
+ "welcome",
10443
+ "token",
10444
+ "authentication-request"
10445
+ ]);
10446
+ }
10384
10447
  const sendOptions = { skipPeerId: true };
10385
10448
  if (this.initialLogin) {
10386
10449
  sendOptions.retryInterval = this.settings.reconnectInterval;
@@ -10388,7 +10451,6 @@ class Connection {
10388
10451
  }
10389
10452
  try {
10390
10453
  const welcomeMsg = await this.tryAuthenticate(this.globalDomain, helloMsg, sendOptions, config);
10391
- this.initialLogin = false;
10392
10454
  this.logger.info("login successful with peerId " + welcomeMsg.peer_id);
10393
10455
  this.peerId = welcomeMsg.peer_id;
10394
10456
  this.resolvedIdentity = welcomeMsg.resolved_identity;
@@ -10491,7 +10553,7 @@ class Connection {
10491
10553
  clearTimeout(this.pingTimer);
10492
10554
  }
10493
10555
  const promises = this.sessions.map((session) => {
10494
- session.leave();
10556
+ return session.leave();
10495
10557
  });
10496
10558
  await Promise.all(promises);
10497
10559
  }
@@ -10716,7 +10778,7 @@ const ContextMessageReplaySpec = {
10716
10778
  }
10717
10779
  };
10718
10780
 
10719
- var version = "6.7.0";
10781
+ var version = "6.7.2";
10720
10782
 
10721
10783
  function prepareConfig (configuration, ext, glue42gd) {
10722
10784
  let nodeStartingContext;
@@ -10811,14 +10873,20 @@ function prepareConfig (configuration, ext, glue42gd) {
10811
10873
  };
10812
10874
  }
10813
10875
  function getContexts() {
10876
+ const defaultConfig = {
10877
+ reAnnounceKnownContexts: true,
10878
+ subscribeOnUpdate: true,
10879
+ subscribeOnGet: true,
10880
+ onlyReAnnounceSubscribedContexts: true
10881
+ };
10814
10882
  if (typeof configuration.contexts === "undefined") {
10815
- return { reAnnounceKnownContexts: true };
10883
+ return defaultConfig;
10816
10884
  }
10817
10885
  if (typeof configuration.contexts === "boolean" && configuration.contexts) {
10818
- return { reAnnounceKnownContexts: true };
10886
+ return defaultConfig;
10819
10887
  }
10820
10888
  if (typeof configuration.contexts === "object") {
10821
- return Object.assign({}, { reAnnounceKnownContexts: true }, configuration.contexts);
10889
+ return { ...defaultConfig, ...configuration.contexts };
10822
10890
  }
10823
10891
  return false;
10824
10892
  }
@@ -10917,13 +10985,28 @@ class GW3ContextData {
10917
10985
  updateCallbacks = {};
10918
10986
  activityId;
10919
10987
  sentExplicitSubscription;
10920
- hasReceivedSnapshot;
10988
+ get hasReceivedSnapshot() {
10989
+ return this.snapshotPromiseWrapper.resolved;
10990
+ }
10991
+ set hasReceivedSnapshot(has) {
10992
+ if (has) {
10993
+ this.snapshotPromiseWrapper.resolve();
10994
+ }
10995
+ else {
10996
+ this.snapshotPromiseWrapper = new PromiseWrapper();
10997
+ }
10998
+ }
10999
+ get snapshotPromise() {
11000
+ return this.snapshotPromiseWrapper.promise;
11001
+ }
11002
+ snapshotPromiseWrapper;
10921
11003
  constructor(contextId, name, isAnnounced, activityId) {
10922
11004
  this.contextId = contextId;
10923
11005
  this.name = name;
10924
11006
  this.isAnnounced = isAnnounced;
10925
11007
  this.activityId = activityId;
10926
11008
  this.context = {};
11009
+ this.snapshotPromiseWrapper = new PromiseWrapper();
10927
11010
  }
10928
11011
  hasCallbacks() {
10929
11012
  return Object.keys(this.updateCallbacks).length > 0;
@@ -12843,10 +12926,15 @@ function deletePath(obj, path) {
12843
12926
  }
12844
12927
 
12845
12928
  class GW3Bridge {
12929
+ ERROR_URI_FAILURE = "global.errors.failure";
12930
+ ERROR_URI_INVALID_CONTEXT = "global.errors.invalid_context";
12846
12931
  _logger;
12847
12932
  _connection;
12848
12933
  _trackAllContexts;
12849
12934
  _reAnnounceKnownContexts;
12935
+ _subscribeOnUpdate;
12936
+ _subscribeOnGet;
12937
+ _onlyReAnnounceSubscribedContexts;
12850
12938
  _gw3Session;
12851
12939
  _contextNameToData = {};
12852
12940
  _gw3Subscriptions = [];
@@ -12873,6 +12961,9 @@ class GW3Bridge {
12873
12961
  this._logger = config.logger;
12874
12962
  this._trackAllContexts = config.trackAllContexts;
12875
12963
  this._reAnnounceKnownContexts = config.reAnnounceKnownContexts;
12964
+ this._subscribeOnUpdate = config.subscribeOnUpdate ?? true;
12965
+ this._subscribeOnGet = config.subscribeOnGet ?? true;
12966
+ this._onlyReAnnounceSubscribedContexts = config.onlyReAnnounceSubscribedContexts ?? true;
12876
12967
  this._gw3Session = this._connection.domain("global", [
12877
12968
  GW_MESSAGE_CONTEXT_CREATED,
12878
12969
  GW_MESSAGE_SUBSCRIBED_CONTEXT,
@@ -12885,9 +12976,14 @@ class GW3Bridge {
12885
12976
  return;
12886
12977
  }
12887
12978
  if (!this._reAnnounceKnownContexts) {
12979
+ this._contextsTempCache = {};
12888
12980
  return this._connection.setLibReAnnounced({ name: "contexts" });
12889
12981
  }
12890
- this.reInitiateState().then(() => this._connection.setLibReAnnounced({ name: "contexts" }));
12982
+ this.reInitiateState()
12983
+ .then(() => this._connection.setLibReAnnounced({ name: "contexts" }))
12984
+ .catch((err) => {
12985
+ this._logger.warn(`Error while re-announcing contexts: ${JSON.stringify(err)}`);
12986
+ });
12891
12987
  });
12892
12988
  this.subscribeToContextCreatedMessages();
12893
12989
  this.subscribeToContextUpdatedMessages();
@@ -12965,10 +13061,11 @@ class GW3Bridge {
12965
13061
  }
12966
13062
  const contextData = this._contextNameToData[name];
12967
13063
  if (!contextData || !contextData.isAnnounced) {
12968
- return this.createContext(name, delta);
13064
+ await this.createContext(name, delta);
13065
+ return;
12969
13066
  }
12970
13067
  let currentContext = contextData.context;
12971
- if (!contextData.hasCallbacks()) {
13068
+ if (!contextData.hasReceivedSnapshot) {
12972
13069
  currentContext = await this.get(contextData.name);
12973
13070
  }
12974
13071
  const calculatedDelta = this.setPathSupported ?
@@ -12980,18 +13077,25 @@ class GW3Bridge {
12980
13077
  && !calculatedDelta.commands?.length) {
12981
13078
  return Promise.resolve();
12982
13079
  }
12983
- return this._gw3Session
13080
+ const gwResponse = await this._gw3Session
12984
13081
  .send({
12985
13082
  type: GW_MESSAGE_UPDATE_CONTEXT,
12986
13083
  domain: "global",
12987
13084
  context_id: contextData.contextId,
12988
13085
  delta: calculatedDelta,
12989
- }, {}, { skipPeerId: false })
12990
- .then((gwResponse) => {
13086
+ }, {}, { skipPeerId: false });
13087
+ if (this._subscribeOnUpdate &&
13088
+ !contextData.sentExplicitSubscription &&
13089
+ !contextData.activityId) {
13090
+ this.subscribe(name, () => { });
13091
+ }
13092
+ if (contextData.sentExplicitSubscription ||
13093
+ contextData.activityId) {
13094
+ await contextData.snapshotPromise;
12991
13095
  this.handleUpdated(contextData, calculatedDelta, {
12992
13096
  updaterId: gwResponse.peer_id
12993
13097
  });
12994
- });
13098
+ }
12995
13099
  }
12996
13100
  async set(name, data) {
12997
13101
  if (data) {
@@ -13004,7 +13108,7 @@ class GW3Bridge {
13004
13108
  if (!contextData || !contextData.isAnnounced) {
13005
13109
  return this.createContext(name, data);
13006
13110
  }
13007
- return this._gw3Session
13111
+ await this._gw3Session
13008
13112
  .send({
13009
13113
  type: GW_MESSAGE_UPDATE_CONTEXT,
13010
13114
  domain: "global",
@@ -13055,14 +13159,21 @@ class GW3Bridge {
13055
13159
  commands.push({ type: "set", path: pathValue.path, value: pathValue.value });
13056
13160
  }
13057
13161
  }
13058
- return this._gw3Session
13162
+ const gwResponse = await this._gw3Session
13059
13163
  .send({
13060
13164
  type: GW_MESSAGE_UPDATE_CONTEXT,
13061
13165
  domain: "global",
13062
13166
  context_id: contextData.contextId,
13063
13167
  delta: { commands }
13064
- }, {}, { skipPeerId: false })
13065
- .then((gwResponse) => {
13168
+ }, {}, { skipPeerId: false });
13169
+ if (this._subscribeOnUpdate &&
13170
+ !contextData.sentExplicitSubscription &&
13171
+ !contextData.activityId) {
13172
+ this.subscribe(name, () => { });
13173
+ }
13174
+ if (contextData.sentExplicitSubscription ||
13175
+ contextData.activityId) {
13176
+ await contextData.snapshotPromise;
13066
13177
  this.handleUpdated(contextData, {
13067
13178
  added: {},
13068
13179
  removed: [],
@@ -13071,7 +13182,7 @@ class GW3Bridge {
13071
13182
  }, {
13072
13183
  updaterId: gwResponse.peer_id
13073
13184
  });
13074
- });
13185
+ }
13075
13186
  }
13076
13187
  async get(name) {
13077
13188
  if (name in this._creationPromises) {
@@ -13082,16 +13193,29 @@ class GW3Bridge {
13082
13193
  return Promise.resolve({});
13083
13194
  }
13084
13195
  if (contextData && (!contextData.hasCallbacks() || !contextData.hasReceivedSnapshot)) {
13085
- return new Promise((resolve) => {
13196
+ return new Promise((resolve, reject) => {
13086
13197
  this.subscribe(name, (data, _d, _r, un) => {
13087
- this.unsubscribe(un);
13198
+ if (!this._subscribeOnGet) {
13199
+ this.unsubscribe(un);
13200
+ }
13088
13201
  resolve(data);
13202
+ }).catch((e) => {
13203
+ if (this.isInvalidContextError(e)) {
13204
+ resolve({});
13205
+ return;
13206
+ }
13207
+ reject(e);
13089
13208
  });
13090
13209
  });
13091
13210
  }
13211
+ await contextData.snapshotPromise;
13092
13212
  const context = contextData?.context ?? {};
13093
13213
  return Promise.resolve(deepClone(context));
13094
13214
  }
13215
+ isInvalidContextError(e) {
13216
+ return e.reason_uri === this.ERROR_URI_INVALID_CONTEXT
13217
+ || (e.reason_uri === this.ERROR_URI_FAILURE && e.reason?.startsWith("Unable to find context with id"));
13218
+ }
13095
13219
  async subscribe(name, callback, subscriptionKey) {
13096
13220
  if (name in this._creationPromises) {
13097
13221
  await this._creationPromises[name];
@@ -13142,11 +13266,10 @@ class GW3Bridge {
13142
13266
  }
13143
13267
  }
13144
13268
  unsubscribe(subscriptionKey) {
13145
- this._contextsSubscriptionsCache = this._contextsSubscriptionsCache.filter((subscription) => subscription.subKey !== subscriptionKey);
13146
13269
  for (const name of Object.keys(this._contextNameToData)) {
13147
13270
  const contextData = this._contextNameToData[name];
13148
13271
  if (!contextData) {
13149
- return;
13272
+ continue;
13150
13273
  }
13151
13274
  const hadCallbacks = contextData.hasCallbacks();
13152
13275
  delete contextData.updateCallbacks[subscriptionKey];
@@ -13154,11 +13277,17 @@ class GW3Bridge {
13154
13277
  hadCallbacks &&
13155
13278
  !contextData.hasCallbacks() &&
13156
13279
  contextData.sentExplicitSubscription) {
13280
+ contextData.hasReceivedSnapshot = false;
13281
+ contextData.context = {};
13157
13282
  this.sendUnsubscribe(contextData).catch(() => { });
13158
13283
  }
13159
13284
  if (!contextData.isAnnounced &&
13160
13285
  !contextData.hasCallbacks()) {
13161
13286
  delete this._contextNameToData[name];
13287
+ delete this._contextNameToId[name];
13288
+ if (contextData.contextId) {
13289
+ delete this._contextIdToName[contextData.contextId];
13290
+ }
13162
13291
  }
13163
13292
  }
13164
13293
  }
@@ -13167,7 +13296,8 @@ class GW3Bridge {
13167
13296
  await this._creationPromises[name];
13168
13297
  }
13169
13298
  const contextData = this._contextNameToData[name];
13170
- if (!contextData) {
13299
+ const contextId = contextData?.contextId;
13300
+ if (!contextData || !contextId) {
13171
13301
  return Promise.reject(`context with ${name} does not exist`);
13172
13302
  }
13173
13303
  return this._gw3Session
@@ -13175,7 +13305,7 @@ class GW3Bridge {
13175
13305
  type: GW_MESSAGE_DESTROY_CONTEXT,
13176
13306
  domain: "global",
13177
13307
  context_id: contextData.contextId,
13178
- }).then((_) => undefined);
13308
+ }).then(() => undefined);
13179
13309
  }
13180
13310
  handleUpdated(contextData, delta, extraData) {
13181
13311
  const oldContext = contextData.context;
@@ -13228,7 +13358,7 @@ class GW3Bridge {
13228
13358
  contextData.contextId = contextCreatedMsg.context_id;
13229
13359
  contextData.activityId = contextCreatedMsg.activity_id;
13230
13360
  if (!contextData.sentExplicitSubscription) {
13231
- this.sendSubscribe(contextData);
13361
+ this.sendSubscribe(contextData).catch(() => { });
13232
13362
  }
13233
13363
  }
13234
13364
  }
@@ -13288,10 +13418,10 @@ class GW3Bridge {
13288
13418
  const oldContext = contextData.context;
13289
13419
  contextData.hasReceivedSnapshot = true;
13290
13420
  if (updatedMessageType === GW_MESSAGE_SUBSCRIBED_CONTEXT) {
13291
- contextData.context = contextUpdatedMsg.data || {};
13421
+ contextData.context = contextUpdatedMsg.data ?? {};
13292
13422
  }
13293
13423
  else if (updatedMessageType === GW_MESSAGE_JOINED_ACTIVITY) {
13294
- contextData.context = contextUpdatedMsg.context_snapshot || {};
13424
+ contextData.context = contextUpdatedMsg.context_snapshot ?? {};
13295
13425
  }
13296
13426
  else if (updatedMessageType === GW_MESSAGE_CONTEXT_UPDATED) {
13297
13427
  contextData.context = applyContextDelta(contextData.context, contextUpdatedMsg.delta, this._logger);
@@ -13373,23 +13503,36 @@ class GW3Bridge {
13373
13503
  return;
13374
13504
  }
13375
13505
  }
13376
- sendSubscribe(contextData) {
13506
+ async sendSubscribe(contextData) {
13377
13507
  contextData.sentExplicitSubscription = true;
13378
- return this._gw3Session
13379
- .send({
13380
- type: GW_MESSAGE_SUBSCRIBE_CONTEXT,
13381
- domain: "global",
13382
- context_id: contextData.contextId,
13383
- }).then((_) => undefined);
13508
+ try {
13509
+ await this._gw3Session.send({
13510
+ type: GW_MESSAGE_SUBSCRIBE_CONTEXT,
13511
+ domain: "global",
13512
+ context_id: contextData.contextId,
13513
+ });
13514
+ return;
13515
+ }
13516
+ catch (error) {
13517
+ contextData.sentExplicitSubscription = false;
13518
+ throw error;
13519
+ }
13384
13520
  }
13385
- sendUnsubscribe(contextData) {
13521
+ async sendUnsubscribe(contextData) {
13522
+ const prev = contextData.sentExplicitSubscription;
13386
13523
  contextData.sentExplicitSubscription = false;
13387
- return this._gw3Session
13388
- .send({
13389
- type: GW_MESSAGE_UNSUBSCRIBE_CONTEXT,
13390
- domain: "global",
13391
- context_id: contextData.contextId,
13392
- }).then((_) => undefined);
13524
+ try {
13525
+ await this._gw3Session.send({
13526
+ type: GW_MESSAGE_UNSUBSCRIBE_CONTEXT,
13527
+ domain: "global",
13528
+ context_id: contextData.contextId,
13529
+ });
13530
+ return;
13531
+ }
13532
+ catch (error) {
13533
+ contextData.sentExplicitSubscription = prev;
13534
+ throw error;
13535
+ }
13393
13536
  }
13394
13537
  calculateContextDeltaV1(from, to) {
13395
13538
  const delta = { added: {}, updated: {}, removed: [], reset: undefined };
@@ -13442,7 +13585,11 @@ class GW3Bridge {
13442
13585
  this._contextIdToName = {};
13443
13586
  delete this._protocolVersion;
13444
13587
  this._contextsTempCache = Object.keys(this._contextNameToData).reduce((cacheSoFar, ctxName) => {
13445
- cacheSoFar[ctxName] = this._contextNameToData[ctxName].context;
13588
+ const contextData = this._contextNameToData[ctxName];
13589
+ const addToCache = !this._onlyReAnnounceSubscribedContexts || contextData.hasReceivedSnapshot;
13590
+ if (addToCache) {
13591
+ cacheSoFar[ctxName] = this._contextNameToData[ctxName].context;
13592
+ }
13446
13593
  return cacheSoFar;
13447
13594
  }, {});
13448
13595
  this._contextNameToData = {};
@@ -15632,13 +15779,15 @@ class ServerStreaming {
15632
15779
  session;
15633
15780
  repository;
15634
15781
  serverRepository;
15782
+ logger;
15635
15783
  ERR_URI_SUBSCRIPTION_FAILED = "com.tick42.agm.errors.subscription.failure";
15636
15784
  callbacks = CallbackRegistryFactory();
15637
15785
  nextStreamId = 0;
15638
- constructor(session, repository, serverRepository) {
15786
+ constructor(session, repository, serverRepository, logger) {
15639
15787
  this.session = session;
15640
15788
  this.repository = repository;
15641
15789
  this.serverRepository = serverRepository;
15790
+ this.logger = logger;
15642
15791
  session.on("add-interest", (msg) => {
15643
15792
  this.handleAddInterest(msg);
15644
15793
  });
@@ -15671,6 +15820,8 @@ class ServerStreaming {
15671
15820
  type: "accepted",
15672
15821
  subscription_id: key,
15673
15822
  stream_id: streamId,
15823
+ }).catch((err) => {
15824
+ this.logger.warn(`Failed to send accepted message for subscription ${key}: ${JSON.stringify(err)}`);
15674
15825
  });
15675
15826
  this.callbacks.execute(SUBSCRIPTION_ADDED, subscription, streamingMethod);
15676
15827
  }
@@ -15708,7 +15859,10 @@ class ServerStreaming {
15708
15859
  stream_id: streamId,
15709
15860
  data,
15710
15861
  };
15711
- this.session.sendFireAndForget(publishMessage);
15862
+ this.session.sendFireAndForget(publishMessage)
15863
+ .catch((err) => {
15864
+ this.logger.warn(`Failed to send publish message for stream ${streamId}: ${JSON.stringify(err)}`);
15865
+ });
15712
15866
  });
15713
15867
  }
15714
15868
  pushDataToSingle(method, subscription, data) {
@@ -15720,7 +15874,10 @@ class ServerStreaming {
15720
15874
  subscription_id: subscription.id,
15721
15875
  data,
15722
15876
  };
15723
- this.session.sendFireAndForget(postMessage);
15877
+ this.session.sendFireAndForget(postMessage)
15878
+ .catch((err) => {
15879
+ this.logger.warn(`Failed to send post message for subscription ${subscription.id}: ${JSON.stringify(err)}`);
15880
+ });
15724
15881
  }
15725
15882
  closeSingleSubscription(streamingMethod, subscription) {
15726
15883
  if (streamingMethod.protocolState.subscriptionsMap) {
@@ -15731,7 +15888,10 @@ class ServerStreaming {
15731
15888
  subscription_id: subscription.id,
15732
15889
  reason: "Server dropping a single subscription",
15733
15890
  };
15734
- this.session.sendFireAndForget(dropSubscriptionMessage);
15891
+ this.session.sendFireAndForget(dropSubscriptionMessage)
15892
+ .catch((err) => {
15893
+ this.logger.warn(`Failed to send drop-subscription message for subscription ${subscription.id}: ${JSON.stringify(err)}`);
15894
+ });
15735
15895
  subscription.instance;
15736
15896
  this.callbacks.execute(SUBSCRIPTION_REMOVED, subscription, streamingMethod);
15737
15897
  }
@@ -15759,7 +15919,10 @@ class ServerStreaming {
15759
15919
  subscription_id: subscription.id,
15760
15920
  reason: "Server dropping all subscriptions on stream_id: " + subscription.streamId,
15761
15921
  };
15762
- this.session.sendFireAndForget(drop);
15922
+ this.session.sendFireAndForget(drop)
15923
+ .catch((err) => {
15924
+ this.logger.warn(`Failed to send drop-subscription message for subscription ${subscription.id}: ${JSON.stringify(err)}`);
15925
+ });
15763
15926
  });
15764
15927
  }
15765
15928
  getSubscriptionList(streamingMethod, branchKey) {
@@ -15868,7 +16031,10 @@ class ServerStreaming {
15868
16031
  reason,
15869
16032
  request_id: subscriptionId,
15870
16033
  };
15871
- this.session.sendFireAndForget(errorMessage);
16034
+ this.session.sendFireAndForget(errorMessage)
16035
+ .catch((err) => {
16036
+ this.logger.warn(`Failed to send subscription failed message for subscription ${subscriptionId}: ${JSON.stringify(err)}`);
16037
+ });
15872
16038
  }
15873
16039
  getStreamId(streamingMethod, branchKey) {
15874
16040
  if (typeof branchKey !== "string") {
@@ -15901,7 +16067,7 @@ class ServerProtocol {
15901
16067
  this.clientRepository = clientRepository;
15902
16068
  this.serverRepository = serverRepository;
15903
16069
  this.logger = logger;
15904
- this.streaming = new ServerStreaming(session, clientRepository, serverRepository);
16070
+ this.streaming = new ServerStreaming(session, clientRepository, serverRepository, logger.subLogger("streaming"));
15905
16071
  this.session.on("invoke", (msg) => this.handleInvokeMessage(msg));
15906
16072
  }
15907
16073
  createStream(repoMethod) {
@@ -15960,7 +16126,10 @@ class ServerProtocol {
15960
16126
  request_id: undefined,
15961
16127
  };
15962
16128
  }
15963
- this.session.sendFireAndForget(msg);
16129
+ this.session.sendFireAndForget(msg)
16130
+ .catch((error => {
16131
+ this.logger.warn(`Failed to send method invocation result for method ${method.definition.name} invocation ${invocationId} - ${JSON.stringify(error)}`);
16132
+ }));
15964
16133
  }
15965
16134
  async unregister(method) {
15966
16135
  const msg = {
@@ -16420,6 +16589,8 @@ class ClientStreaming {
16420
16589
  subscription_id: server.subscriptionId,
16421
16590
  reason_uri: "",
16422
16591
  reason: ON_CLOSE_MSG_CLIENT_INIT,
16592
+ }).catch((err) => {
16593
+ this.logger.warn(`Error sending unsubscribe for subscription id ${server.subscriptionId}: ${JSON.stringify(err)}`);
16423
16594
  });
16424
16595
  delete this.subscriptionIdToLocalKeyMap[server.subscriptionId];
16425
16596
  });
@@ -16759,7 +16930,10 @@ class MessageBus {
16759
16930
  routing_key: routingKey,
16760
16931
  target_identity: target
16761
16932
  });
16762
- this.session.send(args);
16933
+ this.session.send(args)
16934
+ .catch((err) => {
16935
+ this.logger.error(`Failed to publish message to topic ${topic} with routing key ${routingKey} for ${JSON.stringify(target)}: ${JSON.stringify(err)}`);
16936
+ });
16763
16937
  };
16764
16938
  subscribe = (topic, callback, options) => {
16765
16939
  return new Promise((resolve, reject) => {
@@ -16777,8 +16951,12 @@ class MessageBus {
16777
16951
  this.subscriptions.push({ subscription_id, topic, callback, source: target });
16778
16952
  resolve({
16779
16953
  unsubscribe: () => {
16780
- this.session.send({ type: "unsubscribe", subscription_id, peer_id: this.peerId });
16781
- this.subscriptions = this.subscriptions.filter((s) => s.subscription_id !== subscription_id);
16954
+ this.session.send({ type: "unsubscribe", subscription_id, peer_id: this.peerId })
16955
+ .then(() => {
16956
+ this.subscriptions = this.subscriptions.filter((s) => s.subscription_id !== subscription_id);
16957
+ }).catch((err) => {
16958
+ this.logger.warn(`Failed to send unsubscribe request for ${subscription_id}: ${JSON.stringify(err)}`);
16959
+ });
16782
16960
  return Promise.resolve();
16783
16961
  }
16784
16962
  });
@@ -16976,10 +17154,12 @@ const IOConnectCoreFactory = (userConfig, ext) => {
16976
17154
  connection: _connection,
16977
17155
  logger: _logger.subLogger("contexts"),
16978
17156
  trackAllContexts: typeof internalConfig.contexts === "object" ? internalConfig.contexts.trackAllContexts : false,
16979
- reAnnounceKnownContexts: typeof internalConfig.contexts === "object" ? internalConfig.contexts.reAnnounceKnownContexts : false
17157
+ reAnnounceKnownContexts: typeof internalConfig.contexts === "object" ? internalConfig.contexts.reAnnounceKnownContexts : false,
17158
+ subscribeOnGet: typeof internalConfig.contexts === "object" ? internalConfig.contexts.subscribeOnGet : true,
17159
+ subscribeOnUpdate: typeof internalConfig.contexts === "object" ? internalConfig.contexts.subscribeOnUpdate : true,
17160
+ onlyReAnnounceSubscribedContexts: typeof internalConfig.contexts === "object" ? internalConfig.contexts.onlyReAnnounceSubscribedContexts : true
16980
17161
  });
16981
17162
  registerLib("contexts", _contexts, initTimer);
16982
- return _contexts;
16983
17163
  }
16984
17164
  else {
16985
17165
  const replayer = _connection.replayer;
@@ -16987,6 +17167,7 @@ const IOConnectCoreFactory = (userConfig, ext) => {
16987
17167
  replayer.drain(ContextMessageReplaySpec.name);
16988
17168
  }
16989
17169
  }
17170
+ return Promise.resolve();
16990
17171
  }
16991
17172
  async function setupBus() {
16992
17173
  if (!internalConfig.bus) {