@hyper-fetch/core 9.6.1 → 9.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (134) hide show
  1. package/__tests__/features/adapter/adapter.bindings.progress.spec.ts +120 -0
  2. package/__tests__/features/adapter/adapter.bindings.spec.ts +4 -6
  3. package/__tests__/features/adapter/adapter.defaults.spec.ts +87 -0
  4. package/__tests__/features/adapter/adapter.mapping.spec.ts +257 -0
  5. package/__tests__/features/cache/cache.lazy-storage.clear.spec.ts +145 -0
  6. package/__tests__/features/cache/cache.lazy-storage.resilience.spec.ts +667 -0
  7. package/__tests__/features/cache/cache.scoped-events.spec.ts +183 -0
  8. package/__tests__/features/cache/cache.semantics.spec.ts +785 -0
  9. package/__tests__/features/cache/cache.structural-sharing.spec.ts +565 -0
  10. package/__tests__/features/cache/cache.timing.spec.ts +448 -0
  11. package/__tests__/features/client/client.clear.spec.ts +313 -0
  12. package/__tests__/features/client/client.configuration.spec.ts +416 -0
  13. package/__tests__/features/client/client.hydration.round-trip.spec.ts +324 -0
  14. package/__tests__/features/client/client.interceptor.spec.ts +54 -45
  15. package/__tests__/features/client/client.interceptors.pipeline.spec.ts +599 -0
  16. package/__tests__/features/client/client.user-errors.spec.ts +220 -0
  17. package/__tests__/features/dispatcher/dispatcher.cleanup.spec.ts +534 -0
  18. package/__tests__/features/dispatcher/dispatcher.control.spec.ts +381 -0
  19. package/__tests__/features/dispatcher/dispatcher.modes.spec.ts +527 -0
  20. package/__tests__/features/dispatcher/dispatcher.offline.spec.ts +278 -0
  21. package/__tests__/features/dispatcher/dispatcher.queue.spec.ts +35 -12
  22. package/__tests__/features/dispatcher/dispatcher.reentrancy.spec.ts +309 -0
  23. package/__tests__/features/dispatcher/dispatcher.response-order.spec.ts +241 -0
  24. package/__tests__/features/dispatcher/dispatcher.retry-flow.spec.ts +554 -0
  25. package/__tests__/features/dispatcher/dispatcher.retry-removal.spec.ts +196 -0
  26. package/__tests__/features/dispatcher/dispatcher.retry.spec.ts +4 -3
  27. package/__tests__/features/http-adapter/http-adapter.e2e.spec.ts +917 -0
  28. package/__tests__/features/managers/app/app.manager.events.spec.ts +434 -0
  29. package/__tests__/features/managers/logger/logger.levels.spec.ts +199 -0
  30. package/__tests__/features/managers/request/request.manager.abort.spec.ts +449 -0
  31. package/__tests__/features/mocker/mocker.base.spec.ts +22 -3
  32. package/__tests__/features/mocker/mocker.errors.spec.ts +99 -0
  33. package/__tests__/features/mocker/mocker.outcomes.spec.ts +308 -0
  34. package/__tests__/features/optimistic/optimistic.concurrency.spec.ts +278 -0
  35. package/__tests__/features/optimistic/optimistic.helpers.spec.ts +307 -0
  36. package/__tests__/features/optimistic/optimistic.matrix.spec.ts +315 -0
  37. package/__tests__/features/optimistic/optimistic.races.spec.ts +270 -0
  38. package/__tests__/features/optimistic/optimistic.random.spec.ts +191 -0
  39. package/__tests__/features/optimistic/optimistic.rollback.spec.ts +1001 -0
  40. package/__tests__/features/optimistic/optimistic.typescript.spec.ts +196 -0
  41. package/__tests__/features/plugin/plugin.lifecycle.spec.ts +457 -0
  42. package/__tests__/features/request/request.async-mapper-removal.spec.ts +138 -0
  43. package/__tests__/features/request/request.immutability.spec.ts +259 -0
  44. package/__tests__/features/request/request.inference.spec.ts +269 -0
  45. package/__tests__/features/request/request.lifecycle.spec.ts +682 -0
  46. package/__tests__/features/request/request.optimistic-settlement.spec.ts +35 -17
  47. package/__tests__/features/request/request.optimistic.spec.ts +12 -1
  48. package/__tests__/features/request/request.values.spec.ts +408 -0
  49. package/__tests__/features/sdk/sdk.builder.spec.ts +304 -0
  50. package/__tests__/features/utils/emitter.listeners.spec.ts +202 -0
  51. package/__tests__/utils/controlled-adapter.utils.ts +119 -0
  52. package/__tests__/utils/fixtures.utils.ts +193 -0
  53. package/__tests__/utils/optimistic.utils.ts +124 -0
  54. package/dist/adapter/adapter.bindings.d.ts.map +1 -1
  55. package/dist/adapter/adapter.utils.d.ts.map +1 -1
  56. package/dist/cache/cache.d.ts +12 -1
  57. package/dist/cache/cache.d.ts.map +1 -1
  58. package/dist/cache/cache.events.d.ts +20 -6
  59. package/dist/cache/cache.events.d.ts.map +1 -1
  60. package/dist/cache/cache.utils.d.ts +1 -0
  61. package/dist/cache/cache.utils.d.ts.map +1 -1
  62. package/dist/client/client.d.ts +3 -3
  63. package/dist/client/client.d.ts.map +1 -1
  64. package/dist/client/client.utils.d.ts.map +1 -1
  65. package/dist/dispatcher/dispatcher.d.ts +26 -5
  66. package/dist/dispatcher/dispatcher.d.ts.map +1 -1
  67. package/dist/http-adapter/http-adapter.fetch.d.ts.map +1 -1
  68. package/dist/index.d.ts +1 -0
  69. package/dist/index.d.ts.map +1 -1
  70. package/dist/index.mjs +2787 -1893
  71. package/dist/index.mjs.map +1 -1
  72. package/dist/managers/app/app.manager.constants.d.ts.map +1 -1
  73. package/dist/managers/app/app.manager.d.ts +9 -0
  74. package/dist/managers/app/app.manager.d.ts.map +1 -1
  75. package/dist/managers/app/app.manager.utils.d.ts.map +1 -1
  76. package/dist/managers/logger/logger.manager.d.ts.map +1 -1
  77. package/dist/managers/request/request.manager.d.ts.map +1 -1
  78. package/dist/managers/request/request.manager.types.d.ts +2 -0
  79. package/dist/managers/request/request.manager.types.d.ts.map +1 -1
  80. package/dist/mocker/mocker.d.ts +1 -1
  81. package/dist/mocker/mocker.d.ts.map +1 -1
  82. package/dist/optimistic/index.d.ts +5 -0
  83. package/dist/optimistic/index.d.ts.map +1 -0
  84. package/dist/optimistic/optimistic.d.ts +67 -0
  85. package/dist/optimistic/optimistic.d.ts.map +1 -0
  86. package/dist/optimistic/optimistic.settlement.d.ts +60 -0
  87. package/dist/optimistic/optimistic.settlement.d.ts.map +1 -0
  88. package/dist/optimistic/optimistic.types.d.ts +109 -0
  89. package/dist/optimistic/optimistic.types.d.ts.map +1 -0
  90. package/dist/optimistic/optimistic.utils.d.ts +29 -0
  91. package/dist/optimistic/optimistic.utils.d.ts.map +1 -0
  92. package/dist/plugin/plugin.d.ts +2 -0
  93. package/dist/plugin/plugin.d.ts.map +1 -1
  94. package/dist/request/request.d.ts +14 -6
  95. package/dist/request/request.d.ts.map +1 -1
  96. package/dist/request/request.types.d.ts +40 -1
  97. package/dist/request/request.types.d.ts.map +1 -1
  98. package/dist/request/request.utils.d.ts.map +1 -1
  99. package/dist/utils/emitter.utils.d.ts.map +1 -1
  100. package/dist/utils/error.utils.d.ts +17 -0
  101. package/dist/utils/error.utils.d.ts.map +1 -0
  102. package/dist/utils/index.d.ts +1 -0
  103. package/dist/utils/index.d.ts.map +1 -1
  104. package/package.json +1 -1
  105. package/src/adapter/adapter.bindings.ts +46 -18
  106. package/src/adapter/adapter.utils.ts +47 -7
  107. package/src/cache/cache.events.ts +24 -8
  108. package/src/cache/cache.ts +110 -21
  109. package/src/cache/cache.utils.ts +33 -10
  110. package/src/client/client.ts +101 -7
  111. package/src/client/client.utils.ts +10 -4
  112. package/src/dispatcher/dispatcher.ts +285 -132
  113. package/src/http-adapter/http-adapter.fetch.ts +15 -3
  114. package/src/index.ts +4 -0
  115. package/src/managers/app/app.manager.constants.ts +12 -1
  116. package/src/managers/app/app.manager.ts +43 -23
  117. package/src/managers/app/app.manager.utils.ts +8 -4
  118. package/src/managers/logger/logger.manager.ts +21 -8
  119. package/src/managers/request/request.manager.ts +7 -1
  120. package/src/managers/request/request.manager.types.ts +2 -0
  121. package/src/mocker/mocker.ts +14 -11
  122. package/src/optimistic/index.ts +4 -0
  123. package/src/optimistic/optimistic.settlement.ts +406 -0
  124. package/src/optimistic/optimistic.ts +162 -0
  125. package/src/optimistic/optimistic.types.ts +175 -0
  126. package/src/optimistic/optimistic.utils.ts +112 -0
  127. package/src/plugin/plugin.ts +6 -0
  128. package/src/request/request.ts +50 -28
  129. package/src/request/request.types.ts +41 -1
  130. package/src/request/request.utils.ts +51 -66
  131. package/src/utils/emitter.utils.ts +9 -2
  132. package/src/utils/error.utils.ts +29 -0
  133. package/src/utils/index.ts +1 -0
  134. package/tsconfig.json +2 -0
