@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.
@@ -7744,7 +7744,7 @@
7744
7744
  }
7745
7745
  }
7746
7746
 
7747
- var version$1 = "4.1.2";
7747
+ var version$1 = "4.1.4";
7748
7748
 
7749
7749
  const setupGlobalSystem = (io, bridge) => {
7750
7750
  return {
@@ -8031,7 +8031,10 @@
8031
8031
  type: "define",
8032
8032
  metrics: [rootStateMetric],
8033
8033
  };
8034
- session.send(defineRootMetricsMsg);
8034
+ session.sendFireAndForget(defineRootMetricsMsg)
8035
+ .catch((err) => {
8036
+ config.logger.warn(`Failed to send define for root state metric: ${JSON.stringify(err)}`);
8037
+ });
8035
8038
  if (reconnect) {
8036
8039
  replayRepo(repo);
8037
8040
  }
@@ -8079,7 +8082,10 @@
8079
8082
  type: "define",
8080
8083
  metrics: [metric],
8081
8084
  };
8082
- session.send(createMetricsMsg);
8085
+ session.sendFireAndForget(createMetricsMsg)
8086
+ .catch((err) => {
8087
+ config.logger.warn(`Failed to send define for system state metric of ${system.name}: ${JSON.stringify(err)}`);
8088
+ });
8083
8089
  };
8084
8090
  const updateSystem = async (system, state) => {
8085
8091
  await joinPromise;
@@ -8094,7 +8100,10 @@
8094
8100
  timestamp: Date.now(),
8095
8101
  }],
8096
8102
  };
8097
- session.send(shadowedUpdateMetric);
8103
+ session.sendFireAndForget(shadowedUpdateMetric)
8104
+ .catch((err) => {
8105
+ config.logger.warn(`Failed to send update for system state metric of ${system.name}: ${JSON.stringify(err)}`);
8106
+ });
8098
8107
  const stateObj = composeMsgForRootStateMetric(system);
8099
8108
  const rootMetric = {
8100
8109
  type: "publish",
@@ -8108,7 +8117,10 @@
8108
8117
  timestamp: Date.now(),
8109
8118
  }],
8110
8119
  };
8111
- session.send(rootMetric);
8120
+ session.sendFireAndForget(rootMetric)
8121
+ .catch((err) => {
8122
+ config.logger.warn(`Failed to send update for root state metric of ${system.name}: ${JSON.stringify(err)}`);
8123
+ });
8112
8124
  };
8113
8125
  const createMetric = async (metric) => {
8114
8126
  const metricClone = cloneMetric(metric);
@@ -8118,7 +8130,10 @@
8118
8130
  type: "define",
8119
8131
  metrics: [m],
8120
8132
  };
8121
- session.send(createMetricsMsg);
8133
+ session.sendFireAndForget(createMetricsMsg)
8134
+ .catch((err) => {
8135
+ config.logger.warn(`Failed to send define for metric ${metric.name}: ${JSON.stringify(err)}`);
8136
+ });
8122
8137
  if (typeof metricClone.value !== "undefined") {
8123
8138
  updateMetricCore(metricClone);
8124
8139
  }
@@ -8139,7 +8154,10 @@
8139
8154
  timestamp: Date.now(),
8140
8155
  }],
8141
8156
  };
8142
- return session.sendFireAndForget(publishMetricsMsg);
8157
+ return session.sendFireAndForget(publishMetricsMsg)
8158
+ .catch((err) => {
8159
+ config.logger.warn(`Failed to publish metric ${metric.name}: ${JSON.stringify(err)}`);
8160
+ });
8143
8161
  }
8144
8162
  return Promise.resolve();
8145
8163
  };
@@ -9006,8 +9024,9 @@
9006
9024
  const pw = new PromiseWrapper();
9007
9025
  this.logger.debug(`initiating ws to ${this.settings.ws}...`);
9008
9026
  this.ws = new WebSocketConstructor(this.settings.ws ?? "");
9027
+ let wasOpen = false;
9009
9028
  this.ws.onerror = (err) => {
9010
- let reason = "";
9029
+ let reason;
9011
9030
  try {
9012
9031
  reason = JSON.stringify(err);
9013
9032
  }
@@ -9026,17 +9045,26 @@
9026
9045
  }
9027
9046
  this.logger.info(`ws error - reason: ${reason}`);
9028
9047
  pw.reject("error");
9048
+ if (wasOpen) {
9049
+ wasOpen = false;
9050
+ this.notifyForSocketState("error");
9051
+ }
9029
9052
  this.notifyStatusChanged(false, reason);
9030
9053
  };
9031
9054
  this.ws.onclose = (err) => {
9032
9055
  this.logger.info(`ws closed - code: ${err?.code} reason: ${err?.reason}`);
9033
9056
  pw.reject("closed");
9057
+ if (wasOpen) {
9058
+ wasOpen = false;
9059
+ this.notifyForSocketState("closed");
9060
+ }
9034
9061
  this.notifyStatusChanged(false);
9035
9062
  };
