Skip to content

Commit

Permalink
Fiddled with caching code
Browse files Browse the repository at this point in the history
Just a guess as to what might be causing #32 on Firefox
  • Loading branch information
haukex committed Oct 13, 2024
1 parent a70a9f5 commit 6c2f957
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 13 deletions.
18 changes: 10 additions & 8 deletions src/workers/dict-load.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ async function gunzipUTF8(stream :ReadableStream<Uint8Array>): Promise<string> {
* If this function returns `null`, no update is needed, but if an update
* is needed, then the caller must call the returned function when it is
* done doing its work, or not call it if its work fails. */
async function doesDictNeedUpdate(): Promise<null|(()=>void)> {
async function doesDictNeedUpdate(cache :Cache): Promise<null|(()=>void)> {
let dictNeedsUpdate :null|(()=>void) = null // return value
try {
// get the small text file from the network
Expand All @@ -89,11 +89,11 @@ async function doesDictNeedUpdate(): Promise<null|(()=>void)> {
if (dictVerResp.ok) {
// this function, to be called by our callers, saves the current version of the file for the next comparison
const commit = async () => {
(await caches.open(DB_CACHE_NAME)).put(DB_VER_URL, dictVerResp)
cache.put(DB_VER_URL, dictVerResp)
console.debug('Saved the new dict version information.')
}
// next, check if we have a copy of the file in the cache
const dictVerCache = await (await caches.open(DB_CACHE_NAME)).match(DB_VER_URL)
const dictVerCache = await cache.match(DB_VER_URL)
if (dictVerCache) { // we have a copy of the file in the cache
// and then compare whether the two files are the same
// (clone because Response body can only be read once per request)
Expand Down Expand Up @@ -129,6 +129,8 @@ async function doesDictNeedUpdate(): Promise<null|(()=>void)> {
* function returns, and once when the updated dictionary data is loaded.
*/
export async function loadDict(target :string[]): Promise<void> {
const cache = await caches.open(DB_CACHE_NAME)

// Helper function to copy response data to target line array.
const response2lines = async (resp :Response, progCb :boolean): Promise<void> => {
assert(resp.body)
Expand Down Expand Up @@ -159,13 +161,13 @@ export async function loadDict(target :string[]): Promise<void> {
else throw new Error(msg)
// (clone because Response body can only be read once per request)
const dictForCache = dictFromNet.clone()
await response2lines(dictFromNet, progCb); // update the target with this response
await response2lines(dictFromNet, progCb) // update the target with this response
// don't store the response in cache until we know it was processed without error
(await caches.open(DB_CACHE_NAME)).put(DB_URL, dictForCache) // save the response to the cache
cache.put(DB_URL, dictForCache) // save the response to the cache
}

// Check if the dictionary is in the cache.
const dictFromCache = await (await caches.open(DB_CACHE_NAME)).match(DB_URL)
const dictFromCache = await cache.match(DB_URL)
if (dictFromCache) {
console.debug('The dictionary data is in the cache, using that first, and will check for update in background.')
// Schedule the dictionary update check for background execution.
Expand All @@ -174,7 +176,7 @@ export async function loadDict(target :string[]): Promise<void> {
* but see also the various discussions at https://github.com/WICG/netinfo/issues?q=metered
* and the relaunch attempt at https://github.com/tomayac/netinfo/blob/relaunch/README.md */
setTimeout(async () => {
const commit = await doesDictNeedUpdate()
const commit = await doesDictNeedUpdate(cache)
if (commit) {
console.debug('Dictionary needs update, starting background update.')
const m :WorkerMessageType = { type: 'dict-upd', status: 'loading', dictLinesLen: target.length }
Expand Down Expand Up @@ -203,7 +205,7 @@ export async function loadDict(target :string[]): Promise<void> {
await getDictFromNet(true)
// We can also assume we don't have the version information in the cache either, so fetch that in the background.
setTimeout(async () => {
const commit = await doesDictNeedUpdate()
const commit = await doesDictNeedUpdate(cache)
if (commit) commit()
}, 500)
}
Expand Down
10 changes: 5 additions & 5 deletions src/workers/sw.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ self.addEventListener('fetch', event => {
if (event.request.url.toLowerCase().startsWith('http') && event.request.url!==DB_URL && event.request.url!==DB_VER_URL) {
console.debug('SW fetch: Intercepting', event.request)
sendMsg(`fetch: Intercepting ${event.request.method} ${event.request.url}`)
event.respondWith(cacheFirst(caches, APP_CACHE_NAME, event.request))
event.respondWith(cacheFirst(event.request))
}
else {
console.debug('SW fetch: NOT Intercepting', event.request)
Expand All @@ -96,15 +96,15 @@ self.addEventListener('fetch', event => {

/* This function checks for the existence of a request URL in the specified cache,
* returning it if it is found, otherwise it goes out to the network and stores the result in the cache. */
async function cacheFirst(storage :CacheStorage, cacheName :string, request :Request) {
async function cacheFirst(request :Request) {
try {
const cache = await storage.open(cacheName)
const cache = await caches.open(APP_CACHE_NAME)
const responseFromCache = await cache.match(request)
if (responseFromCache) {
console.debug(`cache HIT ${cacheName} ${request.method} ${request.url}`)
console.debug(`cache HIT ${APP_CACHE_NAME} ${request.method} ${request.url}`)
return responseFromCache
} // else
console.debug(`cache MISS ${cacheName} ${request.method} ${request.url}`)
console.debug(`cache MISS ${APP_CACHE_NAME} ${request.method} ${request.url}`)
const responseFromNetwork = await fetch(request)
await cache.put(request, responseFromNetwork.clone())
return responseFromNetwork
Expand Down

0 comments on commit 6c2f957

Please sign in to comment.