@steve31415/baselib 3.60.0 → 3.60.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -200,6 +200,13 @@ export declare class SyncClient<B, C extends EventBody, S extends EventBody, Sum
200
200
  private readonly hub;
201
201
  /** The live hub socket answered our `connect`. */
202
202
  private hubAcked;
203
+ /** Counts acks: a catch-up establishes only if it began under the current one. */
204
+ private ackGen;
205
+ /** When recent quiet hub closes happened (wall clock): a burst is not quiet. */
206
+ private quietHubCloses;
207
+ /** The last POST failed and its edits are still unsettled: reads alone do
208
+ * not make the page live or re-establish it. */
209
+ private postFailing;
203
210
  private hubLastHeardAt;
204
211
  private hubAwaitingPong;
205
212
  /** The last app request (POST or catch-up) succeeded; the bootstrap counts. */
@@ -384,7 +391,15 @@ export declare class SyncClient<B, C extends EventBody, S extends EventBody, Sum
384
391
  * `connect` and the last app request succeeded (a pong overdue replaces
385
392
  * the socket, so an open one has been heard from recently). */
386
393
  private isLive;
387
- private isQuietHubClose;
394
+ /** Hub mode: is this close a quiet reconnect? 1012, 1013 or 4408 on a
395
+ * socket the hub had acked, and fewer than HUB_QUIET_CLOSE_BURST such
396
+ * closes in the last minute; anything else takes the outage path. */
397
+ private takeQuietHubClose;
398
+ /** The ack a catch-up began under, or -1 when the hub socket was not acked. */
399
+ private currentAckGen;
400
+ /** Established needs a complete catch-up that began under the current ack
401
+ * (review 3.60.1, finding 3). */
402
+ private establishesUnder;
388
403
  /** Hub mode's state: live as `connected`/`syncing`; otherwise a countdown
389
404
  * to whichever ladder (hub socket or app request) retries first; otherwise
390
405
  * `connecting`, or `disconnected` once something has failed. */
@@ -405,7 +420,13 @@ export declare class SyncClient<B, C extends EventBody, S extends EventBody, Sum
405
420
  * socket's state; any successful app request restarts the wait. */
406
421
  private armFloor;
407
422
  private cancelFloor;
423
+ /** The app answered. While a failed POST's edits are still unsettled,
424
+ * reads alone change nothing but the floor: the POST's ladder stays in
425
+ * charge, and the page is neither live nor re-established (review
426
+ * 3.60.1, findings 2 and 5). Otherwise the ladder resets, a complete
427
+ * catch-up under the current ack establishes, and unsettled edits post. */
408
428
  private appSucceeded;
429
+ private postFailed;
409
430
  /** A POST or catch-up got no usable answer: the outage starts (if it had
410
431
  * not), and a visible page retries on the app-request ladder whatever the
411
432
  * hub socket's state. An expired session halts instead. */
@@ -57,6 +57,17 @@ const SOCKET_OPEN = 1;
57
57
  /** Outage logs' `closeCode` when a failed app request, not a socket close,
58
58
  * began the outage (hub mode). */
59
59
  const APP_REQUEST_FAILED = 0;