9036
9063
  this.ws.onopen = () => {
9037
9064
  this.startupTimer.mark("ws-opened");
9038
9065
  this.logger.info(`ws opened ${this.settings.identity?.application}`);
9039
9066
  pw.resolve();
9067
+ wasOpen = true;
9040
9068
  this.notifyStatusChanged(true);
9041
9069
  };
9042
9070
  this.ws.onmessage = (message) => {
@@ -9824,17 +9852,31 @@
9824
9852
  callbacks.execute("onJoined", wasReconnect);
9825
9853
  }
9826
9854
  function handleConnectionDisconnected() {
9827
- _connectionOn = false;
9828
9855
  logger.debug("connection is down");
9856
+ _connectionOn = false;
9829
9857
  isJoined = false;
9830
9858
  tryReconnecting = true;
9859
+ Object.keys(requestsMap).forEach(requestId => {
9860
+ const request = requestsMap[requestId];
9861
+ if (request) {
9862
+ logger.trace(`failing pending request ${requestId} due to connection lost`);
9863
+ request.error({
9864
+ err: "Connection lost - gateway connection was disconnected"
9865
+ });
9866
+ }
9867
+ });
9831
9868
  callbacks.execute("onLeft", { disconnected: true });
9832
9869
  }
9833
- function handleConnectionLoggedIn() {
9870
+ async function handleConnectionLoggedIn() {
9834
9871
  _connectionOn = true;
9835
9872
  if (tryReconnecting) {
9836
9873
  logger.debug("connection is now up - trying to reconnect...");
9837
- join(_latestOptions);
9874
+ try {
9875
+ await join(_latestOptions);
9876
+ }
9877
+ catch {
9878
+ logger.trace(`failed to reconnect`);
9879
+ }
9838
9880
  }
9839
9881
  }
9840
9882
  function onJoined(callback) {
@@ -9927,7 +9969,7 @@
9927
9969
  connection
9928
9970
  .send(msg, options)
9929
9971
  .catch((err) => {
9930
- requestsMap[requestId].error({ err });
9972
+ requestsMap[requestId]?.error({ err });
9931
9973
  });
9932
9974
  });
9933
9975
  }
@@ -10006,6 +10048,7 @@
10006
10048
  initialLogin = true;
10007
10049
  initialLoginAttempts = 3;
10008
10050
  loginConfig;
10051
+ loginRetryInProgress = false;
10009
10052
  constructor(settings, logger) {
10010
10053
  this.settings = settings;
10011
10054
  this.logger = logger;
@@ -10119,6 +10162,7 @@
10119
10162
  return this.registry.add("disconnected", callback);
10120
10163
  }
10121
10164
  async login(authRequest, reconnect) {
10165
+ this.logger.debug(`Login initiated - reconnect: ${reconnect}, transport: ${this.transport.name()}`);
10122
10166
  if (!this._defaultAuth) {
10123
10167
  this._defaultAuth = authRequest;
10124
10168
  }
@@ -10127,19 +10171,18 @@
10127
10171
  const newAuth = this.transportSwap();
10128
10172
  authRequest = newAuth ?? authRequest;
10129
10173
  }
10130
- this.logger.trace(`Starting login for transport: ${this.transport.name()} and auth ${JSON.stringify(authRequest)}`);
10131
10174
  try {
10132
10175
  await this.transport.open();
10133
- this.logger.trace(`Transport: ${this.transport.name()} opened, logging in`);
10176
+ this.logger.debug(`Transport: ${this.transport.name()} opened, logging in`);
10134
10177
  timer("connection").mark("transport-opened");
10135
10178
  const identity = await this.loginCore(authRequest, reconnect);
10136
- this.logger.trace(`Logged in with identity: ${JSON.stringify(identity)}`);
10179
+ this.logger.debug(`Logged in with identity: ${JSON.stringify(identity)}`);
10137
10180
  timer("connection").mark("protocol-logged-in");
10138
10181
  return identity;
10139
10182
  }
10140
10183
  catch (error) {
10141
10184
  if (this._switchInProgress) {
10142
- this.logger.trace("An error while logging in after a transport swap, preparing a default swap.");
10185
+ this.logger.debug("An error while logging in after a transport swap, preparing a default swap.");
10143
10186
  this.prepareDefaultSwap();
10144
10187
  }
10145
10188
  throw new Error(error);
@@ -10182,6 +10225,7 @@
10182
10225
  setLoggedIn(value) {
10183
10226
  this._isLoggedIn = value;
10184
10227
  if (this._isLoggedIn) {
10228
+ this.initialLogin = false;
10185
10229
  this.registry.execute("onLoggedIn");
10186
10230
  }
10187
10231
  }
@@ -10208,8 +10252,10 @@
10208
10252
  }
