implemented LRU cache

This commit is contained in:
Jack Case
2025-12-29 17:17:52 +00:00
parent c43dc8f7b3
commit 2733ccc737
2 changed files with 63 additions and 40 deletions

View File

@@ -1,4 +1,4 @@
import { openDB, IDBPDatabase } from "idb/index.js"
import { openDB, IDBPDatabase, unwrap } from "idb/index.js"
export class IDBCursorValueIterator {
cursor: IDBCursorWithValue
@@ -37,11 +37,13 @@ export class IDBCursorValueIterator {
export class CheckCache {
slopdb: SlopDB
cache_capacity: number
size: number
static cache_objectstore_name = "checkcache"
constructor(slopdb: SlopDB, max_entries: number) {
this.slopdb = slopdb
this.cache_capacity = max_entries
this.size = 0
}
cache_item_factory(url: string) {
@@ -53,43 +55,31 @@ export class CheckCache {
async store(url: string) {
const cache_store = this.slopdb.db.transaction(CheckCache.cache_objectstore_name, "readwrite").objectStore(CheckCache.cache_objectstore_name)
await cache_store.add(this.cache_item_factory(url))
const cache_item = this.cache_item_factory(url)
cache_store.add(cache_item)
this.size++
if(this.size > this.cache_capacity) {
this.evict_lru()
}
return cache_item
}
async get(url: string) {
const cache_store = this.slopdb.db.transaction(CheckCache.cache_objectstore_name, "readwrite").objectStore(CheckCache.cache_objectstore_name)
return cache_store.get(url)
const cache_item = await cache_store.get(url)
if(cache_item) {
cache_item.check_timestamp = Date.now()
await cache_store.put(cache_item)
}
return cache_item
}
// async evict_least_recently_checked(count: number) {
// const transaction = this.slopdb.start_transaction(CheckCache.cache_objectstore_name, "readwrite")
// const cache_objectstore = transaction.objectStore(CheckCache.cache_objectstore_name)
// const cursor_result_promise = new Promise<Iterable<any>>((resolve, reject) => {
// const cache_cursor_request = cache_objectstore.openCursor()
// cache_cursor_request.onerror = (error) => {
// reject(error)
// }
// cache_cursor_request.onsuccess = (event) => {
// const cursor = cache_cursor_request.result
// resolve(new IDBCursorValueIterator(cursor))
// }
// })
// const cursor = await cursor_result_promise
// const key_array = Array.from(cursor)
// key_array.sort((a, b) => {
// const a_datetime = a.check_timestamp
// const b_datetime = b.check_timestamp
// return a_datetime.getTime - b_datetime.getTime
// })
// }
async evict_lru() {
const timestamp_index = this.slopdb.db.transaction(CheckCache.cache_objectstore_name, "readwrite").store.index("timestamp")
const timestamp_cursor = await timestamp_index.openCursor()
await timestamp_cursor.delete()
this.size--
}
}
export class SlopDB {
@@ -103,7 +93,8 @@ export class SlopDB {
db.createObjectStore("slop", { keyPath: "domain" })
break
case 2:
db.createObjectStore("checkcache", { keyPath: "url" })
const store = db.createObjectStore("checkcache", { keyPath: "url" })
store.createIndex("timestamp", "check_timestamp")
break
}
}