Skip to content

Commit

Permalink
Merge branch 'hotfix/fix-cache-lock'
Browse files Browse the repository at this point in the history
  • Loading branch information
ITJesse committed Nov 13, 2023
2 parents 886a0f7 + d6f4754 commit abbf5a8
Show file tree
Hide file tree
Showing 2 changed files with 3 additions and 20 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "image-optimizer",
"version": "1.2.1",
"version": "1.2.2",
"main": "index.js",
"license": "MIT",
"scripts": {
Expand Down
21 changes: 2 additions & 19 deletions src/lib/cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,20 +20,12 @@ const getCacheFilePath = (hash: string) => {

export class Cache {
private key: string
private cacheLocker: Locker

constructor(params: CachaParams) {
this.key = `image_cache:${hash(params)}`
this.cacheLocker = new Locker(params)
}
get = async (): Promise<[null] | [string, number]> => {
while (await this.cacheLocker.isLocked()) {
await delay(10)
}
const [_, cached] = await Promise.all([
this.cacheLocker.lock(),
redisClient.hgetall(this.key),
])
const cached = await redisClient.hgetall(this.key)
const { file, timestamp } = cached
if (!file) return [null]
const filePath = getCacheFilePath(file)
Expand All @@ -44,19 +36,12 @@ export class Cache {
])
return [null]
}
await Promise.all([
redisClient.zincrby('cache_access_count', 1, this.key),
this.cacheLocker.unlock(),
])
await redisClient.zincrby('cache_access_count', 1, this.key)
return [filePath, Math.floor((Date.now() - parseInt(timestamp)) / 1000)]
}

set = (data: PassThrough) =>
new Promise<void>(async (resolve, reject) => {
while (await this.cacheLocker.isLocked()) {
await delay(10)
}
await this.cacheLocker.lock()
const bufs = []
const cipher = crypto.createHash('sha1')
data.on('data', (chunk) => {
Expand Down Expand Up @@ -84,8 +69,6 @@ export class Cache {
} catch (err) {
logger.error('Error while create image cache: ', err)
reject(err)
} finally {
await this.cacheLocker.unlock()
}
})
})
Expand Down

0 comments on commit abbf5a8

Please sign in to comment.