10209
10253
  handleConnectionChanged(connected) {
10210
10254
  if (this._connected === connected) {
10255
+ this.logger.trace("connection state unchanged, skipping");
10211
10256
  return;
10212
10257
  }
10258
+ this.logger.info(`connection state changed to ${connected ? "connected" : "disconnected"}`);
10213
10259
  this._connected = connected;
10214
10260
  if (connected) {
10215
10261
  if (this.settings?.replaySpecs?.length) {
@@ -10219,28 +10265,44 @@
10219
10265
  this.registry.execute("connected");
10220
10266
  }
10221
10267
  else {
10222
- this.handleDisconnected();
10268
+ this.setLoggedIn(false);
10269
+ if (this.shouldTryLogin) {
10270
+ this.attemptLoginWithRetry();
10271
+ }
10223
10272
  this.registry.execute("disconnected");
10224
10273
  }
10225
10274
  }
10226
- handleDisconnected() {
10227
- this.setLoggedIn(false);
10228
- const tryToLogin = this.shouldTryLogin;
10229
- if (tryToLogin && this.initialLogin) {
10275
+ async attemptLoginWithRetry() {
10276
+ if (!this.loginConfig) {
10277
+ throw new Error("no login info");
10278
+ }
10279
+ if (this.loginRetryInProgress) {
10280
+ this.logger.debug("login attempt already in progress, ignoring request...");
10281
+ return;
10282
+ }
10283
+ if (this._isLoggedIn) {
10284
+ this.logger.debug("already logged in, ignoring request...");
10285
+ return;
10286
+ }
10287
+ if (this.initialLogin) {
10288
+ this.logger.debug(`initial login attempt failed, ${this.initialLoginAttempts} attempts remaining...`);
10230
10289
  if (this.initialLoginAttempts <= 0) {
10290
+ this.logger.info("maximum initial login attempts reached, will not try to login again");
10231
10291
  return;
10232
10292
  }
10233
10293
  this.initialLoginAttempts--;
10234
10294
  }
10235
- this.logger.debug("disconnected - will try new login?" + this.shouldTryLogin);
10236
- if (this.shouldTryLogin) {
10237
- if (!this.loginConfig) {
10238
- throw new Error("no login info");
10239
- }
10240
- this.login(this.loginConfig, true)
10241
- .catch(() => {
10242
- setTimeout(this.handleDisconnected.bind(this), this.settings.reconnectInterval || 1000);
10243
- });
10295
+ try {
10296
+ this.logger.debug(`will try a new login... ${this.loginRetryInProgress}`);
10297
+ this.loginRetryInProgress = true;
10298
+ await this.login(this.loginConfig, true);
10299
+ }
10300
+ catch (e) {
10301
+ this.logger.error(`error trying to login: ${e?.message}`, e);
10302
+ setTimeout(this.attemptLoginWithRetry.bind(this), this.settings.reconnectInterval ?? 1000);
10303
+ }
10304
+ finally {
10305
+ this.loginRetryInProgress = false;
10244
10306
  }
10245
10307
  }
10246
10308
  handleTransportMessage(msg) {
@@ -10367,7 +10429,6 @@
10367
10429
  return message;
10368
10430
  }
10369
10431
  async loginCore(config, reconnect) {
10370
- this.logger.info("logging in...");
10371
10432
  this.loginConfig = config;
10372
10433
  if (!this.loginConfig) {
10373
10434
  this.loginConfig = { username: "", password: "" };
@@ -10382,11 +10443,13 @@
10382
10443
  if (config.sessionId) {
10383
10444
  helloMsg.request_id = config.sessionId;
10384
10445
  }
10385
- this.globalDomain = domainSession("global", this, this.logger.subLogger("global-domain"), [
10386
- "welcome",
10387
- "token",
10388
- "authentication-request"
10389
- ]);
10446
+ if (!this.globalDomain) {
10447
+ this.globalDomain = domainSession("global", this, this.logger.subLogger("global-domain"), [
10448
+ "welcome",
10449
+ "token",
10450
+ "authentication-request"
10451
+ ]);
10452
+ }
10390
10453
  const sendOptions = { skipPeerId: true };
10391
10454
  if (this.initialLogin) {
10392
10455
  sendOptions.retryInterval = this.settings.reconnectInterval;
@@ -10394,7 +10457,6 @@
10394
10457
  }
10395
10458
  try {
10396
10459
  const welcomeMsg = await this.tryAuthenticate(this.globalDomain, helloMsg, sendOptions, config);
10397
- this.initialLogin = false;
10398
10460
  this.logger.info("login successful with peerId " + welcomeMsg.peer_id);
10399
10461
  this.peerId = welcomeMsg.peer_id;
10400
10462
  this.resolvedIdentity = welcomeMsg.resolved_identity;
@@ -10497,7 +10559,7 @@
10497
10559
  clearTimeout(this.pingTimer);
10498
10560
  }
10499
10561
  const promises = this.sessions.map((session) => {
10500
- session.leave();
10562
+ return session.leave();
10501
10563
  });
10502
10564
  await Promise.all(promises);
10503
10565
  }
@@ -10722,7 +10784,7 @@
10722
10784
  }
10723
10785
  };
10724
10786
 
10725
- var version = "6.7.0";
10787
+ var version = "6.7.2";
10726
10788
 
10727
10789
  function prepareConfig (configuration, ext, glue42gd) {
10728
10790
  let nodeStartingContext;
@@ -10817,14 +10879,20 @@
10817
10879
  };
10818
10880
  }
10819
10881
  function getContexts() {
10882
+ const defaultConfig = {
10883
+ reAnnounceKnownContexts: true,
10884
+ subscribeOnUpdate: true,
10885
+ subscribeOnGet: true,
10886
+ onlyReAnnounceSubscribedContexts: true
10887
+ };
10820
10888
  if (typeof configuration.contexts === "undefined") {
10821
- return { reAnnounceKnownContexts: true };
10889
+ return defaultConfig;
10822
10890
  }
10823
10891
  if (typeof configuration.contexts === "boolean" && configuration.contexts) {
10824
- return { reAnnounceKnownContexts: true };
10892
+ return defaultConfig;
10825
10893
  }
10826
10894
  if (typeof configuration.contexts === "object") {
10827
- return Object.assign({}, { reAnnounceKnownContexts: true }, configuration.contexts);
10895
+ return { ...defaultConfig, ...configuration.contexts };
10828
10896
  }
10829
10897
  return false;
10830
10898
  }
@@ -10923,13 +10991,28 @@
10923
10991
  updateCallbacks = {};
10924
10992
  activityId;
10925
10993
  sentExplicitSubscription;
10926
- hasReceivedSnapshot;
10994
+ get hasReceivedSnapshot() {
10995
+ return this.snapshotPromiseWrapper.resolved;
10996
+ }
10997
+ set hasReceivedSnapshot(has) {
10998
+ if (has) {
10999
+ this.snapshotPromiseWrapper.resolve();
11000
+ }
11001
+ else {
11002
+ this.snapshotPromiseWrapper = new PromiseWrapper();
11003
+ }
11004
+ }
11005
+ get snapshotPromise() {
11006
+ return this.snapshotPromiseWrapper.promise;
11007
+ }
11008
+ snapshotPromiseWrapper;
10927
11009
  constructor(contextId, name, isAnnounced, activityId) {
10928
11010
  this.contextId = contextId;
10929
11011
  this.name = name;
10930
11012
  this.isAnnounced = isAnnounced;
10931
11013
  this.activityId = activityId;
10932
11014
  this.context = {};
11015
+ this.snapshotPromiseWrapper = new PromiseWrapper();
10933
11016
  }
10934
11017
  hasCallbacks() {
10935
11018
  return Object.keys(this.updateCallbacks).length > 0;
@@ -12849,10 +12932,15 @@
12849
12932
  }
12850
12933
 
12851
12934
  class GW3Bridge {
12935
+ ERROR_URI_FAILURE = "global.errors.failure";
12936
+ ERROR_URI_INVALID_CONTEXT = "global.errors.invalid_context";
12852
12937
  _logger;
12853
12938
  _connection;
12854
12939
  _trackAllContexts;
12855
12940
  _reAnnounceKnownContexts;
12941
+ _subscribeOnUpdate;
12942
+ _subscribeOnGet;
12943
+ _onlyReAnnounceSubscribedContexts;
12856
12944
  _gw3Session;
12857
12945
  _contextNameToData = {};
12858
12946
  _gw3Subscriptions = [];
@@ -12879,6 +12967,9 @@
12879
12967
  this._logger = config.logger;
12880
12968
  this._trackAllContexts = config.trackAllContexts;
12881
12969
  this._reAnnounceKnownContexts = config.reAnnounceKnownContexts;
12970
+ this._subscribeOnUpdate = config.subscribeOnUpdate ?? true;
12971
+ this._subscribeOnGet = config.subscribeOnGet ?? true;
12972
+ this._onlyReAnnounceSubscribedContexts = config.onlyReAnnounceSubscribedContexts ?? true;
12882
12973
  this._gw3Session = this._connection.domain("global", [
12883
12974
  GW_MESSAGE_CONTEXT_CREATED,
12884
12975
  GW_MESSAGE_SUBSCRIBED_CONTEXT,
@@ -12891,9 +12982,14 @@
12891
12982
  return;
12892
12983
  }
12893
12984
  if (!this._reAnnounceKnownContexts) {
12985
+ this._contextsTempCache = {};
12894
12986
  return this._connection.setLibReAnnounced({ name: "contexts" });
12895
12987
  }
12896
- this.reInitiateState().then(() => this._connection.setLibReAnnounced({ name: "contexts" }));
12988
+ this.reInitiateState()
12989
+ .then(() => this._connection.setLibReAnnounced({ name: "contexts" }))
12990
+ .catch((err) => {
12991
+ this._logger.warn(`Error while re-announcing contexts: ${JSON.stringify(err)}`);
12992
+ });
12897
12993
  });
12898
12994
  this.subscribeToContextCreatedMessages();
12899
12995
  this.subscribeToContextUpdatedMessages();
@@ -12971,10 +13067,11 @@
12971
13067
  }
12972
13068
  const contextData = this._contextNameToData[name];
12973
13069
  if (!contextData || !contextData.isAnnounced) {
12974
- return this.createContext(name, delta);
13070
+ await this.createContext(name, delta);
13071
+ return;
12975
13072
  }
12976
13073
  let currentContext = contextData.context;
12977
- if (!contextData.hasCallbacks()) {
13074
+ if (!contextData.hasReceivedSnapshot) {
12978
13075
  currentContext = await this.get(contextData.name);
12979
13076
  }
12980
13077
  const calculatedDelta = this.setPathSupported ?
@@ -12986,18 +13083,25 @@
12986
13083
  && !calculatedDelta.commands?.length) {
12987
13084
  return Promise.resolve();
12988
13085
  }
12989
- return this._gw3Session
13086
+ const gwResponse = await this._gw3Session
12990
13087
  .send({
12991
13088
  type: GW_MESSAGE_UPDATE_CONTEXT,
12992
13089
  domain: "global",
12993
13090
  context_id: contextData.contextId,
12994
13091
  delta: calculatedDelta,
12995
- }, {}, { skipPeerId: false })
12996
- .then((gwResponse) => {
13092
+ }, {}, { skipPeerId: false });
13093
+ if (this._subscribeOnUpdate &&
13094
+ !contextData.sentExplicitSubscription &&
13095
+ !contextData.activityId) {
13096
+ this.subscribe(name, () => { });
13097
+ }
13098
+ if (contextData.sentExplicitSubscription ||
13099
+ contextData.activityId) {
13100
+ await contextData.snapshotPromise;
12997
13101
  this.handleUpdated(contextData, calculatedDelta, {
12998
13102
  updaterId: gwResponse.peer_id
12999
13103
  });
13000
- });
13104
+ }
13001
13105
  }
