@hyper-fetch/core 10.5.1 → 10.5.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.
@@ -1,6 +1,6 @@
1
1
  import { waitFor } from "@testing-library/dom";
2
2
  import type { CacheValueType } from "cache";
3
- import { Client, Time, httpExtra } from "index";
3
+ import { Client, Time, httpExtra, scopeKey } from "index";
4
4
 
5
5
  import { createCache, createLazyCacheAdapter } from "../../utils";
6
6
 
@@ -159,6 +159,16 @@ describe("Cache [ Garbage Collector ]", () => {
159
159
  expect(cache.get(cacheKey)).not.toBeDefined();
160
160
  });
161
161
  });
162
+ it("should not schedule garbage collection for null [observed]", async () => {
163
+ const storage = new Map();
164
+ storage.set(cacheKey, { ...cacheData, cacheTime: null });
165
+ const cacheInstance = createCache(client, { storage, version });
166
+
167
+ cacheInstance.observe(cacheKey)();
168
+
169
+ expect([...cacheInstance.garbageCollectors.keys()]).toHaveLength(0);
170
+ expect(cacheInstance.get(cacheKey)).toBeDefined();
171
+ });
162
172
  it("should not schedule garbage collection for null", async () => {
163
173
  const storage = new Map();
164
174
  storage.set(cacheKey, { ...cacheData, cacheTime: null });
@@ -172,4 +182,140 @@ describe("Cache [ Garbage Collector ]", () => {
172
182
  });
173
183
  });
174
184
  });
