@hyper-fetch/core 9.6.1 → 9.6.2

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 (103) 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/plugin/plugin.lifecycle.spec.ts +457 -0
  35. package/__tests__/features/request/request.async-mapper-removal.spec.ts +138 -0
  36. package/__tests__/features/request/request.immutability.spec.ts +259 -0
  37. package/__tests__/features/request/request.inference.spec.ts +269 -0
  38. package/__tests__/features/request/request.lifecycle.spec.ts +682 -0
  39. package/__tests__/features/request/request.optimistic-settlement.spec.ts +35 -17
  40. package/__tests__/features/request/request.values.spec.ts +408 -0
  41. package/__tests__/features/sdk/sdk.builder.spec.ts +304 -0
  42. package/__tests__/features/utils/emitter.listeners.spec.ts +202 -0
  43. package/__tests__/utils/controlled-adapter.utils.ts +119 -0
  44. package/__tests__/utils/fixtures.utils.ts +193 -0
  45. package/dist/adapter/adapter.bindings.d.ts.map +1 -1
  46. package/dist/adapter/adapter.utils.d.ts.map +1 -1
  47. package/dist/cache/cache.d.ts +12 -1
  48. package/dist/cache/cache.d.ts.map +1 -1
  49. package/dist/cache/cache.events.d.ts +20 -6
  50. package/dist/cache/cache.events.d.ts.map +1 -1
  51. package/dist/cache/cache.utils.d.ts +1 -0
  52. package/dist/cache/cache.utils.d.ts.map +1 -1
  53. package/dist/client/client.d.ts +3 -3
  54. package/dist/client/client.d.ts.map +1 -1
  55. package/dist/client/client.utils.d.ts.map +1 -1
  56. package/dist/dispatcher/dispatcher.d.ts +26 -5
  57. package/dist/dispatcher/dispatcher.d.ts.map +1 -1
  58. package/dist/http-adapter/http-adapter.fetch.d.ts.map +1 -1
  59. package/dist/index.mjs +2127 -1741
  60. package/dist/index.mjs.map +1 -1
  61. package/dist/managers/app/app.manager.constants.d.ts.map +1 -1
  62. package/dist/managers/app/app.manager.d.ts +9 -0
  63. package/dist/managers/app/app.manager.d.ts.map +1 -1
  64. package/dist/managers/app/app.manager.utils.d.ts.map +1 -1
  65. package/dist/managers/logger/logger.manager.d.ts.map +1 -1
  66. package/dist/managers/request/request.manager.d.ts.map +1 -1
  67. package/dist/managers/request/request.manager.types.d.ts +2 -0
  68. package/dist/managers/request/request.manager.types.d.ts.map +1 -1
  69. package/dist/mocker/mocker.d.ts +1 -1
  70. package/dist/mocker/mocker.d.ts.map +1 -1
  71. package/dist/plugin/plugin.d.ts +2 -0
  72. package/dist/plugin/plugin.d.ts.map +1 -1
  73. package/dist/request/request.d.ts +1 -1
  74. package/dist/request/request.d.ts.map +1 -1
  75. package/dist/request/request.utils.d.ts.map +1 -1
  76. package/dist/utils/emitter.utils.d.ts.map +1 -1
  77. package/dist/utils/error.utils.d.ts +17 -0
  78. package/dist/utils/error.utils.d.ts.map +1 -0
  79. package/dist/utils/index.d.ts +1 -0
  80. package/dist/utils/index.d.ts.map +1 -1
  81. package/package.json +1 -1
  82. package/src/adapter/adapter.bindings.ts +46 -18
  83. package/src/adapter/adapter.utils.ts +47 -7
  84. package/src/cache/cache.events.ts +24 -8
  85. package/src/cache/cache.ts +109 -21
  86. package/src/cache/cache.utils.ts +33 -10
  87. package/src/client/client.ts +99 -7
  88. package/src/client/client.utils.ts +10 -4
  89. package/src/dispatcher/dispatcher.ts +273 -133
  90. package/src/http-adapter/http-adapter.fetch.ts +15 -3
  91. package/src/managers/app/app.manager.constants.ts +12 -1
  92. package/src/managers/app/app.manager.ts +43 -23
  93. package/src/managers/app/app.manager.utils.ts +8 -4
  94. package/src/managers/logger/logger.manager.ts +21 -8
  95. package/src/managers/request/request.manager.ts +7 -1
  96. package/src/managers/request/request.manager.types.ts +2 -0
  97. package/src/mocker/mocker.ts +14 -11
  98. package/src/plugin/plugin.ts +6 -0
  99. package/src/request/request.ts +31 -22
  100. package/src/request/request.utils.ts +23 -15
  101. package/src/utils/emitter.utils.ts +9 -2
  102. package/src/utils/error.utils.ts +29 -0
  103. package/src/utils/index.ts +1 -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";