13002
13106
  async set(name, data) {
13003
13107
  if (data) {
@@ -13010,7 +13114,7 @@
13010
13114
  if (!contextData || !contextData.isAnnounced) {
13011
13115
  return this.createContext(name, data);
13012
13116
  }
13013
- return this._gw3Session
13117
+ await this._gw3Session
13014
13118
  .send({
13015
13119
  type: GW_MESSAGE_UPDATE_CONTEXT,
13016
13120
  domain: "global",
@@ -13061,14 +13165,21 @@
13061
13165
  commands.push({ type: "set", path: pathValue.path, value: pathValue.value });
13062
13166
  }
13063
13167
  }
13064
- return this._gw3Session
13168
+ const gwResponse = await this._gw3Session
13065
13169
  .send({
13066
13170
  type: GW_MESSAGE_UPDATE_CONTEXT,
13067
13171
  domain: "global",
13068
13172
  context_id: contextData.contextId,
13069
13173
  delta: { commands }
13070
- }, {}, { skipPeerId: false })
13071
- .then((gwResponse) => {
13174
+ }, {}, { skipPeerId: false });
13175
+ if (this._subscribeOnUpdate &&
13176
+ !contextData.sentExplicitSubscription &&
13177
+ !contextData.activityId) {
13178
+ this.subscribe(name, () => { });
13179
+ }
13180
+ if (contextData.sentExplicitSubscription ||
13181
+ contextData.activityId) {
13182
+ await contextData.snapshotPromise;
13072
13183
  this.handleUpdated(contextData, {
13073
13184
  added: {},
13074
13185
  removed: [],
@@ -13077,7 +13188,7 @@
13077
13188
  }, {
13078
13189
  updaterId: gwResponse.peer_id
13079
13190
  });
13080
- });
13191
+ }
13081
13192
  }
