-
Notifications
You must be signed in to change notification settings - Fork 0
Introducing a S3
cache adapter
#25
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
Changes from 4 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
6ab2ac7
Introducing a `S3` cache adapter
edoardocavazza b831790
Fix absolute expire
edoardocavazza 9ac2d1a
More consistent clearPattern
edoardocavazza ee82e4a
Ensure default ttl is used
edoardocavazza d3383df
Explicit parseInt radix
edoardocavazza d130482
Handle missing key case
edoardocavazza 4cd4d07
Use a single GetObject command
edoardocavazza File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
--- | ||
"@chialab/sveltekit-utils": minor | ||
--- | ||
|
||
Introducing a `S3` cache adapter. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,3 +1,4 @@ | ||
export * from './base.js'; | ||
export * from './in-memory.js'; | ||
export * from './redis.js'; | ||
export * from './s3.js'; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,171 @@ | ||
import { BaseCache } from './base'; | ||
import { | ||
DeleteObjectCommand, | ||
DeleteObjectsCommand, | ||
GetObjectCommand, | ||
HeadObjectCommand, | ||
ListObjectsV2Command, | ||
PutObjectCommand, | ||
S3, | ||
type S3ClientConfig, | ||
} from '@aws-sdk/client-s3'; | ||
import { logger } from '../../logger.js'; | ||
import { createJitter, JitterMode, type JitterFn } from '../../utils/misc.js'; | ||
|
||
type S3CacheOptions = { | ||
bucket: string; | ||
keyPrefix?: string; | ||
defaultTTL?: number; | ||
defaultJitter?: JitterMode | JitterFn; | ||
}; | ||
|
||
export class S3Cache<V extends Uint8Array = Uint8Array> extends BaseCache<V> { | ||
readonly #options: S3CacheOptions; | ||
readonly #client: S3; | ||
|
||
public static init<V extends Uint8Array = Uint8Array>( | ||
s3Options: S3ClientConfig, | ||
options: S3CacheOptions, | ||
): S3Cache<V> { | ||
const client = new S3(s3Options); | ||
|
||
return new this(options, client); | ||
} | ||
|
||
private constructor(options: S3CacheOptions, client: S3) { | ||
super(); | ||
|
||
this.#options = options; | ||
this.#client = client; | ||
} | ||
|
||
private buildKey(key: string): string { | ||
return `${this.#options.keyPrefix ?? ''}${key}`; | ||
} | ||
|
||
public async get(key: string): Promise<V | undefined> { | ||
const s3Key = this.buildKey(key); | ||
const head = await this.#client.send( | ||
new HeadObjectCommand({ | ||
Bucket: this.#options.bucket, | ||
Key: s3Key, | ||
}), | ||
); | ||
|
||
if (!head.Metadata) { | ||
return undefined; | ||
} | ||
|
||
edoardocavazza marked this conversation as resolved.
Show resolved
Hide resolved
|
||
const expiresAtStr = head.Metadata?.['expires-at']; | ||
if (expiresAtStr && Date.now() > Number.parseInt(expiresAtStr)) { | ||
edoardocavazza marked this conversation as resolved.
Show resolved
Hide resolved
|
||
await this.delete(key); | ||
return undefined; | ||
} | ||
|
||
const res = await this.#client.send( | ||
new GetObjectCommand({ | ||
Bucket: this.#options.bucket, | ||
Key: s3Key, | ||
}), | ||
); | ||
|
||
if (!res.Body) { | ||
return undefined; | ||
} | ||
return res.Body.transformToByteArray() as Promise<V>; | ||
} | ||
|
||
public async set( | ||
key: string, | ||
value: V, | ||
ttl?: number | undefined, | ||
jitter?: JitterMode | JitterFn | undefined, | ||
): Promise<void> { | ||
const s3Key = this.buildKey(key); | ||
|
||
try { | ||
let expiresAt: number | undefined; | ||
ttl = ttl ?? this.#options.defaultTTL; | ||
if (ttl !== undefined) { | ||
const jitterFn = createJitter(jitter ?? this.#options.defaultJitter ?? JitterMode.None); | ||
expiresAt = Date.now() + Math.round(jitterFn(ttl)); | ||
} | ||
|
||
await this.#client.send( | ||
new PutObjectCommand({ | ||
Bucket: this.#options.bucket, | ||
Key: s3Key, | ||
Body: value, | ||
Metadata: expiresAt ? { 'expires-at': `${expiresAt}` } : {}, | ||
}), | ||
); | ||
} catch (err) { | ||
logger.error({ key, err }, 'Got error while trying to set cache key'); | ||
edoardocavazza marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
} | ||
|
||
public async delete(key: string): Promise<void> { | ||
await this.#client.send( | ||
new DeleteObjectCommand({ | ||
Bucket: this.#options.bucket, | ||
Key: this.buildKey(key), | ||
}), | ||
); | ||
} | ||
|
||
public async *keys(prefix?: string): AsyncIterableIterator<string> { | ||
const fullPrefix = this.buildKey(prefix ?? ''); | ||
let cont: string | undefined; | ||
do { | ||
const res = await this.#client.send( | ||
new ListObjectsV2Command({ | ||
Bucket: this.#options.bucket, | ||
Prefix: fullPrefix, | ||
ContinuationToken: cont, | ||
}), | ||
); | ||
for (const obj of res.Contents ?? []) { | ||
if (obj.Key) { | ||
yield obj.Key.slice((this.#options.keyPrefix ?? '').length); | ||
} | ||
} | ||
cont = res.NextContinuationToken; | ||
} while (cont); | ||
} | ||
|
||
public async clear(prefix?: string): Promise<void> { | ||
edoardocavazza marked this conversation as resolved.
Show resolved
Hide resolved
|
||
const toDel: string[] = []; | ||
for await (const k of this.keys(prefix)) { | ||
toDel.push(this.buildKey(k)); | ||
} | ||
while (toDel.length) { | ||
const chunk = toDel.splice(0, 1000); | ||
await this.#client.send( | ||
new DeleteObjectsCommand({ | ||
Bucket: this.#options.bucket, | ||
Delete: { Objects: chunk.map((Key) => ({ Key })) }, | ||
}), | ||
); | ||
} | ||
} | ||
|
||
public async clearPattern(pattern: string): Promise<void> { | ||
const escapedPattern = pattern.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); | ||
const rx = new RegExp('^' + escapedPattern.replace(/\*/g, '.*') + '$'); | ||
const toDel: string[] = []; | ||
for await (const k of this.keys()) { | ||
if (rx.test(k)) { | ||
toDel.push(this.buildKey(k)); | ||
} | ||
} | ||
while (toDel.length) { | ||
const chunk = toDel.splice(0, 1000); | ||
await this.#client.send( | ||
new DeleteObjectsCommand({ | ||
Bucket: this.#options.bucket, | ||
Delete: { Objects: chunk.map((Key) => ({ Key })) }, | ||
}), | ||
); | ||
} | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.