@@ -13,7 +14,7 @@ import { getRequestType, canRetryRequest, getDispatcherEvents, DispatcherMode }
13
14
  import type { ResponseDetailsType, LoggerMethods } from "managers";
14
15
  import type { RequestInstance, RequestJSON } from "request";
15
16
  import { Request, scopeKey } from "request";
16
- import { EventEmitter } from "utils";
17
+ import { EventEmitter, throwOutsideLifecycle } from "utils";
17
18
 
18
19
  /**
19
20
  * 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 +28,14 @@ export class Dispatcher<Adapter extends AdapterInstance> {
27
28
 
28
29
  private requestCount = new Map<string, number>();
29
30
  private runningRequests = new Map<string, RunningRequestValueType[]>();
31
+ /** Failed requests waiting for their next attempt, by requestId */
30
32
  private retryTimers = new Map<string, ReturnType<typeof setTimeout>>();
33
+ /** Requests which got their response and are still in the queue while their listeners run */
34
+ private answeredRequests = new Set<string>();
35
+ /** Order in which the requests were sent - responses can come back in another one */
36
+ private sentCount = 0;
37
+ /** Cache element (by its storage key) to the order number of the request whose data it holds */
38
+ private cachedOrder = new Map<string, number>();
31
39
 
32
40
  private logger: LoggerMethods;
33
41
  private client: ClientInstance<{ adapter: Adapter }>;