13082
13193
  async get(name) {
13083
13194
  if (name in this._creationPromises) {
@@ -13088,16 +13199,29 @@
13088
13199
  return Promise.resolve({});
13089
13200
  }
13090
13201
  if (contextData && (!contextData.hasCallbacks() || !contextData.hasReceivedSnapshot)) {
13091
- return new Promise((resolve) => {
13202
+ return new Promise((resolve, reject) => {
13092
13203
  this.subscribe(name, (data, _d, _r, un) => {
13093
- this.unsubscribe(un);
13204
+ if (!this._subscribeOnGet) {
13205
+ this.unsubscribe(un);
13206
+ }
13094
13207
  resolve(data);
13208
+ }).catch((e) => {
13209
+ if (this.isInvalidContextError(e)) {
13210
+ resolve({});
13211
+ return;
13212
+ }
13213
+ reject(e);
13095
13214
  });
13096
13215
  });
13097
13216
  }
13217
+ await contextData.snapshotPromise;
13098
13218
  const context = contextData?.context ?? {};
13099
13219
  return Promise.resolve(deepClone(context));
13100
13220
  }
13221
+ isInvalidContextError(e) {
13222
+ return e.reason_uri === this.ERROR_URI_INVALID_CONTEXT
13223
+ || (e.reason_uri === this.ERROR_URI_FAILURE && e.reason?.startsWith("Unable to find context with id"));
13224
+ }
13101
13225
  async subscribe(name, callback, subscriptionKey) {
13102
13226
  if (name in this._creationPromises) {
13103
13227
  await this._creationPromises[name];
@@ -13148,11 +13272,10 @@
13148
13272
  }
13149
13273
  }
13150
13274
  unsubscribe(subscriptionKey) {
13151
- this._contextsSubscriptionsCache = this._contextsSubscriptionsCache.filter((subscription) => subscription.subKey !== subscriptionKey);
13152
13275
  for (const name of Object.keys(this._contextNameToData)) {
13153
13276
  const contextData = this._contextNameToData[name];
13154
13277
  if (!contextData) {
13155
- return;
13278
+ continue;
13156
13279
  }
13157
13280
  const hadCallbacks = contextData.hasCallbacks();
13158
13281
  delete contextData.updateCallbacks[subscriptionKey];
@@ -13160,11 +13283,17 @@
13160
13283
  hadCallbacks &&
13161
13284
  !contextData.hasCallbacks() &&
13162
13285
  contextData.sentExplicitSubscription) {
13286
+ contextData.hasReceivedSnapshot = false;
13287
+ contextData.context = {};
13163
13288
  this.sendUnsubscribe(contextData).catch(() => { });
13164
13289
  }
13165
13290
  if (!contextData.isAnnounced &&
13166
13291
  !contextData.hasCallbacks()) {
13167
13292
  delete this._contextNameToData[name];
13293
+ delete this._contextNameToId[name];
13294
+ if (contextData.contextId) {
13295
+ delete this._contextIdToName[contextData.contextId];
13296
+ }
13168
13297
  }
13169
13298
  }
13170
13299
  }
@@ -13173,7 +13302,8 @@
13173
13302
  await this._creationPromises[name];
13174
13303
  }
