fix(cache): improve cache handling by checking availability before operations (#397)

* fix(cache): improve cache handling by checking availability before operations

* fix(cache): improve cache handling and improve error management
This commit is contained in:
brios
2026-04-22 17:27:06 -04:00
committed by Zach Yale
parent a261749b8c
commit b2ff955e9c
@@ -16,8 +16,7 @@ export class CacheStorageService {
return cachedResponse; return cachedResponse;
} }
// Cache stale or failed to get, fetch from uri // Cache unavailable, stale, or failed — fetch from server
const httpResponse = await this.fetchFromUri(uri); const httpResponse = await this.fetchFromUri(uri);
const headers = new Headers(); const headers = new Headers();
httpResponse.headers.keys().forEach((key) => { httpResponse.headers.keys().forEach((key) => {
@@ -29,37 +28,25 @@ export class CacheStorageService {
status: httpResponse.status, status: httpResponse.status,
statusText: httpResponse.statusText, statusText: httpResponse.statusText,
}); });
this.put(uri, res.clone()).catch((error) => { this.put(uri, res.clone());
console.error("Error caching response:", error);
});
return res; return res;
} }
/** /**
* @throws no throws * @returns cached response, or null if cache is unavailable, stale, or failed to access/validate
* @returns cached response, or null if cache is stale or failed to access/validate
*/ */
private async attemptToGetAndValidateCache(uri: string, noValidate: boolean = false): Promise<Response | null> { private async attemptToGetAndValidateCache(uri: string, noValidate: boolean = false): Promise<Response | null> {
let stale: boolean = true;
let entry;
try { try {
entry = await this.match(uri); const entry = await this.match(uri);
if (entry) { if (!entry) return null;
stale = false; if (noValidate) return entry;
if (!noValidate) { const valid = await this.validateCacheFromUri(uri, entry);
stale = !(await this.validateCacheFromUri(uri, entry)); return valid ? entry : null;
} } catch {
} return null;
} catch (error) {
console.error("Error accessing or validating cache:", error);
stale = true;
} }
if (!stale && entry)
return entry;
return null;
} }
private async fetchFromUri(uri: string): Promise<HttpResponse<ArrayBuffer>> { private async fetchFromUri(uri: string): Promise<HttpResponse<ArrayBuffer>> {
@@ -67,7 +54,7 @@ export class CacheStorageService {
this.http.get<ArrayBuffer>(uri, { this.http.get<ArrayBuffer>(uri, {
responseType: "arraybuffer" as "json", responseType: "arraybuffer" as "json",
observe: "response", observe: "response",
cache: "no-store", // Avoid double caching cache: "no-store",
}), }),
); );
} }
@@ -85,51 +72,76 @@ export class CacheStorageService {
); );
return response.status === 304; return response.status === 304;
} catch (error: unknown) { // It throws if the status is not 2xx } catch (error: unknown) {
if (error instanceof HttpErrorResponse && error.status === 304) { if (error instanceof HttpErrorResponse && error.status === 304) {
return true; // Not modified, cache is valid return true;
} }
console.error("Error validating cache:", error);
return false; return false;
} }
} }
match(uri: string): Promise<Response | undefined> { async match(uri: string): Promise<Response | undefined> {
return this.cache().then((cache) => cache.match(uri)); try {
const cache = await this.openCache();
return cache ? await cache.match(uri) : undefined;
} catch {
return undefined;
}
} }
has(uri: string): Promise<boolean> { async has(uri: string): Promise<boolean> {
return this.cache().then((cache) => const response = await this.match(uri);
cache.match(uri).then((response) => !!response), return !!response;
);
} }
put(uri: string, entry: Response): Promise<void> { async put(uri: string, entry: Response): Promise<void> {
return this.cache().then((cache) => cache.put(uri, entry)); try {
const cache = await this.openCache();
if (cache) await cache.put(uri, entry);
} catch {
// Silently fail — caching is best-effort
}
} }
delete(uri: string): Promise<boolean> { async delete(uri: string): Promise<boolean> {
return this.cache().then((cache) => cache.delete(uri)); try {
const cache = await this.openCache();
return cache ? await cache.delete(uri) : false;
} catch {
return false;
}
} }
clear(): Promise<void> { async clear(): Promise<void> {
return this.cache() try {
.then((cache) => cache.keys()) const cache = await this.openCache();
.then((keys) => Promise.all(keys.map((key) => this.delete(key.url)))) if (!cache) return;
.then(() => undefined); const keys = await cache.keys();
await Promise.all(keys.map((key) => cache.delete(key.url)));
} catch {
// Silently fail
}
} }
getCacheSizeInBytes(): Promise<number> { async getCacheSizeInBytes(): Promise<number> {
return this.cache() try {
.then((cache) => cache.keys()) const cache = await this.openCache();
.then((keys) => keys.map((key) => this.match(key.url))) if (!cache) return 0;
.then((promises) => Promise.all(promises)) const keys = await cache.keys();
.then((responses) => responses.map(response => parseInt(response?.headers.get("content-length") || "0"))) const responses = await Promise.all(keys.map((key) => cache.match(key.url)));
.then((sizes) => sizes.reduce((total, size) => total + size, 0)); return responses.reduce((total, response) =>
total + parseInt(response?.headers.get("content-length") || "0"), 0);
} catch {
return 0;
}
} }
private async openCache(): Promise<Cache | null> {
private cache(): Promise<Cache> { try {
return caches.open(CacheStorageService.CACHE_NAME); if (typeof caches === 'undefined') return null;
return await caches.open(CacheStorageService.CACHE_NAME);
} catch {
return null;
}
} }
} }