@@ -1,3 +1,4 @@
1
+ /* eslint-disable max-lines */
1
2
  import type { AdapterInstance, RequestResponseType } from "adapter";
2
3
  import { getErrorMessage } from "adapter";
3
4
  import type { ClientInstance } from "client";
@@ -11,9 +12,10 @@ import type {
11
12
  } from "dispatcher";
12
13
  import { getRequestType, canRetryRequest, getDispatcherEvents, DispatcherMode } from "dispatcher";
13
14
  import type { ResponseDetailsType, LoggerMethods } from "managers";
15
+ import { isStaleOptimisticResponse } from "optimistic/optimistic.settlement";
14
16
  import type { RequestInstance, RequestJSON } from "request";
15
17
  import { Request, scopeKey } from "request";
16
- import { EventEmitter } from "utils";
18
+ import { EventEmitter, throwOutsideLifecycle } from "utils";
17
19
 
18
20
  /**
19
21
  * Dispatcher controls and manages the requests that are going to be executed with adapter. It manages them based on the options provided with request.
@@ -27,7 +29,14 @@ export class Dispatcher<Adapter extends AdapterInstance> {
27
29
 
28
30
  private requestCount = new Map<string, number>();
29
31
  private runningRequests = new Map<string, RunningRequestValueType[]>();
32
+ /** Failed requests waiting for their next attempt, by requestId */
30
33
  private retryTimers = new Map<string, ReturnType<typeof setTimeout>>();