13175
13304
  const contextData = this._contextNameToData[name];
13176
- if (!contextData) {
13305
+ const contextId = contextData?.contextId;
13306
+ if (!contextData || !contextId) {
13177
13307
  return Promise.reject(`context with ${name} does not exist`);
13178
13308
  }
13179
13309
  return this._gw3Session
@@ -13181,7 +13311,7 @@
13181
13311
  type: GW_MESSAGE_DESTROY_CONTEXT,
13182
13312
  domain: "global",
13183
13313
  context_id: contextData.contextId,
13184
- }).then((_) => undefined);
13314
+ }).then(() => undefined);
13185
13315
  }
13186
13316
  handleUpdated(contextData, delta, extraData) {
13187
13317
  const oldContext = contextData.context;
@@ -13234,7 +13364,7 @@
13234
13364
  contextData.contextId = contextCreatedMsg.context_id;
13235
13365
  contextData.activityId = contextCreatedMsg.activity_id;
13236
13366
  if (!contextData.sentExplicitSubscription) {
13237
- this.sendSubscribe(contextData);
13367
+ this.sendSubscribe(contextData).catch(() => { });
13238
13368
  }
13239
13369
  }
13240
13370
  }
@@ -13294,10 +13424,10 @@
13294
13424
  const oldContext = contextData.context;
13295
13425
  contextData.hasReceivedSnapshot = true;
13296
13426
  if (updatedMessageType === GW_MESSAGE_SUBSCRIBED_CONTEXT) {
13297
- contextData.context = contextUpdatedMsg.data || {};
13427
+ contextData.context = contextUpdatedMsg.data ?? {};
13298
13428
  }
13299
13429
  else if (updatedMessageType === GW_MESSAGE_JOINED_ACTIVITY) {
13300
- contextData.context = contextUpdatedMsg.context_snapshot || {};
13430
+ contextData.context = contextUpdatedMsg.context_snapshot ?? {};
13301
13431
  }
13302
13432
  else if (updatedMessageType === GW_MESSAGE_CONTEXT_UPDATED) {
13303
13433
  contextData.context = applyContextDelta(contextData.context, contextUpdatedMsg.delta, this._logger);
@@ -13379,23 +13509,36 @@
13379
13509
  return;
13380
13510
  }
13381
13511
  }