60
+ /** Hub mode: at most this many quiet reconnects (1012/1013/4408 on an acked
61
+ * socket) per window; more take the ladder. The hub's own closes come at
62
+ * most every 180-300 s per socket. */
63
+ const HUB_QUIET_CLOSE_BURST = 3;
64
+ const HUB_QUIET_CLOSE_WINDOW_MS = 60_000;
65
+ function isEventsResponse(value) {
66
+ if (value === null || typeof value !== 'object')
67
+ return false;
68
+ const { outcomes, events } = value;
69
+ return Array.isArray(outcomes) && (events === undefined || Array.isArray(events));
70
+ }
60
71
  function messageType(raw) {
61
72
  try {
62
73
  return JSON.parse(raw)?.type;
@@ -160,6 +171,13 @@ export class SyncClient {
160
171
  hub;
161
172
  /** The live hub socket answered our `connect`. */
162
173
  hubAcked = false;
174
+ /** Counts acks: a catch-up establishes only if it began under the current one. */
175
+ ackGen = 0;
176
+ /** When recent quiet hub closes happened (wall clock): a burst is not quiet. */
177
+ quietHubCloses = [];
178
+ /** The last POST failed and its edits are still unsettled: reads alone do
179
+ * not make the page live or re-establish it. */
180
+ postFailing = false;
163
181
  hubLastHeardAt = 0;
164
182
  hubAwaitingPong = false;
165
183
  /** The last app request (POST or catch-up) succeeded; the bootstrap counts. */
@@ -748,6 +766,7 @@ export class SyncClient {
748
766
  return;
749
767
  this.clearConnectionTimers();
750
768
  this.socket = null;
769
+ const wasAcked = this.hubAcked;
751
770
  this.hubAcked = false;
752
771
  if (this.halted || this.disposed)
753
772
  return;
@@ -776,12 +795,15 @@ export class SyncClient {
776
795
  // on a handshake begun for a handover.
777
796
  const rolling = this.candidate !== null;
778
797
  this.dropCandidate();
779
- if (event.code === CLOSE_SERVICE_RESTART || this.isQuietHubClose(event.code)) {
798
+ if (this.hub ? this.takeQuietHubClose(event.code, wasAcked) : event.code === CLOSE_SERVICE_RESTART) {
780
799
  // The server's planned close (its age cap: a tab whose own rollover
781
800
  // didn't run, such as a frozen one): reconnect at once, as after our
782
801
  // own rollover, with no outage and no ladder step. A failure of that
783
802
  // reconnect is an ordinary outage. The hub's 1013 (its auth check
784
- // was unavailable) and 4408 (it heard nothing for 180 s) are the same.
803
+ // was unavailable) and 4408 (it heard nothing for 180 s) are the
804
+ // same, but only for a socket the hub had acked, and not in a burst:
805
+ // the hub refuses with 1013 before acking while its auth is down,
806
+ // and that must back off on the ladder (review 3.60.1, finding 1).
785
807
  this.options.logger.info('ws closed by server', { closeCode: event.code, openForMs, rolling });
786
808
  this.connectNow();
787
809
  return;
@@ -1071,6 +1093,7 @@ export class SyncClient {
1071
1093
  this.abortControllers.add(controller);
1072
1094
  const timeout = this.setTimer(() => controller.abort(), BACKGROUND_FETCH_TIMEOUT_MS);
1073
1095
  let ok = false;
1096
+ const ackGen = this.currentAckGen();
1074
1097
  try {
1075
1098
  const result = await this.options.fetchCatchup(this.options.store.currentSeq(), controller.signal);
1076
1099
  if (controller.signal.aborted || this.stopBeforeStoreMutation())
@@ -1081,15 +1104,18 @@ export class SyncClient {
1081
1104
  this.options.onBuildObserved?.(result.buildId);
1082
1105
  else if (kind === 'background')
1083
1106
  this.options.onBuildChanged?.();
1107
+ let complete = !result.reload;
1084
1108
  if (result.reload) {
1085
1109
  this.requestReload('server');
1086
1110
  }
1087
1111
  else {
1088
- for (const event of result.events)
1089
- this.handleServerEvent(event);
1112
+ for (const event of result.events) {
1113
+ if (!this.handleServerEvent(event))
1114
+ complete = false;
1115
+ }
1090
1116
  }
1091
1117
  if (this.hub)
1092
- this.appSucceeded();
1118
+ this.appSucceeded(this.establishesUnder(ackGen, complete));
1093
1119
  return true;
1094
1120
  }
1095
1121
  catch {
@@ -2010,8 +2036,29 @@ export class SyncClient {
2010
2036
  return false;
2011
2037
  return this.hub === null || (this.hubAcked && this.appOk);
2012
2038
  }
2013
- isQuietHubClose(code) {
2014
- return this.hub !== null && (code === CLOSE_TRY_AGAIN_LATER || code === CLOSE_HUB_IDLE);
2039
+ /** Hub mode: is this close a quiet reconnect? 1012, 1013 or 4408 on a
2040
+ * socket the hub had acked, and fewer than HUB_QUIET_CLOSE_BURST such
2041
+ * closes in the last minute; anything else takes the outage path. */
2042
+ takeQuietHubClose(code, wasAcked) {
2043
+ if (code !== CLOSE_SERVICE_RESTART && code !== CLOSE_TRY_AGAIN_LATER && code !== CLOSE_HUB_IDLE)
2044
+ return false;
2045
+ if (!wasAcked)
2046
+ return false;
2047
+ const now = this.now();
2048
+ this.quietHubCloses = this.quietHubCloses.filter((at) => at <= now && now - at < HUB_QUIET_CLOSE_WINDOW_MS);
2049
+ if (this.quietHubCloses.length >= HUB_QUIET_CLOSE_BURST)
2050
+ return false;
2051
+ this.quietHubCloses.push(now);
2052
+ return true;
2053
+ }
2054
+ /** The ack a catch-up began under, or -1 when the hub socket was not acked. */
2055
+ currentAckGen() {
2056
+ return this.hubAcked ? this.ackGen : -1;
2057
+ }
2058
+ /** Established needs a complete catch-up that began under the current ack
2059
+ * (review 3.60.1, finding 3). */
2060
+ establishesUnder(ackGen, complete) {
2061
+ return complete && ackGen !== -1 && ackGen === this.ackGen && this.hubAcked && this.socket?.readyState === SOCKET_OPEN;
2015
2062
  }
2016
2063
  /** Hub mode's state: live as `connected`/`syncing`; otherwise a countdown
2017
2064
  * to whichever ladder (hub socket or app request) retries first; otherwise
@@ -2026,7 +2073,9 @@ export class SyncClient {
2026
2073
  this.countdownTimer = null;
2027
2074
  }
2028
2075
  if (live) {
2029
- this.updateConnectedState();
2076
+ // A detected resync loop keeps its error state until it converges.
2077
+ if (!this.loopEscalated)
2078
+ this.updateConnectedState();
2030
2079
  return;
2031
2080
  }
2032
2081
  const pending = this.pendingCount();
@@ -2073,6 +2122,7 @@ export class SyncClient {
2073
2122
  if (this.hubAcked)
2074
2123
  return;
2075
2124
  this.hubAcked = true;
2125
+ this.ackGen++;
2076
2126
  this.refreshHubState();
2077
2127
  void this.runCatchup('connect');
2078
2128
  }
@@ -2127,15 +2177,32 @@ export class SyncClient {
2127
2177
  this.options.runtime.clearTimeout(this.floorTimer);
2128
2178
  this.floorTimer = null;
2129
2179
  }
2130
- appSucceeded() {
2180
+ /** The app answered. While a failed POST's edits are still unsettled,
2181
+ * reads alone change nothing but the floor: the POST's ladder stays in
2182
+ * charge, and the page is neither live nor re-established (review
2183
+ * 3.60.1, findings 2 and 5). Otherwise the ladder resets, a complete
2184
+ * catch-up under the current ack establishes, and unsettled edits post. */
2185
+ appSucceeded(establishes) {
2186
+ this.armFloor();
2187
+ if (this.postFailing && this.unsettledPending().length > 0) {
2188
+ this.scheduleAppRetry();
2189
+ this.refreshHubState();
2190
+ return;
2191
+ }
2192
+ this.postFailing = false;
2131
2193
  this.appOk = true;
2132
2194
  this.appAttempts = 0;
2133
2195
  this.cancelAppRetry();
2134
- this.armFloor();
2135
- if (this.hubAcked && this.socket?.readyState === SOCKET_OPEN)
2196
+ if (establishes)
2136
2197
  this.onSyncEstablished();
2137
2198
  else
2138
2199
  this.refreshHubState();
2200
+ if (this.unsettledPending().length > 0)
2201
+ this.kickPost();
2202
+ }
2203
+ postFailed() {
2204
+ this.postFailing = true;
2205
+ this.appFailed();
2139
2206
  }
2140
2207
  /** A POST or catch-up got no usable answer: the outage starts (if it had
2141
2208
  * not), and a visible page retries on the app-request ladder whatever the
@@ -2208,21 +2275,37 @@ export class SyncClient {
2208
2275
  return inFlight;
2209
2276
  }
2210
2277
  async postOnce(postEvents, events) {
2278
+ const ackGen = this.currentAckGen();
2211
2279
  let response;
2212
2280
  try {
2213
2281
  response = await this.withTimeout((signal) => postEvents({ clientGuid: this.options.clientGuid, events, lastSeq: this.options.store.currentSeq() }, signal));
2214
2282
  }
2215
2283
  catch {
2216
- this.appFailed();
2284
+ this.postFailed();
2217
2285
  return;
2218
2286
  }
2219
2287
  if (this.stopBeforeStoreMutation())
2220
2288
  return;
2221
- this.lastContactAt = this.now();
2222
- this.applyPostResponse(response);
2289
+ // A body that is not the response shape, or a store that throws applying
2290
+ // it, is a failed request: the ladder re-posts (review 3.60.1, finding 4).
2291
+ let complete;
2292
+ try {
2293
+ if (!isEventsResponse(response))
2294
+ throw new Error('response has no outcomes');
2295
+ complete = this.applyPostResponse(response);
2296
+ }
2297
+ catch (error) {
2298
+ if (this.stopBeforeStoreMutation())
2299
+ return;
2300
+ this.options.logger.error('sync post response unusable', { error });
2301
+ this.postFailed();
2302
+ return;
2303
+ }
2223
2304
  if (this.stopBeforeStoreMutation())
2224
2305
  return;
2225
- this.appSucceeded();
2306
+ this.lastContactAt = this.now();
2307
+ this.postFailing = false;
2308
+ this.appSucceeded(this.establishesUnder(ackGen, complete && response.currentSeq !== undefined));
2226
2309
  // An app answering in the old shape sent no frames: the echoes come by
2227
2310
  // catch-up, as for a same-origin POST.
2228
2311
  if (response.currentSeq === undefined && !response.reload)
@@ -2235,16 +2318,19 @@ export class SyncClient {
2235
2318
  * have moved it past them, review round 2 B1); rejections settle as on
2236
2319
  * the socket. */
2237
2320
  applyPostResponse(response) {
2321
+ let complete = !response.reload;
2238
2322
  if (response.reload) {
2239
2323
  this.requestReload('server');
2240
2324
  }
2241
2325
  else {
2242
- for (const event of response.events ?? [])
2243
- this.handleServerEvent(event);
2326
+ for (const event of response.events ?? []) {
2327
+ if (!this.handleServerEvent(event))
2328
+ complete = false;
2329
+ }
2244
2330
  }
2245
2331
  for (const outcome of response.outcomes) {
2246
2332
  if (this.stopBeforeStoreMutation())
2247
- return;
2333
+ return false;
2248
2334
  if (outcome.status === 'rejected') {
2249
2335
  this.handleRejection({
2250
2336
  type: 'rejection',
@@ -2254,9 +2340,12 @@ export class SyncClient {
2254
2340
  continue;
2255
2341
  }
2256
2342
  this.counters.httpPostedEvents++;
2257
- for (const frame of ('events' in outcome ? outcome.events : undefined) ?? [])
2258
- this.handleServerEvent(frame);
2343
+ for (const frame of ('events' in outcome ? outcome.events : undefined) ?? []) {
2344
+ if (!this.handleServerEvent(frame))
2345
+ complete = false;
2346
+ }
2259
2347
  }
2348
+ return complete;
2260
2349
  }
2261
2350
  detachSocket(socket) {
2262
2351
  socket.onopen = null;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@steve31415/baselib",
3
- "version": "3.60.0",
3
+ "version": "3.60.1",
4
4
  "description": "Plasticine new-world shared platform library: logging, auth, service-to-service auth, db, HTTP, sync, app updates",
5
5
  "type": "module",
6
6
  "license": "MIT",