Skip to content

feat: make metadata update operation atomic in persisten cache storage #1593

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

Merged
merged 1 commit into from
Feb 12, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ export const makePersistentCacheStorageFactory =
resourceName: string;
quotaInBytes: number;
}): Cache<T> => {
let metadataUpdateQueue = Promise.resolve();
const loaded = createVolatileCache<T>();
const metadataKey = makeMetadataKey(resourceName);
const getItemKey = (key: string) => makeItemKey(resourceName, key);
Expand All @@ -42,15 +43,22 @@ export const makePersistentCacheStorageFactory =
return result[metadataKey] as Metadata;
};

const updateMetadata = async (mutate: (metadata: Metadata) => Metadata) => {
metadataUpdateQueue = metadataUpdateQueue.then(async () => {
const currentMetadata = await getMetadata();
const nextMetadata = mutate(currentMetadata);
await extensionLocalStorage.set({ [metadataKey]: nextMetadata });
});
return metadataUpdateQueue;
};

const updateAccessTime = async (key: string) => {
const metadata = await getMetadata();
const nextMetadata: Metadata = {
await updateMetadata((metadata) => ({
...metadata,
[key]: {
accessTime: Date.now()
}
};
await extensionLocalStorage.set({ [metadataKey]: nextMetadata });
}));
};

const isQuotaExceeded = async () => {
Expand All @@ -67,7 +75,7 @@ export const makePersistentCacheStorageFactory =
};

const evict = async () => {
let metadata = await getMetadata();
const metadata = await getMetadata();
const mostDatedKeysToPurge = Object.entries(metadata)
.map(([key, { accessTime }]) => ({ accessTime, key }))
.sort((a, b) => a.accessTime - b.accessTime)
Expand All @@ -78,11 +86,12 @@ export const makePersistentCacheStorageFactory =
.map((i) => i.key);

await extensionLocalStorage.remove(mostDatedKeysToPurge);
metadata = await getMetadata();
for (const key of mostDatedKeysToPurge) {
delete metadata[key];
}
await extensionLocalStorage.set({ [metadataKey]: metadata });
await updateMetadata((currentMetadata) => {
for (const key of mostDatedKeysToPurge) {
delete currentMetadata[key];
}
return currentMetadata;
});
};

return {
Expand Down
Loading