@@ -195,6 +203,17 @@ export class Dispatcher<Adapter extends AdapterInstance> {
195
203
  * Clear requests from queue cache
196
204
  */
197
205
  clearQueue = (queryKey: string) => {
206
+ return this.removeQueueItems(
207
+ queryKey,
208
+ this.getRunningRequests(queryKey).map((running) => running.requestId),
209
+ );
210
+ };
211
+
212
+ /**
213
+ * Empty the queue. Requests listed in `answeredIds` are running or were just canceled, so they still report
214
+ * their own response. All the others would never be heard of again - those are reported as removed.
215
+ */
216
+ private removeQueueItems = (queryKey: string, answeredIds: string[]) => {
198
217
  const queue = this.getQueue(queryKey);
199
218
  const newQueue = { queryKey, requests: [], stopped: queue.stopped };
200
219
  this.storage.set(queryKey, newQueue);
@@ -202,13 +221,42 @@ export class Dispatcher<Adapter extends AdapterInstance> {
202
221
  // Emit Queue Changes
203
222
  this.client.triggerPlugins("onDispatcherQueueCleared", { dispatcher: this, queue: newQueue });
204
223
  this.events.emitQueueChanged(newQueue);
224
+ this.emitRemovedItems(queue.requests, answeredIds);
205
225
  this.events.emitDrained(newQueue);
206
226
 
207
- this.removeWaitingRetries(queue);
208
-
209
227
  return newQueue;
210
228
  };
211
229
 
230
+ private emitRemovedItems = (items: ResolvedQueueItemType[], answeredIds: string[]) => {
231
+ items.forEach((item) => {
232
+ this.cancelRetry(item.requestId);
233
+
234
+ if (!answeredIds.includes(item.requestId)) {
235
+ this.client.requestManager.events.emitRemove({
236
+ requestId: item.requestId,
237
+ request: item.request,
238
+ resolved: item.resolved,
239
+ });
240
+ }
241
+ });
242
+ };
243
+
244
+ /**
245
+ * A request can be sent when it is not in flight, not held by `stopRequest`, not waiting for its retry,
246
+ * not just answered and - for the requests kept for later with the `offline` option - when there is a connection
247
+ */
248
+ private canPerformRequest = (item: ResolvedQueueItemType, runningIds: Set<string>) => {
249
+ const isWaitingForNetwork = !this.client.appManager.isOnline && item.request.offline;
250
+
251
+ return (
252
+ !item.stopped &&
253
+ !isWaitingForNetwork &&
254
+ !this.retryTimers.has(item.requestId) &&
255
+ !this.answeredRequests.has(item.requestId) &&
256
+ !runningIds.has(item.requestId)
257
+ );
258
+ };
259
+
212
260
  /**
213
261
  * Method used to flush the queue requests
214
262
  */
@@ -225,15 +273,20 @@ export class Dispatcher<Adapter extends AdapterInstance> {
225
273
 
226
274
  // When there are no requests to flush, when its stopped, there is running request
227
275
  // or there is no request to trigger - we don't want to perform actions
228
- if (isStopped || isOffline || isEmpty) {
276
+ if (isStopped || isEmpty) {
229
277
  this.logger.debug({ title: "Skipping queue trigger", type: "system", extra: { isStopped, isOffline, isEmpty } });
230
278
  } else if (isConcurrent) {
279
+ // Collected once - looking for every request in the list of the running ones gets slow with a long queue
280
+ const runningIds = new Set(runningRequests.map((running) => running.requestId));
231
281
  queue.requests.forEach((element) => {
232
- if (!this.hasRunningRequest(queryKey, element.requestId)) {
282
+ if (this.canPerformRequest(element, runningIds)) {
283
+ runningIds.add(element.requestId);
233
284
  this.performRequest(element);
234
285
  }
235
286
  });
236
- } else if (isInactive) {
287
+ }
288
+ // One by one - the first request holds the queue also while it waits for its retry or for the network
289
+ else if (isInactive && this.canPerformRequest(queueItem, new Set())) {
237
290
  await this.performRequest(queueItem);
238
291
  this.flushQueue(queryKey);
239
292
  }
@@ -260,13 +313,18 @@ export class Dispatcher<Adapter extends AdapterInstance> {
260
313
  */
261
314
  clear = () => {
262
315
  const keys = this.getQueuesKeys();
263
- const queues = keys.map((queryKey) => this.getQueue(queryKey));
316
+ // Running requests are canceled and report it on their own, the waiting ones are reported as removed
317
+ const removed = keys.map((queryKey) => ({
318
+ items: this.getQueue(queryKey).requests,
319
+ answeredIds: this.getRunningRequests(queryKey).map((running) => running.requestId),
320
+ }));
264
321
  keys.forEach((queryKey) => this.cancelRunningRequests(queryKey));
265
322
 
266
323
  [...this.runningRequests.keys()].forEach((queryKey) => this.setRunningRequests(queryKey, []));
267
324
  this.runningRequests.clear();
325
+ this.cachedOrder.clear();
268
326
  this.storage.clear();
269
- queues.forEach((queue) => this.removeWaitingRetries(queue));
327
+ removed.forEach(({ items, answeredIds }) => this.emitRemovedItems(items, answeredIds));
270
328
  this.client.triggerPlugins("onDispatcherCleared", { dispatcher: this });
271
329
  };
272
330
 
@@ -283,18 +341,6 @@ export class Dispatcher<Adapter extends AdapterInstance> {
283
341
  return this.retryTimers.delete(requestId);
284
342
  };
285
343
 
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
344
  // *********************************************************************
299
345
  // *********************************************************************
300
346
  // Requests
@@ -363,7 +409,12 @@ export class Dispatcher<Adapter extends AdapterInstance> {
363
409
  */
364
410
  private setRunningRequests = (queryKey: string, runningRequests: RunningRequestValueType[]) => {
365
411
  const previousRequests = this.getRunningRequests(queryKey);
366
- this.runningRequests.set(queryKey, runningRequests);
412
+ if (runningRequests.length > 0) {
413
+ this.runningRequests.set(queryKey, runningRequests);
414
+ } else {
415
+ // Do not keep an empty list for every queryKey that was ever used
416
+ this.runningRequests.delete(queryKey);
417
+ }
367
418
  if (
368
419
  previousRequests.length !== runningRequests.length ||
369
420
  previousRequests.some((req, i) => req !== runningRequests[i])
@@ -503,8 +554,9 @@ export class Dispatcher<Adapter extends AdapterInstance> {
503
554
  }
504
555
  case DispatcherMode.PREVIOUS_CANCELED: {
505
556
  // Cancel all previous on-going requests
557
+ const canceledIds = this.getRunningRequests(queryKey).map((running) => running.requestId);
506
558
  this.cancelRunningRequests(queryKey);
507
- this.clearQueue(queryKey);
559
+ this.removeQueueItems(queryKey, canceledIds);
508
560
  this.addQueueItem(queryKey, storageItem);
509
561
  this.flushQueue(queryKey);
510
562
  return requestId;
@@ -534,12 +586,13 @@ export class Dispatcher<Adapter extends AdapterInstance> {
534
586
  const queue = this.getQueue(queryKey);
535
587
  const queueItem = queue.requests.find((req) => req.requestId === requestId);
536
588
 
537
- if (!queueItem) {return;}
538
-
539
- this.cancelRetry(requestId);
589
+ if (!queueItem) {
590
+ return;
591
+ }
540
592
 
541
593
  queue.requests = queue.requests.filter((req) => req.requestId !== requestId);
542
594
  this.storage.set(queryKey, queue);
595
+ this.cancelRetry(requestId);
543
596
 
544
597
  // Clean controllers
545
598
  if (this.hasRunningRequest(queryKey, requestId)) {
@@ -565,6 +618,34 @@ export class Dispatcher<Adapter extends AdapterInstance> {
565
618
  return queue;
566
619
  };
567
620
 
621
+ /**
622
+ * Save the number of used attempts on the queued request
623
+ */
624
+ private setQueueItemRetries = (queryKey: string, requestId: string, retries: number) => {
625
+ const queue = this.getQueue(queryKey);
626
+ const queueItem = queue.requests.find((item) => item.requestId === requestId);
627
+
628
+ if (queueItem) {
629
+ queueItem.retries = retries;
630
+ this.storage.set(queryKey, queue);
631
+ }
632
+ };
633
+
634
+ /**
635
+ * The `retryOnError` callback belongs to the user - when it throws, the request is not retried
636
+ */
637
+ private getShouldRetryOnError = (request: RequestInstance, response: RequestResponseType<any>) => {
638
+ if (!request.retryOnError) {
639
+ return true;
640
+ }
641
+ try {
642
+ return !!request.retryOnError(response);
643
+ } catch (error) {
644
+ this.logger.error({ title: "The retryOnError callback failed", type: "system", extra: { error, request } });
645
+ return false;
646
+ }
647
+ };
648
+
568
649
  /**
569
650
  * Request can run for some time, once it's done, we have to check if it's successful or if it was aborted
570
651
  * It can be different once the previous call was set as cancelled and removed from queue before this request got resolved
@@ -595,6 +676,8 @@ export class Dispatcher<Adapter extends AdapterInstance> {
595
676
 
596
677
  // Additionally keep the running request to possibly abort it later
597
678
  const runningRequest = this.addRunningRequest(queryKey, requestId, request);
679
+ this.sentCount += 1;
680
+ const sentOrder = this.sentCount;
598
681
 
599
682
  // Propagate the loading to all connected hooks
600
683
  requestManager.events.emitLoading({
@@ -627,128 +710,185 @@ export class Dispatcher<Adapter extends AdapterInstance> {
627
710
  // Remove running request, must be called after isCancelled
628
711
  this.deleteRunningRequest(queryKey, requestId);
629
712
 
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
- });
655
-
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
- });
713
+ // The request is no longer running, but it stays in the queue until its response is handled below. Listeners
714
+ // of the response can add requests to this queue - flushing it must not send the answered request again.
715
+ this.answeredRequests.add(requestId);
716
+ try {
717
+ // A request removed from the queue while it was running (cleared queue) has nothing left to retry
718
+ const isQueued = !!this.getRequest(queryKey, requestId);
719
+ const canRetryResponse = !response.success && canRetry && isQueued && !isCanceled && !isOfflineResponseStatus;
720
+ const willRetry = canRetryResponse && this.getShouldRetryOnError(request, response);
721
+
722
+ const requestDetails: ResponseDetailsType = {
723
+ isCanceled,
724
+ isOffline: isOfflineResponseStatus,
725
+ retries: storageItem.retries,
726
+ willRetry,
727
+ addedTimestamp: storageItem.timestamp,
728
+ triggerTimestamp: runningRequest.timestamp,
729
+ requestTimestamp: response.requestTimestamp,
730
+ responseTimestamp: response.responseTimestamp,
731
+ };
732
+
733
+ // A throwing listener must not leave the request in the queue forever (and block all the queued ones behind it)
734
+ const notify = (callback: VoidFunction) => {
735
+ try {
736
+ callback();
737
+ } catch (error) {
738
+ this.logger.error({
739
+ title: "Response listener failed",
740
+ type: "system",
741
+ extra: { error, request, requestId },
742
+ });
743
+ throwOutsideLifecycle(error);
744
+ }
745
+ };
663
746
 
664
- // On cancelled
665
- if (isCanceled) {
666
- const queue = this.getQueue(queryKey);
667
- const queueItem = queue.requests.find((req) => req.requestId === requestId);
747
+ // Global response emitter to handle request execution
748
+ notify(() => requestManager.events.emitResponse({ request, requestId, response, details: requestDetails }));
668
749
 
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);
750
+ // Turn off loading
751
+ notify(() =>
752
+ requestManager.events.emitLoading({
753
+ request,
754
+ requestId,
755
+ loading: false,
756
+ isRetry: !!storageItem.retries,
757
+ isOffline,
758
+ }),
759
+ );
760
+
761
+ // Requests of one cache key can answer in another order than they were sent. Once the data of a request is in
762
+ // the cache, a response of a request sent before it is outdated - it must not replace that data.
763
+ const storageKey = scopeKey(request.cacheKey, scope);
764
+ const isOutdated = (this.cachedOrder.get(storageKey) ?? 0) > sentOrder;
765
+
766
+ if (isOutdated) {
767
+ this.logger.debug({
768
+ title: "Response of a request sent before the cached one, skipping the cache",
769
+ type: "system",
770
+ extra: { requestId, request, response },
771
+ });
772
+ } else {
773
+ if (response.success) {
774
+ this.cachedOrder.set(storageKey, sentOrder);
775
+ }
776
+ // Cache event to emit the data inside and store it
777
+ notify(() => cache.set(request, { ...response, ...requestDetails }));
674
778
  }
675
- return this.logger.debug({
676
- title: "Request canceled",
779
+ this.logger.debug({
780
+ title: "Dispatcher processing response",
677
781
  type: "system",
678
- extra: { response, requestDetails, request },
782
+ extra: { requestId, request, response, details: requestDetails },
679
783
  });
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",
784
+
785
+ // On cancelled
786
+ if (isCanceled) {
787
+ const queue = this.getQueue(queryKey);
788
+ const queueItem = queue.requests.find((req) => req.requestId === requestId);
789
+
790
+ // do not remove cancelled request as it may be result of manual queue pause
791
+ // if abort was done without stop action we can remove request
792
+ if (!queue.stopped && !queueItem?.stopped) {
793
+ this.logger.debug({ title: "Request paused", type: "system", extra: { response, requestDetails, request } });
794
+ return this.delete(queryKey, requestId, abortKey);
795
+ }
796
+ return this.logger.debug({
797
+ title: "Request canceled",
687
798
  type: "system",
688
799
  extra: { response, requestDetails, request },
689
800
  });
690
- return this.delete(queryKey, requestId, abortKey);
691
801
  }
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 },
802
+ // On offline
803
+ if (!response.success && isOfflineResponseStatus) {
804
+ // if we don't want to keep offline request - just delete them
805
+ if (!offline) {
806
+ this.logger.warning({
807
+ title: "Removing non-offline request",
808
+ type: "system",
809
+ extra: { response, requestDetails, request },
727
810
  });
728
- requestManager.events.emitRemove({ requestId, request, resolved: storageItem.resolved });
729
- return;
811
+ return this.delete(queryKey, requestId, abortKey);
730
812
  }
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,
813
+ // do not remove request from store as we want to re-send it later
814
+ return this.logger.debug({
815
+ title: "Awaiting for network restoration",
816
+ type: "system",
817
+ extra: { response, requestDetails, request },
740
818
  });
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 },
819
+ }
820
+ // On success
821
+ if (response.success) {
822
+ this.delete(queryKey, requestId, abortKey);
823
+ return this.logger.debug({
824
+ title: "Successful response, removing request from queue.",
825
+ type: "system",
826
+ extra: {
827
+ response,
828
+ requestDetails,
829
+ request,
830
+ },
749
831
  });
750
832
  }
751
- this.delete(queryKey, requestId, abortKey);
833
+ // On retry
834
+ if (willRetry) {
835
+ this.logger.debug({ title: "Waiting for retry", type: "system", extra: { response, requestDetails, request } });
836
+ const retries = storageItem.retries + 1;
837
+ // The attempts are counted on the queued item - whatever sends it next (the timer below, a new request
838
+ // flushing the queue, the network coming back, the queue being started) continues from this number
839
+ this.setQueueItemRetries(queryKey, requestId, retries);
840
+ // Only the latest failure schedules the retry
841
+ this.cancelRetry(requestId);
842
+ // Perform retry once request is failed
843
+ const retryTimer = setTimeout(async () => {
844
+ this.retryTimers.delete(requestId);
845
+ const queueItem = this.getRequest(queryKey, requestId);
846
+
847
+ // Dispatcher methods cancel this timer, so the item was taken directly from the storage and nobody announced it
848
+ if (!queueItem) {
849
+ this.logger.debug({
850
+ title: "Request no longer in queue, skipping retry",
851
+ type: "request",
852
+ extra: { response, requestDetails, request, requestId },
853
+ });
854
+ requestManager.events.emitRemove({ requestId, request, resolved: storageItem.resolved });
855
+ return;
856
+ }
857
+ // Stopped while waiting - it will be sent again when the request gets started
858
+ if (queueItem.stopped) {
859
+ return;
860
+ }
861
+
862
+ this.logger.warning({
863
+ title: "Error response, performing retry",
864
+ type: "request",
865
+ extra: { response, requestDetails, request, requestId },
866
+ });
867
+ await this.performRequest({
868
+ ...storageItem,
869
+ retries,
870
+ });
871
+ // Let the queue go on when it was held by this request
872
+ this.flushQueue(queryKey);
873
+ }, retryTime || 0);
874
+ this.retryTimers.set(requestId, retryTimer);
875
+ } else {
876
+ if (request.retry) {
877
+ this.logger.error({
878
+ title: "All retries have been used. Removing request from queue.",
879
+ type: "request",
880
+ extra: { response, requestDetails, request, requestId },
881
+ });
882
+ }
883
+ this.delete(queryKey, requestId, abortKey);
884
+ }
885
+ } finally {
886
+ this.answeredRequests.delete(requestId);
887
+ // A request which stays in the queue was skipped by the flushes made from its listeners - for example
888
+ // the one of the network coming back - so it gets its chance now
889
+ if (this.getRequest(queryKey, requestId)) {
890
+ this.flushQueue(queryKey);
891
+ }
752
892
  }
753
893
  };
754
894
  }
@@ -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) {
@@ -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