-
Notifications
You must be signed in to change notification settings - Fork 0
Add a Compressed Redis store #4
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
Open
peter-newman-loke
wants to merge
1
commit into
master
Choose a base branch
from
feature/compressed-redis-store
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+156
−0
Open
Changes from all commits
Commits
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,49 @@ | ||
| import test from "node:test"; | ||
| import assert from "node:assert/strict"; | ||
| import Redis from "ioredis"; | ||
|
|
||
| import { RedisCacheStore, CompressedRedisCacheStore } from "."; | ||
| import { testCache } from "./storetest"; | ||
|
|
||
| const { REDIS_HOST = "localhost" } = process.env; | ||
|
|
||
| test("CompressedRedisCacheStore", async (t) => { | ||
| const redisClient = new Redis(REDIS_HOST); | ||
| t.after(() => redisClient.quit()); | ||
|
|
||
| const cache = new CompressedRedisCacheStore(redisClient); | ||
|
|
||
| await testCache(t, cache); | ||
|
|
||
| const uncompressedCache = new RedisCacheStore(redisClient); | ||
| uncompressedCache.setKeyTemplate("-- test --"); | ||
|
|
||
| await t.test( | ||
| "CompressedRedisCacheStore can read RedisCacheStore entries", | ||
| async () => { | ||
| const key = "object"; | ||
| const value = { a: 1, b: "c" }; | ||
|
|
||
| const expiresAt = Date.now() + 5000; | ||
| await uncompressedCache.set(key, { value, expiresAt }); | ||
|
|
||
| assert.deepEqual(await cache.get(key), { value, expiresAt }); | ||
|
|
||
| await cache.delete(key); | ||
| }, | ||
| ); | ||
| await t.test( | ||
| "RedisCacheStore treats CachedRedisCacheStore entries as misses", | ||
| async () => { | ||
| const key = "object"; | ||
| const value = { a: 1, b: "c" }; | ||
|
|
||
| const expiresAt = Date.now() + 5000; | ||
| await cache.set(key, { value, expiresAt }); | ||
|
|
||
| assert.deepEqual(await uncompressedCache.get(key), undefined); | ||
|
|
||
| await cache.delete(key); | ||
| }, | ||
| ); | ||
| }); |
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,106 @@ | ||
| import { exponentialBuckets, Histogram, linearBuckets } from "prom-client"; | ||
| import type { | ||
| Redis as IORedisClient, | ||
| Cluster as IORedisCluster, | ||
| } from "ioredis"; | ||
|
|
||
| import type { CacheStore, StoreEntity } from "./store"; | ||
| import { metrics } from "./metrics"; | ||
| import { brotliCompress, brotliDecompress, constants } from "node:zlib"; | ||
| import { promisify } from "node:util"; | ||
|
|
||
| const brotliCompressAsync = promisify(brotliCompress); | ||
| const brotliDecompressAsync = promisify(brotliDecompress); | ||
|
|
||
| const cacheValueSize = new Histogram({ | ||
| name: "cache_compressed_redis_value_size_bytes", | ||
| help: "Size of bytes sent to Redis after compression", | ||
| labelNames: ["key"], | ||
| buckets: exponentialBuckets(100, 10, 5), | ||
| registers: [], | ||
| }); | ||
|
|
||
| const cacheCompressionRatio = new Histogram({ | ||
| name: "cache_compressed_ratio", | ||
| help: "Ratio of uncompressed:compressed data", | ||
| labelNames: ["key"], | ||
| buckets: linearBuckets(0, 0.1, 11), | ||
| registers: [], | ||
| }); | ||
|
|
||
| metrics.push(cacheValueSize, cacheCompressionRatio); | ||
|
|
||
| type Client = Pick<IORedisClient | IORedisCluster, "getBuffer" | "set" | "del">; | ||
|
|
||
| // Brotli looks like all the interesting options are on the compressor, | ||
| // which wouldn't change the format of the stored data. But version the magic bytes just in case. | ||
| // Br 26-03 | ||
| const brotli2603MagicBytes = Buffer.from([0x42, 0x72, 0x26, 0x03]); | ||
|
|
||
| export class CompressedRedisCacheStore<T> implements CacheStore<T> { | ||
| private keyTemplate: string | null = null; | ||
|
|
||
| constructor(private client: Client) {} | ||
|
|
||
| setKeyTemplate(keyTemplate: string) { | ||
| if (this.keyTemplate !== null) { | ||
| throw new Error("Cannot change key template"); | ||
| } | ||
|
|
||
| this.keyTemplate = keyTemplate; | ||
| } | ||
|
|
||
| async get(key: string): Promise<StoreEntity<T> | undefined> { | ||
| const rawData = await this.client.getBuffer(key); | ||
|
|
||
| if (rawData === null) return undefined; | ||
|
|
||
| if ( | ||
| rawData | ||
| .subarray(0, brotli2603MagicBytes.length) | ||
| .equals(brotli2603MagicBytes) | ||
| ) { | ||
| return JSON.parse( | ||
| ( | ||
| await brotliDecompressAsync( | ||
| rawData.subarray(brotli2603MagicBytes.length), | ||
| ) | ||
| ).toString("utf8"), | ||
| ); | ||
| } | ||
|
|
||
| try { | ||
| return JSON.parse(rawData.toString("utf8")); | ||
| } catch { | ||
| return undefined; | ||
| } | ||
| } | ||
|
|
||
| async set(key: string, record: StoreEntity<T>): Promise<void> { | ||
| const ttl = record.expiresAt - Date.now(); | ||
| if (ttl <= 0) return; | ||
|
|
||
| const jsonBuffer = Buffer.from(JSON.stringify(record), "utf8"); | ||
| const buf = Buffer.concat([ | ||
| brotli2603MagicBytes, | ||
| await brotliCompressAsync(jsonBuffer, { | ||
| [constants.BROTLI_PARAM_MODE]: constants.BROTLI_MODE_TEXT, | ||
| [constants.BROTLI_PARAM_SIZE_HINT]: jsonBuffer.length, | ||
| }), | ||
| ]); | ||
|
|
||
| if (this.keyTemplate !== null) { | ||
| cacheValueSize.observe({ key: this.keyTemplate }, buf.length); | ||
| cacheCompressionRatio.observe( | ||
| { key: this.keyTemplate }, | ||
| buf.length / jsonBuffer.length, | ||
| ); | ||
| } | ||
|
|
||
| await this.client.set(key, buf, "PX", ttl); | ||
| } | ||
|
|
||
| async delete(key: string): Promise<void> { | ||
| await this.client.del(key); | ||
| } | ||
| } | ||
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
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.
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.
Are these well known magic bytes or just something you came up with, fine either, if it's well known just note itJust clocked that 26-03 is the year and month 🤦
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 was surprised to learn there's no magic bytes in the Brotli compression format itself. I guess it reduces compression ratios.