185
+ describe("when the element is observed", () => {
186
+ const time = 1000;
187
+ const observedRequest = () => request.setCacheTime(time);
188
+ const getResponse = (timestamp = Date.now()) => ({
189
+ ...cacheData,
190
+ requestTimestamp: timestamp,
191
+ responseTimestamp: timestamp,
192
+ cacheTime: time,
193
+ });
194
+
195
+ beforeEach(() => {
196
+ vi.useFakeTimers();
197
+ client = new Client({ url: "shared-base-url" });
198
+ request = client.createRequest()({ endpoint: "shared-endpoint", cacheKey, staleTime, cacheTime });
199
+ cache = createCache(client, { version });
200
+ });
201
+
202
+ afterEach(() => {
203
+ vi.useRealTimers();
204
+ });
205
+
206
+ it("should keep the element after its cache time", async () => {
207
+ cache.observe(cacheKey);
208
+ cache.set(observedRequest(), getResponse());
209
+
210
+ await vi.advanceTimersByTimeAsync(time * 5);
211
+
212
+ expect(cache.get(cacheKey)).toBeDefined();
213
+ expect([...cache.garbageCollectors.keys()]).toHaveLength(0);
214
+ });
215
+ it("should cancel the collection scheduled before the element got observed", async () => {
216
+ const spy = vi.fn();
217
+ cache.events.onDeleteByKey(cacheKey, spy);
218
+ cache.set(observedRequest(), getResponse());
219
+
220
+ cache.observe(cacheKey);
221
+ await vi.advanceTimersByTimeAsync(time * 5);
222
+
223
+ expect(cache.get(cacheKey)).toBeDefined();
224
+ expect(spy).not.toHaveBeenCalled();
225
+ });
226
+ it("should count the cache time from the moment the last observer stops", async () => {
227
+ const stopFirst = cache.observe(cacheKey);
228
+ const stopSecond = cache.observe(cacheKey);
229
+ cache.set(observedRequest(), getResponse());
230
+ await vi.advanceTimersByTimeAsync(time * 5);
231
+
232
+ stopFirst();
233
+ await vi.advanceTimersByTimeAsync(time * 5);
234
+ expect(cache.get(cacheKey)).toBeDefined();
235
+
236
+ stopSecond();
237
+ await vi.advanceTimersByTimeAsync(time - 1);
238
+ expect(cache.get(cacheKey)).toBeDefined();
239
+
240
+ await vi.advanceTimersByTimeAsync(1);
241
+ expect(cache.get(cacheKey)).toBeUndefined();
242
+ });
243
+ it("should count the cache time from the response when it is newer than the last observer", async () => {
244
+ cache.observe(cacheKey)();
245
+ await vi.advanceTimersByTimeAsync(time / 2);
246
+ cache.set(observedRequest(), getResponse());
247
+
248
+ await vi.advanceTimersByTimeAsync(time - 1);
249
+ expect(cache.get(cacheKey)).toBeDefined();
250
+
251
+ await vi.advanceTimersByTimeAsync(1);
252
+ expect(cache.get(cacheKey)).toBeUndefined();
253
+ });
254
+ it("should stop observing once when the stop function is called many times", async () => {
255
+ const stop = cache.observe(cacheKey);
256
+ cache.observe(cacheKey);
257
+ cache.set(observedRequest(), getResponse());
258
+
259
+ stop();
260
+ stop();
261
+ await vi.advanceTimersByTimeAsync(time * 5);
262
+
263
+ expect(cache.get(cacheKey)).toBeDefined();
264
+ });
265
+ it("should not collect the element when the app goes back online", async () => {
266
+ cache.observe(cacheKey);
267
+ cache.set(observedRequest(), getResponse());
268
+ client.appManager.setOnline(false);
269
+ await vi.advanceTimersByTimeAsync(time * 5);
270
+
271
+ client.appManager.setOnline(true);
272
+ await vi.advanceTimersByTimeAsync(time * 5);
273
+
274
+ expect(cache.get(cacheKey)).toBeDefined();
275
+ });
276
+ it("should keep observing the element saved again after a deletion", async () => {
277
+ cache.observe(cacheKey);
278
+ cache.set(observedRequest(), getResponse());
279
+
280
+ cache.delete(cacheKey);
281
+ cache.set(observedRequest(), getResponse());
282
+ await vi.advanceTimersByTimeAsync(time * 5);
283
+
284
+ expect(cache.get(cacheKey)).toBeDefined();
285
+ });
286
+ it("should keep observing the elements saved after the cache is cleared", async () => {
287
+ cache.observe(cacheKey);
288
+ cache.set(observedRequest(), getResponse());
289
+
290
+ await cache.clear();
291
+ cache.set(observedRequest(), getResponse());
292
+ await vi.advanceTimersByTimeAsync(time * 5);
293
+
294
+ expect(cache.get(cacheKey)).toBeDefined();
295
+ });
296
+ it("should observe the elements of each scope separately", async () => {
297
+ const scoped = observedRequest().setScope("user-1");
298
+ const storageKey = scopeKey(cacheKey, "user-1");
299
+ cache.observe(storageKey);
300
+ cache.set(observedRequest(), getResponse());
301
+ cache.set(scoped, getResponse());
302
+
303
+ await vi.advanceTimersByTimeAsync(time * 5);
304
+
305
+ expect(cache.get(cacheKey)).toBeUndefined();
306
+ expect(cache.get(storageKey)).toBeDefined();
307
+ });
308
+ it("should keep the observed outdated element in the lazy storage", async () => {
309
+ const lazyStorage = new Map<string, CacheValueType>();
310
+ const timestamp = Date.now() - time * 5;
311
+ lazyStorage.set(cacheKey, { ...getResponse(timestamp), staleTime: Infinity });
312
+ const lazyCache = createCache(client, { lazyStorage: createLazyCacheAdapter(lazyStorage), version });
313
+
314
+ lazyCache.observe(cacheKey);
315
+ await lazyCache.getLazyResource(cacheKey);
316
+
317
+ expect(lazyStorage.get(cacheKey)).toBeDefined();
318
+ expect(lazyCache.get(cacheKey)).toBeDefined();
319
+ });
320
+ });
175
321
  });
