-
-
Notifications
You must be signed in to change notification settings - Fork 212
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat: Cache Cover Art Calls #3015
base: master
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,105 @@ | ||
/* eslint-disable no-console */ | ||
import localforage from "localforage"; | ||
|
||
// Initialize IndexedDB | ||
const coverArtCache = localforage.createInstance({ | ||
name: "listenbrainz", | ||
driver: [localforage.INDEXEDDB, localforage.LOCALSTORAGE], | ||
storeName: "coverart", | ||
}); | ||
|
||
const coverArtCacheExpiry = localforage.createInstance({ | ||
name: "listenbrainz", | ||
driver: [localforage.INDEXEDDB, localforage.LOCALSTORAGE], | ||
storeName: "coverart-expiry", | ||
}); | ||
|
||
const DEFAULT_CACHE_TTL = 1000 * 60 * 60 * 24 * 7; // 7 days | ||
|
||
/** | ||
* Removes all expired entries from both the cover art cache and expiry cache | ||
* This helps keep the cache size manageable by cleaning up old entries | ||
*/ | ||
const removeAllExpiredCacheEntries = async () => { | ||
try { | ||
const keys = await coverArtCacheExpiry.keys(); | ||
// Check each key to see if it's expired2 | ||
const expiredKeys = await Promise.all( | ||
keys.map(async (key) => { | ||
try { | ||
const expiry = await coverArtCacheExpiry.getItem<number>(key); | ||
return expiry && expiry < Date.now() ? key : null; | ||
} catch { | ||
// If we can't read the expiry time, treat the entry as expired | ||
return key; | ||
} | ||
}) | ||
); | ||
|
||
// Filter out null values and remove expired entries from both caches | ||
const keysToRemove = expiredKeys.filter( | ||
(key): key is string => key !== null | ||
); | ||
await Promise.allSettled([ | ||
...keysToRemove.map((key) => coverArtCache.removeItem(key)), | ||
...keysToRemove.map((key) => coverArtCacheExpiry.removeItem(key)), | ||
]); | ||
} catch (error) { | ||
console.error("Error removing expired cache entries:", error); | ||
} | ||
}; | ||
|
||
/** | ||
* Stores a cover art URL in the cache with an expiration time | ||
* @param key - Unique identifier for the cover art | ||
* @param value - The URL or data URI of the cover art | ||
*/ | ||
const setCoverArtCache = async (key: string, value: string) => { | ||
// Validate inputs to prevent storing invalid data | ||
if (!key || !value) { | ||
console.error("Invalid key or value provided to setCoverArtCache"); | ||
return; | ||
} | ||
|
||
try { | ||
// Store both the cover art and its expiration time simultaneously | ||
await Promise.allSettled([ | ||
coverArtCache.setItem(key, value), | ||
coverArtCacheExpiry.setItem(key, Date.now() + DEFAULT_CACHE_TTL), | ||
]); | ||
// Run cleanup in background to avoid blocking the main operation | ||
removeAllExpiredCacheEntries().catch(console.error); | ||
} catch (error) { | ||
console.error("Error setting cover art cache:", error); | ||
} | ||
}; | ||
|
||
/** | ||
* Retrieves a cover art URL from the cache if it exists and hasn't expired | ||
* @param key - Unique identifier for the cover art | ||
* @returns The cached cover art URL/data URI, or null if not found/expired | ||
*/ | ||
const getCoverArtCache = async (key: string): Promise<string | null> => { | ||
if (!key) { | ||
console.error("Invalid key provided to getCoverArtCache"); | ||
return null; | ||
} | ||
|
||
try { | ||
// Check if the entry has expired | ||
const expiry = await coverArtCacheExpiry.getItem<number>(key); | ||
if (!expiry || expiry < Date.now()) { | ||
await Promise.allSettled([ | ||
coverArtCache.removeItem(key), | ||
coverArtCacheExpiry.removeItem(key), | ||
]); | ||
return null; | ||
} | ||
return await coverArtCache.getItem<string>(key); | ||
} catch (error) { | ||
console.error("Error getting cover art cache:", error); | ||
return null; | ||
} | ||
}; | ||
|
||
export { setCoverArtCache, getCoverArtCache }; |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -13,6 +13,7 @@ import { GlobalAppContextT } from "./GlobalAppContext"; | |
import APIServiceClass from "./APIService"; | ||
import { ToastMsg } from "../notifications/Notifications"; | ||
import RecordingFeedbackManager from "./RecordingFeedbackManager"; | ||
import { getCoverArtCache, setCoverArtCache } from "./coverArtCache"; | ||
|
||
const originalFetch = window.fetch; | ||
const fetchWithRetry = require("fetch-retry")(originalFetch); | ||
|
@@ -756,13 +757,23 @@ const getAlbumArtFromReleaseGroupMBID = async ( | |
optionalSize?: CAAThumbnailSizes | ||
): Promise<string | undefined> => { | ||
try { | ||
const cacheKey = `rag:${releaseGroupMBID}-${optionalSize}`; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. rag? Release Art Group? |
||
const cachedCoverArt = await getCoverArtCache(cacheKey); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This needs to be applied to |
||
if (cachedCoverArt) { | ||
return cachedCoverArt; | ||
} | ||
const CAAResponse = await fetchWithRetry( | ||
`https://coverartarchive.org/release-group/${releaseGroupMBID}`, | ||
retryParams | ||
); | ||
if (CAAResponse.ok) { | ||
const body: CoverArtArchiveResponse = await CAAResponse.json(); | ||
return getThumbnailFromCAAResponse(body, optionalSize); | ||
const coverArt = getThumbnailFromCAAResponse(body, optionalSize); | ||
if (coverArt) { | ||
// Cache the successful result | ||
await setCoverArtCache(cacheKey, coverArt); | ||
} | ||
return coverArt; | ||
} | ||
} catch (error) { | ||
// eslint-disable-next-line no-console | ||
|
@@ -781,13 +792,25 @@ const getAlbumArtFromReleaseMBID = async ( | |
optionalSize?: CAAThumbnailSizes | ||
): Promise<string | undefined> => { | ||
try { | ||
// Check cache first | ||
const cacheKey = `ca:${userSubmittedReleaseMBID}-${optionalSize}-${useReleaseGroupFallback}`; | ||
const cachedCoverArt = await getCoverArtCache(cacheKey); | ||
if (cachedCoverArt) { | ||
return cachedCoverArt; | ||
} | ||
|
||
const CAAResponse = await fetchWithRetry( | ||
`https://coverartarchive.org/release/${userSubmittedReleaseMBID}`, | ||
retryParams | ||
); | ||
if (CAAResponse.ok) { | ||
const body: CoverArtArchiveResponse = await CAAResponse.json(); | ||
return getThumbnailFromCAAResponse(body, optionalSize); | ||
const coverArt = getThumbnailFromCAAResponse(body, optionalSize); | ||
if (coverArt) { | ||
// Cache the successful result | ||
await setCoverArtCache(cacheKey, coverArt); | ||
} | ||
return coverArt; | ||
} | ||
|
||
if (CAAResponse.status === 404 && useReleaseGroupFallback) { | ||
|
@@ -802,7 +825,14 @@ const getAlbumArtFromReleaseMBID = async ( | |
return undefined; | ||
} | ||
|
||
return await getAlbumArtFromReleaseGroupMBID(releaseGroupMBID); | ||
const fallbackCoverArt = await getAlbumArtFromReleaseGroupMBID( | ||
releaseGroupMBID | ||
); | ||
if (fallbackCoverArt) { | ||
// Cache the fallback result | ||
await setCoverArtCache(cacheKey, fallbackCoverArt); | ||
} | ||
return fallbackCoverArt; | ||
} | ||
} catch (error) { | ||
// eslint-disable-next-line no-console | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
const localforageMock = { | ||
createInstance: jest.fn(() => ({ | ||
setItem: jest.fn(), | ||
getItem: jest.fn(), | ||
removeItem: jest.fn(), | ||
keys: jest.fn().mockResolvedValue([]), | ||
})), | ||
}; | ||
|
||
export default localforageMock; |
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Is there an advantage to having a separate cache instead of storing an object with
{expiry : xxxx, data: yyyyy}
?Is it to make the homemade garbage collection more efficient?
I also saw that there was a plugin for handling expiry, and they implemented it using the same DB instance but adding a separate key-value pair, the key being based on the original key.
That could be another way to do it: https://github.com/LuudJanssen/localforage-cache/blob/master/src/localforage.js#L117-L124
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I believe, one of the important factors of saving data in IndexedDB / LocalStorage is the cleanup process. What
removeAllExpiredCacheEntries
does is run over all the keys and check if the key has been expired or not.Saving the expiration key as
${key}_expires_${hash}
makes this process slower as we'll have to index all keys, and filter down the keys of this regex and then process.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This approach is definitely better because a Single operation ensures data and expiry are always in sync, and makes the code simpler. BUT, when checking if data is expired, this forces you to deserialize the entire object which will increase memory usage and processing time.