13382
- sendSubscribe(contextData) {
13512
+ async sendSubscribe(contextData) {
13383
13513
  contextData.sentExplicitSubscription = true;
13384
- return this._gw3Session
13385
- .send({
13386
- type: GW_MESSAGE_SUBSCRIBE_CONTEXT,
13387
- domain: "global",
13388
- context_id: contextData.contextId,
13389
- }).then((_) => undefined);
13514
+ try {
13515
+ await this._gw3Session.send({
13516
+ type: GW_MESSAGE_SUBSCRIBE_CONTEXT,
13517
+ domain: "global",
13518
+ context_id: contextData.contextId,
13519
+ });
13520
+ return;
13521
+ }
13522
+ catch (error) {
13523
+ contextData.sentExplicitSubscription = false;
13524
+ throw error;
13525
+ }
13390
13526
  }
13391
- sendUnsubscribe(contextData) {
13527
+ async sendUnsubscribe(contextData) {
13528
+ const prev = contextData.sentExplicitSubscription;
13392
13529
  contextData.sentExplicitSubscription = false;
13393
- return this._gw3Session
13394
- .send({
13395
- type: GW_MESSAGE_UNSUBSCRIBE_CONTEXT,
13396
- domain: "global",
13397
- context_id: contextData.contextId,
13398
- }).then((_) => undefined);
13530
+ try {
13531
+ await this._gw3Session.send({
13532
+ type: GW_MESSAGE_UNSUBSCRIBE_CONTEXT,
13533
+ domain: "global",
13534
+ context_id: contextData.contextId,
13535
+ });
13536
+ return;
13537
+ }
13538
+ catch (error) {
13539
+ contextData.sentExplicitSubscription = prev;
13540
+ throw error;
13541
+ }
13399
13542
  }
13400
13543
  calculateContextDeltaV1(from, to) {
13401
13544
  const delta = { added: {}, updated: {}, removed: [], reset: undefined };
@@ -13448,7 +13591,11 @@
13448
13591
  this._contextIdToName = {};
13449
13592
  delete this._protocolVersion;
13450
13593
  this._contextsTempCache = Object.keys(this._contextNameToData).reduce((cacheSoFar, ctxName) => {
13451
- cacheSoFar[ctxName] = this._contextNameToData[ctxName].context;
13594
+ const contextData = this._contextNameToData[ctxName];
13595
+ const addToCache = !this._onlyReAnnounceSubscribedContexts || contextData.hasReceivedSnapshot;
13596
+ if (addToCache) {
13597
+ cacheSoFar[ctxName] = this._contextNameToData[ctxName].context;
13598
+ }
13452
13599
  return cacheSoFar;
13453
13600
  }, {});
13454
13601
  this._contextNameToData = {};
@@ -15638,13 +15785,15 @@
15638
15785
  session;
15639
15786
  repository;
15640
15787
  serverRepository;
15788
+ logger;
15641
15789
  ERR_URI_SUBSCRIPTION_FAILED = "com.tick42.agm.errors.subscription.failure";
15642
15790
  callbacks = CallbackRegistryFactory();
15643
15791
  nextStreamId = 0;
15644
- constructor(session, repository, serverRepository) {
15792
+ constructor(session, repository, serverRepository, logger) {
15645
15793
  this.session = session;
15646
15794
  this.repository = repository;
15647
15795
  this.serverRepository = serverRepository;
15796
+ this.logger = logger;
15648
15797
  session.on("add-interest", (msg) => {
15649
15798
  this.handleAddInterest(msg);
15650
15799
  });
@@ -15677,6 +15826,8 @@
15677
15826
  type: "accepted",
15678
15827
  subscription_id: key,
15679
15828
  stream_id: streamId,
15829
+ }).catch((err) => {
15830
+ this.logger.warn(`Failed to send accepted message for subscription ${key}: ${JSON.stringify(err)}`);
15680
15831
  });
15681
15832
  this.callbacks.execute(SUBSCRIPTION_ADDED, subscription, streamingMethod);
15682
15833
  }
@@ -15714,7 +15865,10 @@
15714
15865
  stream_id: streamId,
15715
15866
  data,
15716
15867
  };
15717
- this.session.sendFireAndForget(publishMessage);
15868
+ this.session.sendFireAndForget(publishMessage)
15869
+ .catch((err) => {
15870
+ this.logger.warn(`Failed to send publish message for stream ${streamId}: ${JSON.stringify(err)}`);
15871
+ });
15718
15872
  });
15719
15873
  }
15720
15874
  pushDataToSingle(method, subscription, data) {
@@ -15726,7 +15880,10 @@
15726
15880
  subscription_id: subscription.id,
15727
15881
  data,
15728
15882
  };
15729
- this.session.sendFireAndForget(postMessage);
15883
+ this.session.sendFireAndForget(postMessage)
15884
+ .catch((err) => {
15885
+ this.logger.warn(`Failed to send post message for subscription ${subscription.id}: ${JSON.stringify(err)}`);
15886
+ });
15730
15887
  }
15731
15888
  closeSingleSubscription(streamingMethod, subscription) {
15732
15889
  if (streamingMethod.protocolState.subscriptionsMap) {
@@ -15737,7 +15894,10 @@
15737
15894
  subscription_id: subscription.id,
15738
15895
  reason: "Server dropping a single subscription",
15739
15896
  };
15740
- this.session.sendFireAndForget(dropSubscriptionMessage);
15897
+ this.session.sendFireAndForget(dropSubscriptionMessage)
15898
+ .catch((err) => {
15899
+ this.logger.warn(`Failed to send drop-subscription message for subscription ${subscription.id}: ${JSON.stringify(err)}`);
15900
+ });
15741
15901
  subscription.instance;
15742
15902
  this.callbacks.execute(SUBSCRIPTION_REMOVED, subscription, streamingMethod);
15743
15903
  }
@@ -15765,7 +15925,10 @@
15765
15925
  subscription_id: subscription.id,
15766
15926
  reason: "Server dropping all subscriptions on stream_id: " + subscription.streamId,
15767
15927
  };
15768
- this.session.sendFireAndForget(drop);
15928
+ this.session.sendFireAndForget(drop)
15929
+ .catch((err) => {
15930
+ this.logger.warn(`Failed to send drop-subscription message for subscription ${subscription.id}: ${JSON.stringify(err)}`);
15931
+ });
15769
15932
  });
15770
15933
  }
15771
15934
  getSubscriptionList(streamingMethod, branchKey) {
@@ -15874,7 +16037,10 @@
15874
16037
  reason,
15875
16038
  request_id: subscriptionId,
15876
16039
  };