@@ -20,6 +20,10 @@ export declare class Cache<Adapter extends AdapterInstance> {
20
20
  lazyStorage?: CacheAsyncStorageType;
21
21
  version: string;
22
22
  garbageCollectors: Map<string, NodeJS.Timeout>;
23
+ /** Number of consumers using each storage key - observed elements are never garbage collected */
24
+ private observers;
25
+ /** Moments the last observer of an element stopped - the cache time of the element counts from there */
26
+ private releaseTimestamps;
23
27
  private logger;
24
28
  private client;
25
29
  constructor(options?: CacheOptionsType | undefined);
@@ -81,7 +85,15 @@ export declare class Cache<Adapter extends AdapterInstance> {
81
85
  */
82
86
  getAllKeys: () => Promise<string[]>;
83
87
  /**
84
- * Schedule garbage collection for given key
88
+ * Mark the cache element as used, for example by a mounted hook. Observed elements are never garbage collected.
89
+ * Their `cacheTime` counts from the moment the last observer stops, or from the response if that is later.
90
+ * Observing does not fetch, refresh or invalidate anything.
91
+ * @param cacheKey storage key of the element - `scopeKey(cacheKey, scope)` for scoped requests
92
+ * @returns function that stops observing. Calling it again does nothing.
93
+ */
94
+ observe: (cacheKey: string) => (() => void);
95
+ /**
96
+ * Schedule garbage collection for given key. Elements used by observers are not scheduled.
85
97
  * @param cacheKey
86
98
  * @returns
87
99
  */
@@ -89,6 +101,7 @@ export declare class Cache<Adapter extends AdapterInstance> {
89
101
  /**
90
102
  * Time left to the garbage collection of the cache element. Returns Infinity for elements stored forever
91
103
  * and a negative value for outdated elements or elements without valid times.
104
+ * The cache time counts from the response, or from the moment the last observer stopped if that is later.
92
105
  */
93
106
  private getTimeLeft;
94
107
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"cache.d.ts","sourceRoot":"","sources":["../../src/cache/cache.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAC7D,OAAO,KAAK,EACV,gBAAgB,EAChB,qBAAqB,EACrB,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IACH,OAAO,CAAC,WAAW,CAejB;IAEF;;;OAGG;IACH,OAAO,CAAC,cAAc,CAkBpB;IAEF;;;OAGG;IACH,KAAK,QAAa,OAAO,CAAC,IAAI,CAAC,CAiB7B;CACH"}
package/dist/index.mjs CHANGED
@@ -2864,6 +2864,10 @@ var Cache = class {
2864
2864
  lazyStorage = void 0;
2865
2865
  version;
2866
2866
  garbageCollectors = /* @__PURE__ */ new Map();
2867
+ /** Number of consumers using each storage key - observed elements are never garbage collected */
2868
+ observers = /* @__PURE__ */ new Map();
2869
+ /** Moments the last observer of an element stopped - the cache time of the element counts from there */
2870
+ releaseTimestamps = /* @__PURE__ */ new Map();
2867
2871
  logger;
2868
2872
  client;
2869
2873
  constructor(options) {
@@ -3009,6 +3013,7 @@ var Cache = class {
3009
3013
  });
3010
3014
  clearTimeout(this.garbageCollectors.get(cacheKey));
3011
3015
  this.garbageCollectors.delete(cacheKey);
3016
+ this.releaseTimestamps.delete(cacheKey);
3012
3017
  const listenersKey = this.storage.get(cacheKey)?.cacheKey ?? cacheKey;
3013
3018
  this.storage.delete(cacheKey);
3014
3019
  this.runLazyStorage("delete", cacheKey, (lazyStorage) => lazyStorage.delete(cacheKey));
@@ -3069,7 +3074,7 @@ var Cache = class {
3069
3074
  const isNewestData = syncData ? syncData.responseTimestamp < data.responseTimestamp : true;
3070
3075
  const isStaleData = data.staleTime === null ? false : data.staleTime <= now - data.responseTimestamp;
3071
3076
  const isValidLazyData = data.version === this.version;
3072
- const isExpiredData = this.client.appManager.isOnline && this.getTimeLeft(data, now) < 0;
3077
+ const isExpiredData = this.client.appManager.isOnline && !this.observers.has(cacheKey) && this.getTimeLeft(cacheKey, data, now) < 0;
3073
3078
  if (!isValidLazyData || isExpiredData) this.runLazyStorage("delete", cacheKey, (lazyStorage) => lazyStorage.delete(cacheKey));
3074
3079
  if (isNewestData && !isStaleData && isValidLazyData && !isExpiredData) {
3075
3080
  this.storage.set(cacheKey, data);
@@ -3105,7 +3110,33 @@ var Cache = class {
3105
3110
  return [...new Set([...asyncKeys, ...syncKeys])];
3106
3111
  };
3107
3112
  /**
3108
- * Schedule garbage collection for given key
3113
+ * Mark the cache element as used, for example by a mounted hook. Observed elements are never garbage collected.
3114
+ * Their `cacheTime` counts from the moment the last observer stops, or from the response if that is later.
3115
+ * Observing does not fetch, refresh or invalidate anything.
3116
+ * @param cacheKey storage key of the element - `scopeKey(cacheKey, scope)` for scoped requests
3117
+ * @returns function that stops observing. Calling it again does nothing.
3118
+ */
3119
+ observe = (cacheKey) => {
3120
+ this.observers.set(cacheKey, (this.observers.get(cacheKey) ?? 0) + 1);
3121
+ this.releaseTimestamps.delete(cacheKey);
3122
+ clearTimeout(this.garbageCollectors.get(cacheKey));
3123
+ this.garbageCollectors.delete(cacheKey);
3124
+ let isObserving = true;
3125
+ return () => {
3126
+ if (!isObserving) return;
3127
+ isObserving = false;
3128
+ const observers = (this.observers.get(cacheKey) ?? 1) - 1;
3129
+ if (observers > 0) {
3130
+ this.observers.set(cacheKey, observers);
3131
+ return;
3132
+ }
3133
+ this.observers.delete(cacheKey);
3134
+ this.releaseTimestamps.set(cacheKey, Date.now());
3135
+ this.scheduleGarbageCollector(cacheKey);
3136
+ };
3137
+ };
3138
+ /**
3139
+ * Schedule garbage collection for given key. Elements used by observers are not scheduled.
3109
3140
  * @param cacheKey
3110
3141
  * @returns
3111
3142
  */
@@ -3113,50 +3144,65 @@ var Cache = class {
3113
3144
  const cacheData = this.storage.get(cacheKey);
3114
3145
  clearTimeout(this.garbageCollectors.get(cacheKey));
3115
3146
  this.garbageCollectors.delete(cacheKey);
3116
- if (cacheData) {
3117
- const timeLeft = this.getTimeLeft(cacheData, Date.now());
3118
- if (cacheData.cacheTime === null) this.logger.debug({
3119
- title: "Cache time is null",
3147
+ if (!cacheData) {
3148
+ this.releaseTimestamps.delete(cacheKey);
3149
+ return;
3150
+ }
3151
+ if (this.observers.has(cacheKey)) {
3152
+ this.logger.debug({
3153
+ title: "Cache element is observed",
3120
3154
  type: "system",
3121
3155
  extra: { cacheKey }
3122
3156
  });
3123
- else if (timeLeft === Infinity) this.logger.debug({
3124
- title: "Cache time is Infinite",
3157
+ return;
3158
+ }
3159
+ const timeLeft = this.getTimeLeft(cacheKey, cacheData, Date.now());
3160
+ if (cacheData.cacheTime === null) this.logger.debug({
3161
+ title: "Cache time is null",
3162
+ type: "system",
3163
+ extra: { cacheKey }
3164
+ });
3165
+ else if (timeLeft === Infinity) this.logger.debug({
3166
+ title: "Cache time is Infinite",
3167
+ type: "system",
3168
+ extra: { cacheKey }
3169
+ });
3170
+ else if (timeLeft >= 0) {
3171
+ const delay = Math.min(timeLeft, MAX_TIMER_DELAY);
3172
+ this.garbageCollectors.set(cacheKey, setTimeout(() => {
3173
+ this.garbageCollectors.delete(cacheKey);
3174
+ if (delay < timeLeft) this.scheduleGarbageCollector(cacheKey);
3175
+ else if (this.client.appManager.isOnline) {
3176
+ this.logger.info({
3177
+ title: "Garbage collecting cache data",
3178
+ type: "system",
3179
+ extra: { cacheKey }
3180
+ });
3181
+ this.delete(cacheKey);
3182
+ }
3183
+ }, delay));
3184
+ } else if (this.client.appManager.isOnline) {
3185
+ this.logger.info({
3186
+ title: "Garbage collecting cache data",
3125
3187
  type: "system",
3126
3188
  extra: { cacheKey }
3127
3189
  });
3128
- else if (timeLeft >= 0) {
3129
- const delay = Math.min(timeLeft, MAX_TIMER_DELAY);
3130
- this.garbageCollectors.set(cacheKey, setTimeout(() => {
3131
- this.garbageCollectors.delete(cacheKey);
3132
- if (delay < timeLeft) this.scheduleGarbageCollector(cacheKey);
3133
- else if (this.client.appManager.isOnline) {
3134
- this.logger.info({
3135
- title: "Garbage collecting cache data",
3136
- type: "system",
3137
- extra: { cacheKey }
3138
- });
3139
- this.delete(cacheKey);
3140
- }
3141
- }, delay));
3142
- } else if (this.client.appManager.isOnline) {
3143
- this.logger.info({
3144
- title: "Garbage collecting cache data",
3145
- type: "system",
3146
- extra: { cacheKey }
3147
- });
3148
- this.delete(cacheKey);
3149
- }
3190
+ this.delete(cacheKey);
3150
3191
  }
3151
3192
  };
3152
3193
  /**
3153
3194
  * Time left to the garbage collection of the cache element. Returns Infinity for elements stored forever
3154
3195
  * and a negative value for outdated elements or elements without valid times.
3196
+ * The cache time counts from the response, or from the moment the last observer stopped if that is later.
3155
3197
  */
3156
- getTimeLeft = (cacheData, now) => {
3198
+ getTimeLeft = (cacheKey, cacheData, now) => {
3157
3199
  const { cacheTime, responseTimestamp } = cacheData;
3158
- if (cacheTime === null || typeof cacheTime === "number" && !Number.isFinite(cacheTime)) return Infinity;
3159
- const timeLeft = cacheTime + responseTimestamp - now;
3200
+ if (cacheTime === null || typeof cacheTime === "number" && !Number.isFinite(cacheTime)) {
3201
+ this.releaseTimestamps.delete(cacheKey);
3202
+ return Infinity;
3203
+ }
3204
+ const releaseTimestamp = this.releaseTimestamps.get(cacheKey) ?? -Infinity;
3205
+ const timeLeft = cacheTime + Math.max(responseTimestamp, releaseTimestamp) - now;
3160
3206
  return Number.isNaN(timeLeft) ? -1 : timeLeft;
3161
3207
  };
3162
3208
  /**
@@ -3186,6 +3232,7 @@ var Cache = class {
3186
3232
  clear = async () => {
3187
3233
  this.garbageCollectors.forEach((timeout) => clearTimeout(timeout));
3188
3234
  this.garbageCollectors.clear();
3235
+ this.releaseTimestamps.clear();
3189
3236
  this.storage.clear();
3190
3237
  await this.runLazyStorage("clear", "*", async (lazyStorage) => {
3191
3238
  const keys = [...await lazyStorage.keys()];