34
+ /** Requests which got their response and are still in the queue while their listeners run */
35
+ private answeredRequests = new Set<string>();
36
+ /** Order in which the requests were sent - responses can come back in another one */
37
+ private sentCount = 0;
38
+ /** Cache element (by its storage key) to the order number of the request whose data it holds */
39
+ private cachedOrder = new Map<string, number>();
31
40
 
32
41
  private logger: LoggerMethods;
33
42
  private client: ClientInstance<{ adapter: Adapter }>;
@@ -195,6 +204,17 @@ export class Dispatcher<Adapter extends AdapterInstance> {
195
204
  * Clear requests from queue cache
196
205
  */
197
206
  clearQueue = (queryKey: string) => {
207
+ return this.removeQueueItems(
208
+ queryKey,
209
+ this.getRunningRequests(queryKey).map((running) => running.requestId),
210
+ );
211
+ };
212
+
213
+ /**
214
+ * Empty the queue. Requests listed in `answeredIds` are running or were just canceled, so they still report
215
+ * their own response. All the others would never be heard of again - those are reported as removed.
216
+ */
217
+ private removeQueueItems = (queryKey: string, answeredIds: string[]) => {
198
218
  const queue = this.getQueue(queryKey);
199
219
  const newQueue = { queryKey, requests: [], stopped: queue.stopped };
200
220
  this.storage.set(queryKey, newQueue);
@@ -202,13 +222,42 @@ export class Dispatcher<Adapter extends AdapterInstance> {
202
222
  // Emit Queue Changes
203
223
  this.client.triggerPlugins("onDispatcherQueueCleared", { dispatcher: this, queue: newQueue });
204
224
  this.events.emitQueueChanged(newQueue);
225
+ this.emitRemovedItems(queue.requests, answeredIds);
205
226
  this.events.emitDrained(newQueue);
206
227
 
207
- this.removeWaitingRetries(queue);
208
-
209
228
  return newQueue;
210
229
  };
211
230
 
231
+ private emitRemovedItems = (items: ResolvedQueueItemType[], answeredIds: string[]) => {
232
+ items.forEach((item) => {
233
+ this.cancelRetry(item.requestId);
234
+
235
+ if (!answeredIds.includes(item.requestId)) {
236
+ this.client.requestManager.events.emitRemove({
237
+ requestId: item.requestId,
238
+ request: item.request,
239
+ resolved: item.resolved,
240
+ });
241
+ }
242
+ });
243
+ };
244
+
245
+ /**
246
+ * A request can be sent when it is not in flight, not held by `stopRequest`, not waiting for its retry,
247
+ * not just answered and - for the requests kept for later with the `offline` option - when there is a connection
248
+ */
249
+ private canPerformRequest = (item: ResolvedQueueItemType, runningIds: Set<string>) => {
250
+ const isWaitingForNetwork = !this.client.appManager.isOnline && item.request.offline;
251
+
252
+ return (
253
+ !item.stopped &&
254
+ !isWaitingForNetwork &&
255
+ !this.retryTimers.has(item.requestId) &&
256
+ !this.answeredRequests.has(item.requestId) &&
257
+ !runningIds.has(item.requestId)
258
+ );
259
+ };
260
+
212
261
  /**
213
262
  * Method used to flush the queue requests
214
263
  */
@@ -225,15 +274,20 @@ export class Dispatcher<Adapter extends AdapterInstance> {
225
274
 
226
275
  // When there are no requests to flush, when its stopped, there is running request
227
276
  // or there is no request to trigger - we don't want to perform actions
228
- if (isStopped || isOffline || isEmpty) {
277
+ if (isStopped || isEmpty) {
229
278
  this.logger.debug({ title: "Skipping queue trigger", type: "system", extra: { isStopped, isOffline, isEmpty } });
230
279
  } else if (isConcurrent) {
280
+ // Collected once - looking for every request in the list of the running ones gets slow with a long queue
281
+ const runningIds = new Set(runningRequests.map((running) => running.requestId));
231
282
  queue.requests.forEach((element) => {
232
- if (!this.hasRunningRequest(queryKey, element.requestId)) {
283
+ if (this.canPerformRequest(element, runningIds)) {
284
+ runningIds.add(element.requestId);
233
285
  this.performRequest(element);
234
286
  }
235
287
  });
236
- } else if (isInactive) {
288
+ }
289
+ // One by one - the first request holds the queue also while it waits for its retry or for the network
290
+ else if (isInactive && this.canPerformRequest(queueItem, new Set())) {
237
291
  await this.performRequest(queueItem);
238
292
  this.flushQueue(queryKey);
239
293
  }
@@ -260,13 +314,18 @@ export class Dispatcher<Adapter extends AdapterInstance> {
260
314
  */
261
315
  clear = () => {
262
316
  const keys = this.getQueuesKeys();
263
- const queues = keys.map((queryKey) => this.getQueue(queryKey));
317
+ // Running requests are canceled and report it on their own, the waiting ones are reported as removed
318
+ const removed = keys.map((queryKey) => ({
319
+ items: this.getQueue(queryKey).requests,
320
+ answeredIds: this.getRunningRequests(queryKey).map((running) => running.requestId),
321
+ }));
264
322
  keys.forEach((queryKey) => this.cancelRunningRequests(queryKey));
265
323
 
266
324
  [...this.runningRequests.keys()].forEach((queryKey) => this.setRunningRequests(queryKey, []));
267
325
  this.runningRequests.clear();
326
+ this.cachedOrder.clear();
268
327
  this.storage.clear();
269
- queues.forEach((queue) => this.removeWaitingRetries(queue));
328
+ removed.forEach(({ items, answeredIds }) => this.emitRemovedItems(items, answeredIds));
270
329
  this.client.triggerPlugins("onDispatcherCleared", { dispatcher: this });
271
330
  };
272
331
 
@@ -283,18 +342,6 @@ export class Dispatcher<Adapter extends AdapterInstance> {
283
342
  return this.retryTimers.delete(requestId);
284
343
  };
285
344
 
286
- /**
287
- * Clearing does not announce removed items. Requests waiting for a retry have no attempt left to end with,
288
- * so without this event their listeners would never be notified.
289
- */
290
- private removeWaitingRetries = (queue: ResolvedQueueDataType) => {
291
- queue.requests.forEach(({ requestId, request, resolved }) => {
292
- if (this.cancelRetry(requestId)) {
293
- this.client.requestManager.events.emitRemove({ requestId, request, resolved });
294
- }
295
- });
296
- };
297
-
298
345
  // *********************************************************************
299
346
  // *********************************************************************
300
347
  // Requests
@@ -363,7 +410,12 @@ export class Dispatcher<Adapter extends AdapterInstance> {
363
410
  */
364
411
  private setRunningRequests = (queryKey: string, runningRequests: RunningRequestValueType[]) => {
365
412
  const previousRequests = this.getRunningRequests(queryKey);
366
- this.runningRequests.set(queryKey, runningRequests);
413
+ if (runningRequests.length > 0) {
414
+ this.runningRequests.set(queryKey, runningRequests);
415
+ } else {
416
+ // Do not keep an empty list for every queryKey that was ever used
417
+ this.runningRequests.delete(queryKey);
418
+ }
367
419
  if (
368
420
  previousRequests.length !== runningRequests.length ||
369
421
  previousRequests.some((req, i) => req !== runningRequests[i])
@@ -503,8 +555,9 @@ export class Dispatcher<Adapter extends AdapterInstance> {
503
555
  }
504
556
  case DispatcherMode.PREVIOUS_CANCELED: {
505
557
  // Cancel all previous on-going requests
558
+ const canceledIds = this.getRunningRequests(queryKey).map((running) => running.requestId);
506
559
  this.cancelRunningRequests(queryKey);
507
- this.clearQueue(queryKey);
560
+ this.removeQueueItems(queryKey, canceledIds);
508
561
  this.addQueueItem(queryKey, storageItem);
509
562
  this.flushQueue(queryKey);
510
563
  return requestId;
@@ -534,12 +587,13 @@ export class Dispatcher<Adapter extends AdapterInstance> {
534
587
  const queue = this.getQueue(queryKey);
535
588
  const queueItem = queue.requests.find((req) => req.requestId === requestId);
536
589
 
537
- if (!queueItem) {return;}
538
-
539
- this.cancelRetry(requestId);
590
+ if (!queueItem) {
591
+ return;
592
+ }
540
593
 
541
594
  queue.requests = queue.requests.filter((req) => req.requestId !== requestId);
542
595
  this.storage.set(queryKey, queue);
596
+ this.cancelRetry(requestId);
543
597
 
544
598
  // Clean controllers
545
599
  if (this.hasRunningRequest(queryKey, requestId)) {
@@ -565,6 +619,34 @@ export class Dispatcher<Adapter extends AdapterInstance> {
565
619
  return queue;
566
620
  };
567
621
 
622
+ /**
623
+ * Save the number of used attempts on the queued request
624
+ */
625
+ private setQueueItemRetries = (queryKey: string, requestId: string, retries: number) => {
626
+ const queue = this.getQueue(queryKey);
627
+ const queueItem = queue.requests.find((item) => item.requestId === requestId);
628
+
629
+ if (queueItem) {
630
+ queueItem.retries = retries;
631
+ this.storage.set(queryKey, queue);
632
+ }
633
+ };
634
+
635
+ /**
636
+ * The `retryOnError` callback belongs to the user - when it throws, the request is not retried
637
+ */
638
+ private getShouldRetryOnError = (request: RequestInstance, response: RequestResponseType<any>) => {
639
+ if (!request.retryOnError) {
640
+ return true;
641
+ }
642
+ try {
643
+ return !!request.retryOnError(response);
644
+ } catch (error) {
645
+ this.logger.error({ title: "The retryOnError callback failed", type: "system", extra: { error, request } });
646
+ return false;
647
+ }
648
+ };
649
+
568
650
  /**
569
651
  * Request can run for some time, once it's done, we have to check if it's successful or if it was aborted
570
652
  * It can be different once the previous call was set as cancelled and removed from queue before this request got resolved
@@ -595,6 +677,8 @@ export class Dispatcher<Adapter extends AdapterInstance> {
595
677
 
596
678
  // Additionally keep the running request to possibly abort it later
597
679
  const runningRequest = this.addRunningRequest(queryKey, requestId, request);
680
+ this.sentCount += 1;
681
+ const sentOrder = this.sentCount;
598
682
 
599
683
  // Propagate the loading to all connected hooks
600
684
  requestManager.events.emitLoading({
@@ -627,128 +711,197 @@ export class Dispatcher<Adapter extends AdapterInstance> {
627
711
  // Remove running request, must be called after isCancelled
628
712
  this.deleteRunningRequest(queryKey, requestId);
629
713
 
630
- const shouldRetryOnError = response.success || !canRetry || !request.retryOnError || request.retryOnError(response);
631
- const willRetry = !response.success && canRetry && shouldRetryOnError && !isCanceled && !isOfflineResponseStatus;
632
-
633
- const requestDetails: ResponseDetailsType = {
634
- isCanceled,
635
- isOffline: isOfflineResponseStatus,
636
- retries: storageItem.retries,
637
- willRetry,
638
- addedTimestamp: storageItem.timestamp,
639
- triggerTimestamp: runningRequest.timestamp,
640
- requestTimestamp: response.requestTimestamp,
641
- responseTimestamp: response.responseTimestamp,
642
- };
643
-
644
- // Global response emitter to handle request execution
645
- requestManager.events.emitResponse({ request, requestId, response, details: requestDetails });
646
-
647
- // Turn off loading
648
- requestManager.events.emitLoading({
649
- request,
650
- requestId,
651
- loading: false,
652
- isRetry: !!storageItem.retries,
653
- isOffline,
654
- });
714
+ // The request is no longer running, but it stays in the queue until its response is handled below. Listeners
715
+ // of the response can add requests to this queue - flushing it must not send the answered request again.
716
+ this.answeredRequests.add(requestId);
717
+ try {
718
+ // A request removed from the queue while it was running (cleared queue) has nothing left to retry
719
+ const isQueued = !!this.getRequest(queryKey, requestId);
720
+ const canRetryResponse = !response.success && canRetry && isQueued && !isCanceled && !isOfflineResponseStatus;
721
+ const willRetry = canRetryResponse && this.getShouldRetryOnError(request, response);
722
+
723
+ const requestDetails: ResponseDetailsType = {
724
+ isCanceled,
725
+ isOffline: isOfflineResponseStatus,
726
+ retries: storageItem.retries,
727
+ willRetry,
728
+ addedTimestamp: storageItem.timestamp,
729
+ triggerTimestamp: runningRequest.timestamp,
730
+ requestTimestamp: response.requestTimestamp,
731
+ responseTimestamp: response.responseTimestamp,
732
+ };
733
+
734
+ // A throwing listener must not leave the request in the queue forever (and block all the queued ones behind it)
735
+ const notify = (callback: VoidFunction) => {
736
+ try {
737
+ callback();
738
+ } catch (error) {
739
+ this.logger.error({
740
+ title: "Response listener failed",
741
+ type: "system",
742
+ extra: { error, request, requestId },
743
+ });
744
+ throwOutsideLifecycle(error);
745
+ }
746
+ };
655
747
 
656
- // Cache event to emit the data inside and store it
657
- cache.set(request, { ...response, ...requestDetails });
658
- this.logger.debug({
659
- title: "Dispatcher processing response",
660
- type: "system",
661
- extra: { requestId, request, response, details: requestDetails },
662
- });
748
+ // Global response emitter to handle request execution
749
+ notify(() => requestManager.events.emitResponse({ request, requestId, response, details: requestDetails }));
663
750
 
664
- // On cancelled
665
- if (isCanceled) {
666
- const queue = this.getQueue(queryKey);
667
- const queueItem = queue.requests.find((req) => req.requestId === requestId);
751
+ // Turn off loading
752
+ notify(() =>
753
+ requestManager.events.emitLoading({
754
+ request,
755
+ requestId,
756
+ loading: false,
757
+ isRetry: !!storageItem.retries,
758
+ isOffline,
759
+ }),
760
+ );
761
+
762
+ // Requests of one cache key can answer in another order than they were sent. Once the data of a request is in
763
+ // the cache, a response of a request sent before it is outdated - it must not replace that data.
764
+ const storageKey = scopeKey(request.cacheKey, scope);
765
+ const isOutdated = (this.cachedOrder.get(storageKey) ?? 0) > sentOrder;
766
+ // A pending optimistic change on the key makes the response stale - the refresh after it supplies current data.
767
+ // Always checked, so a fetch marked as stale is released even when its response is skipped for another reason.
768
+ let isStaleOptimistic = false;
769
+ notify(() => {
770
+ isStaleOptimistic = isStaleOptimisticResponse(this.client, request, requestId);
771
+ });
668
772
 
669
- // do not remove cancelled request as it may be result of manual queue pause
670
- // if abort was done without stop action we can remove request
671
- if (!queue.stopped && !queueItem?.stopped) {
672
- this.logger.debug({ title: "Request paused", type: "system", extra: { response, requestDetails, request } });
673
- return this.delete(queryKey, requestId, abortKey);
773
+ if (isOutdated) {
774
+ this.logger.debug({
775
+ title: "Response of a request sent before the cached one, skipping the cache",
776
+ type: "system",
777
+ extra: { requestId, request, response },
778
+ });
779
+ } else if (isStaleOptimistic) {
780
+ this.logger.debug({
781
+ title: "Response started before a pending optimistic change settled, skipping the cache",
782
+ type: "system",
783
+ extra: { requestId, request, response },
784
+ });
785
+ } else {
786
+ if (response.success) {
787
+ this.cachedOrder.set(storageKey, sentOrder);
788
+ }
789
+ // Cache event to emit the data inside and store it
790
+ notify(() => cache.set(request, { ...response, ...requestDetails }));
674
791
  }
675
- return this.logger.debug({
676
- title: "Request canceled",
792
+ this.logger.debug({
793
+ title: "Dispatcher processing response",
677
794
  type: "system",
678
- extra: { response, requestDetails, request },
795
+ extra: { requestId, request, response, details: requestDetails },
679
796
  });
680
- }
681
- // On offline
682
- if (!response.success && isOfflineResponseStatus) {
683
- // if we don't want to keep offline request - just delete them
684
- if (!offline) {
685
- this.logger.warning({
686
- title: "Removing non-offline request",
797
+
798
+ // On cancelled
799
+ if (isCanceled) {
800
+ const queue = this.getQueue(queryKey);
801
+ const queueItem = queue.requests.find((req) => req.requestId === requestId);
802
+
803
+ // do not remove cancelled request as it may be result of manual queue pause
804
+ // if abort was done without stop action we can remove request
805
+ if (!queue.stopped && !queueItem?.stopped) {
806
+ this.logger.debug({ title: "Request paused", type: "system", extra: { response, requestDetails, request } });
807
+ return this.delete(queryKey, requestId, abortKey);
808
+ }
809
+ return this.logger.debug({
810
+ title: "Request canceled",
687
811
  type: "system",
688
812
  extra: { response, requestDetails, request },
689
813
  });
690
- return this.delete(queryKey, requestId, abortKey);
691
814
  }
692
- // do not remove request from store as we want to re-send it later
693
- return this.logger.debug({
694
- title: "Awaiting for network restoration",
695
- type: "system",
696
- extra: { response, requestDetails, request },
697
- });
698
- }
699
- // On success
700
- if (response.success) {
701
- this.delete(queryKey, requestId, abortKey);
702
- return this.logger.debug({
703
- title: "Successful response, removing request from queue.",
704
- type: "system",
705
- extra: {
706
- response,
707
- requestDetails,
708
- request,
709
- },
710
- });
711
- }
712
- // On retry
713
- if (willRetry) {
714
- this.logger.debug({ title: "Waiting for retry", type: "system", extra: { response, requestDetails, request } });
715
- // Flushing the queue during the wait sends the request earlier - only the latest failure schedules the retry
716
- this.cancelRetry(requestId);
717
- // Perform retry once request is failed
718
- const retryTimer = setTimeout(() => {
719
- this.retryTimers.delete(requestId);
720
-
721
- // Dispatcher methods cancel this timer, so the item was taken directly from the storage and nobody announced it
722
- if (!this.getRequest(queryKey, requestId)) {
723
- this.logger.debug({
724
- title: "Request no longer in queue, skipping retry",
725
- type: "request",
726
- extra: { response, requestDetails, request, requestId },
815
+ // On offline
816
+ if (!response.success && isOfflineResponseStatus) {
817
+ // if we don't want to keep offline request - just delete them
818
+ if (!offline) {
819
+ this.logger.warning({
820
+ title: "Removing non-offline request",
821
+ type: "system",
822
+ extra: { response, requestDetails, request },
727
823
  });
728
- requestManager.events.emitRemove({ requestId, request, resolved: storageItem.resolved });
729
- return;
824
+ return this.delete(queryKey, requestId, abortKey);
730
825
  }
731
-
732
- this.logger.warning({
733
- title: "Error response, performing retry",
734
- type: "request",
735
- extra: { response, requestDetails, request, requestId },
736
- });
737
- this.performRequest({
738
- ...storageItem,
739
- retries: storageItem.retries + 1,
826
+ // do not remove request from store as we want to re-send it later
827
+ return this.logger.debug({
828
+ title: "Awaiting for network restoration",
829
+ type: "system",
830
+ extra: { response, requestDetails, request },
740
831
  });
741
- }, retryTime || 0);
742
- this.retryTimers.set(requestId, retryTimer);
743
- } else {
744
- if (request.retry) {
745
- this.logger.error({
746
- title: "All retries have been used. Removing request from queue.",
747
- type: "request",
748
- extra: { response, requestDetails, request, requestId },
832
+ }
833
+ // On success
834
+ if (response.success) {
835
+ this.delete(queryKey, requestId, abortKey);
836
+ return this.logger.debug({
837
+ title: "Successful response, removing request from queue.",
838
+ type: "system",
839
+ extra: {
840
+ response,
841
+ requestDetails,
842
+ request,
843
+ },
749
844
  });
750
845
  }
751
- this.delete(queryKey, requestId, abortKey);
846
+ // On retry
847
+ if (willRetry) {
848
+ this.logger.debug({ title: "Waiting for retry", type: "system", extra: { response, requestDetails, request } });
849
+ const retries = storageItem.retries + 1;
850
+ // The attempts are counted on the queued item - whatever sends it next (the timer below, a new request
851
+ // flushing the queue, the network coming back, the queue being started) continues from this number
852
+ this.setQueueItemRetries(queryKey, requestId, retries);
853
+ // Only the latest failure schedules the retry
854
+ this.cancelRetry(requestId);
855
+ // Perform retry once request is failed
856
+ const retryTimer = setTimeout(async () => {
857
+ this.retryTimers.delete(requestId);
858
+ const queueItem = this.getRequest(queryKey, requestId);
859
+
860
+ // Dispatcher methods cancel this timer, so the item was taken directly from the storage and nobody announced it
861
+ if (!queueItem) {
862
+ this.logger.debug({
863
+ title: "Request no longer in queue, skipping retry",
864
+ type: "request",
865
+ extra: { response, requestDetails, request, requestId },
866
+ });
867
+ requestManager.events.emitRemove({ requestId, request, resolved: storageItem.resolved });
868
+ return;
869
+ }
870
+ // Stopped while waiting - it will be sent again when the request gets started
871
+ if (queueItem.stopped) {
872
+ return;
873
+ }
874
+
875
+ this.logger.warning({
876
+ title: "Error response, performing retry",
877
+ type: "request",
878
+ extra: { response, requestDetails, request, requestId },
879
+ });
880
+ await this.performRequest({
881
+ ...storageItem,
882
+ retries,
883
+ });
884
+ // Let the queue go on when it was held by this request
885
+ this.flushQueue(queryKey);
886
+ }, retryTime || 0);
887
+ this.retryTimers.set(requestId, retryTimer);
888
+ } else {
889
+ if (request.retry) {
890
+ this.logger.error({
891
+ title: "All retries have been used. Removing request from queue.",
892
+ type: "request",
893
+ extra: { response, requestDetails, request, requestId },
894
+ });
895
+ }
896
+ this.delete(queryKey, requestId, abortKey);
897
+ }
898
+ } finally {
899
+ this.answeredRequests.delete(requestId);
900
+ // A request which stays in the queue was skipped by the flushes made from its listeners - for example
901
+ // the one of the network coming back - so it gets its chance now
902
+ if (this.getRequest(queryKey, requestId)) {
903
+ this.flushQueue(queryKey);
904
+ }
752
905
  }
753
906
  };
754
907
  }
@@ -105,7 +105,11 @@ export const getAdapter = () =>
105
105
 
106
106
  const response = await fetch(fullUrl, init);
107
107
 
108
- if (timeoutId) {clearTimeout(timeoutId);}
108
+ // The timeout covers the whole exchange - a body that stops arriving has to end with the timeout error.
109
+ // Only a streamed body is handed over to the user as soon as the headers arrive.
110
+ if (timeoutId && streaming && response.body) {
111
+ clearTimeout(timeoutId);
112
+ }
109
113
 
110
114
  onResponseStart();
111
115
 
@@ -140,7 +144,9 @@ export const getAdapter = () =>
140
144
  while (true) {
141
145
  // eslint-disable-next-line no-await-in-loop
142
146
  const { done, value } = await reader.read();
143
- if (done) {break;}
147
+ if (done) {
148
+ break;
149
+ }
144
150
  chunks.push(value);
145
151
  receivedLength += value.length;
146
152
  onResponseProgress({ total: contentLength || receivedLength, loaded: receivedLength } as ProgressEvent);
@@ -158,6 +164,10 @@ export const getAdapter = () =>
158
164
  body = await response.text();
159
165
  }
160
166
 
167
+ if (timeoutId) {
168
+ clearTimeout(timeoutId);
169
+ }
170
+
161
171
  onResponseEnd();
162
172
  unmountListener();
163
173
 
@@ -170,7 +180,9 @@ export const getAdapter = () =>
170
180
  }
171
181
  }
172
182
  } catch (error: any) {
173
- if (timeoutId) {clearTimeout(timeoutId);}
183
+ if (timeoutId) {
184
+ clearTimeout(timeoutId);
185
+ }
174
186
  unmountListener();
175
187
 
176
188
  if (controller?.signal?.aborted) {
package/src/index.ts CHANGED
@@ -1,5 +1,9 @@
1
1
  // rollup client entry point
2
2
 
3
+ // Exported first on purpose: tsgo (TS 7 preview) resolves the types of the program in import order, and a client
4
+ // built from a custom Adapter is close to its instantiation depth limit in `createRequest()()`
5
+ // (`__tests__/features/adapter/adapter.base.spec.ts`). Any other position pushes that spec over the limit.
6
+ export * from "./optimistic";
3
7
  export * from "./plugin";
4
8
  export * from "./client";
5
9
  export * from "./cache";
@@ -3,6 +3,16 @@ import type { RequiredKeys } from "types";
3
3
 
4
4
  import { onWindowEvent, onDocumentEvent, isNavigatorOnline } from "./app.manager.utils";
5
5
 
6
+ /** Document is visible unless the browser reports it as hidden - when the state is unknown we assume it is visible */
7
+ const isDocumentVisible = () => {
8
+ try {
9
+ return window.document.visibilityState !== "hidden";
10
+ } catch {
11
+ /* istanbul ignore next */
12
+ return true;
13
+ }
14
+ };
15
+
6
16
  export enum AppEvents {
7
17
  FOCUS = "focus",
8
18
  BLUR = "blur",
@@ -14,7 +24,8 @@ export const appManagerInitialOptions: RequiredKeys<AppManagerOptionsType> = {
14
24
  initiallyFocused: true,
15
25
  initiallyOnline: isNavigatorOnline,
16
26
  focusEvent: (setFocused) => {
17
- const unmountVisibility = onDocumentEvent("visibilitychange", () => setFocused(true));
27
+ // Visibility changes in both directions - hidden document means the application lost the focus
28
+ const unmountVisibility = onDocumentEvent("visibilitychange", () => setFocused(isDocumentVisible()));
18
29
  const unmountFocus = onWindowEvent("focus", () => setFocused(true));
19
30
  const unmountBlur = onWindowEvent("blur", () => setFocused(false));
20
31