15877
- this.session.sendFireAndForget(errorMessage);
16040
+ this.session.sendFireAndForget(errorMessage)
16041
+ .catch((err) => {
16042
+ this.logger.warn(`Failed to send subscription failed message for subscription ${subscriptionId}: ${JSON.stringify(err)}`);
16043
+ });
15878
16044
  }
15879
16045
  getStreamId(streamingMethod, branchKey) {
15880
16046
  if (typeof branchKey !== "string") {
@@ -15907,7 +16073,7 @@
15907
16073
  this.clientRepository = clientRepository;
15908
16074
  this.serverRepository = serverRepository;
15909
16075
  this.logger = logger;
15910
- this.streaming = new ServerStreaming(session, clientRepository, serverRepository);
16076
+ this.streaming = new ServerStreaming(session, clientRepository, serverRepository, logger.subLogger("streaming"));
15911
16077
  this.session.on("invoke", (msg) => this.handleInvokeMessage(msg));
15912
16078
  }
15913
16079
  createStream(repoMethod) {
@@ -15966,7 +16132,10 @@
15966
16132
  request_id: undefined,
15967
16133
  };
15968
16134
  }
15969
- this.session.sendFireAndForget(msg);
16135
+ this.session.sendFireAndForget(msg)
16136
+ .catch((error => {
16137
+ this.logger.warn(`Failed to send method invocation result for method ${method.definition.name} invocation ${invocationId} - ${JSON.stringify(error)}`);
16138
+ }));
15970
16139
  }
15971
16140
  async unregister(method) {
15972
16141
  const msg = {
@@ -16426,6 +16595,8 @@
16426
16595
  subscription_id: server.subscriptionId,
16427
16596
  reason_uri: "",
16428
16597
  reason: ON_CLOSE_MSG_CLIENT_INIT,
16598
+ }).catch((err) => {
16599
+ this.logger.warn(`Error sending unsubscribe for subscription id ${server.subscriptionId}: ${JSON.stringify(err)}`);
16429
16600
  });
16430
16601
  delete this.subscriptionIdToLocalKeyMap[server.subscriptionId];
16431
16602
  });
@@ -16765,7 +16936,10 @@
16765
16936
  routing_key: routingKey,
16766
16937
  target_identity: target
16767
16938
  });
16768
- this.session.send(args);
16939
+ this.session.send(args)
16940
+ .catch((err) => {
16941
+ this.logger.error(`Failed to publish message to topic ${topic} with routing key ${routingKey} for ${JSON.stringify(target)}: ${JSON.stringify(err)}`);
16942
+ });
16769
16943
  };
16770
16944
  subscribe = (topic, callback, options) => {
16771
16945
  return new Promise((resolve, reject) => {
@@ -16783,8 +16957,12 @@
16783
16957
  this.subscriptions.push({ subscription_id, topic, callback, source: target });
16784
16958
  resolve({
16785
16959
  unsubscribe: () => {
16786
- this.session.send({ type: "unsubscribe", subscription_id, peer_id: this.peerId });
16787
- this.subscriptions = this.subscriptions.filter((s) => s.subscription_id !== subscription_id);
16960
+ this.session.send({ type: "unsubscribe", subscription_id, peer_id: this.peerId })
16961
+ .then(() => {
16962
+ this.subscriptions = this.subscriptions.filter((s) => s.subscription_id !== subscription_id);
16963
+ }).catch((err) => {
16964
+ this.logger.warn(`Failed to send unsubscribe request for ${subscription_id}: ${JSON.stringify(err)}`);
16965
+ });
16788
16966
  return Promise.resolve();
16789
16967
  }
16790
16968
  });
@@ -16982,10 +17160,12 @@
16982
17160
  connection: _connection,
16983
17161
  logger: _logger.subLogger("contexts"),
16984
17162
  trackAllContexts: typeof internalConfig.contexts === "object" ? internalConfig.contexts.trackAllContexts : false,
16985
- reAnnounceKnownContexts: typeof internalConfig.contexts === "object" ? internalConfig.contexts.reAnnounceKnownContexts : false
17163
+ reAnnounceKnownContexts: typeof internalConfig.contexts === "object" ? internalConfig.contexts.reAnnounceKnownContexts : false,
17164
+ subscribeOnGet: typeof internalConfig.contexts === "object" ? internalConfig.contexts.subscribeOnGet : true,
17165
+ subscribeOnUpdate: typeof internalConfig.contexts === "object" ? internalConfig.contexts.subscribeOnUpdate : true,
17166
+ onlyReAnnounceSubscribedContexts: typeof internalConfig.contexts === "object" ? internalConfig.contexts.onlyReAnnounceSubscribedContexts : true
16986
17167
  });
16987
17168
  registerLib("contexts", _contexts, initTimer);
16988
- return _contexts;
16989
17169
  }
16990
17170
  else {
16991
17171
  const replayer = _connection.replayer;
@@ -16993,6 +17173,7 @@
16993
17173
  replayer.drain(ContextMessageReplaySpec.name);
16994
17174
  }
16995
17175
  }
17176
+ return Promise.resolve();
16996
17177
  }
16997
17178
  async function setupBus() {
16998
17179
  if (!internalConfig.bus) {