@open-mercato/cache-redis-protocol 0.0.0-stage → 0.11.1-develop.9003.1.ce86c31a07

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,413 @@
1
+ import type { CacheGetOptions, CacheSetOptions, CacheStrategy, CacheValue } from '@open-mercato/cache/types'
2
+ import type { CacheProviderHelpers, CacheProviderLogger } from '@open-mercato/cache/provider'
3
+ import type { RespClient, RespManagedClient } from './client'
4
+ import { isClusterClient } from './cluster'
5
+ import { buildRespKeyLayout, RESP_LAYOUT_VERSION } from './layout'
6
+ import type { RespKeyLayout } from './layout'
7
+ import { DELETE_IF_UNCHANGED, REAP_TAG_MEMBERS, sha1Hex, WRITE_ENTRY } from './scripts'
8
+ import type { RespScript } from './scripts'
9
+ import { RESP_DEFAULTS } from './settings'
10
+
11
+ export type RespCacheStrategyTimeouts = {
12
+ /** Upper bound for establishing the first connection inside `createRespCacheStrategy`. */
13
+ connectMs?: number
14
+ }
15
+
16
+ export type RespCacheStrategyOptions = {
17
+ namespace: string
18
+ helpers: CacheProviderHelpers
19
+ logger?: CacheProviderLogger
20
+ defaultTtl?: number
21
+ /** SCAN/SSCAN COUNT hint and the number of entries per MGET/script call. */
22
+ batchSize?: number
23
+ /** Encoded entries above this size are not stored; the previous value is removed instead. */
24
+ maxValueBytes?: number
25
+ timeouts?: RespCacheStrategyTimeouts
26
+ /** Attempts for multi-key commands answered with TRYAGAIN during cluster slot migration (50 ms apart). */
27
+ tryAgainAttempts?: number
28
+ }
29
+
30
+ export type RespCacheStrategy = CacheStrategy & {
31
+ healthcheck(): Promise<void>
32
+ cleanup(): Promise<number>
33
+ close(): Promise<void>
34
+ }
35
+
36
+ export type RespStrategyClientFactory = () => RespClient | RespManagedClient | Promise<RespClient | RespManagedClient>
37
+
38
+ type RespEntry = {
39
+ v: typeof RESP_LAYOUT_VERSION
40
+ value: CacheValue
41
+ tags: string[]
42
+ expiresAt: number | null
43
+ }
44
+
45
+ type Deletion = { valueKey: string; member: string; digest: string; tagKeys: string[] }
46
+ type StaleMember = { valueKey: string; member: string; digest: string }
47
+
48
+ const NO_LOGGER: CacheProviderLogger = { warn() {}, error() {} }
49
+
50
+ function isManagedClient(value: RespClient | RespManagedClient): value is RespManagedClient {
51
+ return typeof (value as RespManagedClient).dispose === 'function' && 'client' in value
52
+ }
53
+
54
+ function isRespEntry(value: unknown): value is RespEntry {
55
+ if (typeof value !== 'object' || value === null) return false
56
+ const record = value as Record<string, unknown>
57
+ return record.v === RESP_LAYOUT_VERSION
58
+ && 'value' in record
59
+ && Array.isArray(record.tags)
60
+ && record.tags.every((tag) => typeof tag === 'string')
61
+ && (record.expiresAt === null || typeof record.expiresAt === 'number')
62
+ }
63
+
64
+ function uniqueTags(tags: unknown): string[] {
65
+ if (!Array.isArray(tags)) return []
66
+ return Array.from(new Set(tags.filter((tag): tag is string => typeof tag === 'string' && tag.length > 0)))
67
+ }
68
+
69
+ function isNoScriptError(error: unknown): boolean {
70
+ return error instanceof Error && error.message.startsWith('NOSCRIPT')
71
+ }
72
+
73
+ const TRY_AGAIN_DELAY_MS = 50
74
+
75
+ function isTryAgainError(error: unknown): boolean {
76
+ if (!(error instanceof Error)) return false
77
+ if (error.message.includes('TRYAGAIN')) return true
78
+ const previous = (error as { previousErrors?: unknown }).previousErrors
79
+ return Array.isArray(previous) && previous.some((entry) => entry instanceof Error && entry.message.includes('TRYAGAIN'))
80
+ }
81
+
82
+ /**
83
+ * Multi-key commands (MULTI, scripts, MGET) get TRYAGAIN while their slot is
84
+ * being migrated between cluster nodes. Retry them for a bounded number of
85
+ * attempts; single-key commands are redirected by the client itself.
86
+ */
87
+ async function retryTryAgain<T>(attempts: number, operation: () => Promise<T>): Promise<T> {
88
+ for (let attempt = 1; ; attempt += 1) {
89
+ try {
90
+ return await operation()
91
+ } catch (error) {
92
+ if (!isTryAgainError(error) || attempt >= attempts) throw error
93
+ await new Promise((resolve) => setTimeout(resolve, TRY_AGAIN_DELAY_MS))
94
+ }
95
+ }
96
+ }
97
+
98
+ function withTimeout<T>(promise: Promise<T>, ms: number, message: string): Promise<T> {
99
+ let timer: ReturnType<typeof setTimeout> | null = null
100
+ const timeout = new Promise<never>((_, reject) => {
101
+ timer = setTimeout(() => reject(new Error(message)), ms)
102
+ })
103
+ return Promise.race([promise, timeout]).finally(() => {
104
+ if (timer) clearTimeout(timer)
105
+ })
106
+ }
107
+
108
+ function waitUntilReady(client: RespClient): Promise<void> {
109
+ if (client.status === 'ready') return Promise.resolve()
110
+ return new Promise<void>((resolve, reject) => {
111
+ const onReady = () => {
112
+ client.off('end', onEnd)
113
+ resolve()
114
+ }
115
+ const onEnd = () => {
116
+ client.off('ready', onReady)
117
+ reject(new Error('[internal] RESP connection ended before it became ready'))
118
+ }
119
+ client.once('ready', onReady)
120
+ client.once('end', onEnd)
121
+ })
122
+ }
123
+
124
+ async function connectClient(client: RespClient, timeoutMs: number): Promise<void> {
125
+ if (client.status === 'ready') return
126
+ const connecting = client.status === 'wait' ? client.connect().then(() => waitUntilReady(client)) : waitUntilReady(client)
127
+ await withTimeout(connecting, timeoutMs, `[internal] RESP connection was not ready within ${timeoutMs}ms`)
128
+ }
129
+
130
+ /**
131
+ * CacheStrategy over a RESP (Redis protocol) server for already tenant-scoped
132
+ * physical keys.
133
+ *
134
+ * Layout (version 1), with `<ns>` the deployment namespace:
135
+ * - `om:{<ns>}:v:<physicalKey>` holds the encoded entry `{ v, value, tags, expiresAt }`
136
+ * with a native `PX` TTL;
137
+ * - `om:{<ns>}:t:<tag>` is a set of physical keys indexed under that tag, expiring
138
+ * no earlier than its longest-lived member.
139
+ *
140
+ * The `{<ns>}` hash tag puts every key of a namespace in one cluster slot so a
141
+ * value and its tag sets can be written and compared/deleted in one script. The trade-off: one namespace never spreads across cluster shards.
142
+ */
143
+ export async function createRespCacheStrategy(
144
+ clientFactory: RespStrategyClientFactory,
145
+ options: RespCacheStrategyOptions,
146
+ ): Promise<RespCacheStrategy> {
147
+ const layout: RespKeyLayout = buildRespKeyLayout(options.namespace)
148
+ const helpers = options.helpers
149
+ const logger = options.logger ?? NO_LOGGER
150
+ const batchSize = options.batchSize ?? RESP_DEFAULTS.batchSize
151
+ const maxValueBytes = options.maxValueBytes ?? RESP_DEFAULTS.maxValueBytes
152
+ const connectMs = options.timeouts?.connectMs ?? RESP_DEFAULTS.connectTimeoutMs
153
+ const defaultTtl = options.defaultTtl
154
+ const tryAgainAttempts = Math.max(1, options.tryAgainAttempts ?? RESP_DEFAULTS.tryAgainAttempts)
155
+
156
+ const created = await clientFactory()
157
+ const client = isManagedClient(created) ? created.client : created
158
+ const dispose = isManagedClient(created) ? () => created.dispose() : () => undefined
159
+
160
+ try {
161
+ await connectClient(client, connectMs)
162
+ } catch (error) {
163
+ dispose()
164
+ client.disconnect()
165
+ throw error
166
+ }
167
+
168
+ async function runScript(script: RespScript, keys: string[], args: Array<string | Buffer>): Promise<number> {
169
+ const result = await retryTryAgain(tryAgainAttempts, async (): Promise<unknown> => {
170
+ try {
171
+ return await client.evalsha(script.sha, keys.length, ...keys, ...args)
172
+ } catch (error) {
173
+ if (!isNoScriptError(error)) throw error
174
+ return client.eval(script.source, keys.length, ...keys, ...args)
175
+ }
176
+ })
177
+ return typeof result === 'number' ? result : Number(result ?? 0)
178
+ }
179
+
180
+ async function scanEach(match: string, visit: (keys: string[]) => Promise<void>): Promise<void> {
181
+ const nodes = isClusterClient(client) ? client.nodes('master') : [client]
182
+ for (const node of nodes) {
183
+ let cursor = '0'
184
+ do {
185
+ const [next, keys] = await node.scan(cursor, 'MATCH', match, 'COUNT', batchSize)
186
+ cursor = next
187
+ if (keys.length > 0) await visit(keys)
188
+ } while (cursor !== '0')
189
+ }
190
+ }
191
+
192
+ async function sscanEach(key: string, visit: (members: string[]) => Promise<void>): Promise<void> {
193
+ let cursor = '0'
194
+ do {
195
+ const [next, members] = await client.sscan(key, cursor, 'COUNT', batchSize)
196
+ cursor = next
197
+ if (members.length > 0) await visit(members)
198
+ } while (cursor !== '0')
199
+ }
200
+
201
+ function decodeEntry(raw: Buffer): RespEntry | null {
202
+ try {
203
+ const parsed: unknown = JSON.parse(helpers.decode(raw))
204
+ return isRespEntry(parsed) ? parsed : null
205
+ } catch {
206
+ return null
207
+ }
208
+ }
209
+
210
+ async function deleteIfUnchanged(deletions: Deletion[]): Promise<number> {
211
+ if (deletions.length === 0) return 0
212
+ const keys: string[] = []
213
+ const args: string[] = []
214
+ for (const deletion of deletions) {
215
+ keys.push(deletion.valueKey, ...deletion.tagKeys)
216
+ args.push(deletion.digest, deletion.member, String(deletion.tagKeys.length))
217
+ }
218
+ return runScript(DELETE_IF_UNCHANGED, keys, args)
219
+ }
220
+
221
+ async function reapMembers(tagKey: string, stale: StaleMember[]): Promise<number> {
222
+ if (stale.length === 0) return 0
223
+ return runScript(
224
+ REAP_TAG_MEMBERS,
225
+ [tagKey, ...stale.map((entry) => entry.valueKey)],
226
+ stale.flatMap((entry) => [entry.member, entry.digest]),
227
+ )
228
+ }
229
+
230
+ async function readEntry(key: string): Promise<RespEntry | null> {
231
+ const valueKey = layout.valueKey(key)
232
+ const raw = await client.getBuffer(valueKey)
233
+ if (!raw) return null
234
+ const entry = decodeEntry(raw)
235
+ if (entry) return entry
236
+ logger.warn('dropping undecodable cache entry')
237
+ await deleteIfUnchanged([{ valueKey, member: key, digest: sha1Hex(raw), tagKeys: [] }])
238
+ return null
239
+ }
240
+
241
+ async function readValues(valueKeys: string[]): Promise<Array<Buffer | null>> {
242
+ return retryTryAgain(tryAgainAttempts, () => client.mgetBuffer(...valueKeys))
243
+ }
244
+
245
+ async function invalidateMembers(tagKey: string, members: string[], wanted: Set<string>): Promise<number> {
246
+ const valueKeys = members.map((member) => layout.valueKey(member))
247
+ const raws = await readValues(valueKeys)
248
+ const deletions: Deletion[] = []
249
+ const stale: StaleMember[] = []
250
+ members.forEach((member, index) => {
251
+ const valueKey = valueKeys[index]
252
+ const raw = raws[index]
253
+ if (!raw) {
254
+ stale.push({ valueKey, member, digest: '' })
255
+ return
256
+ }
257
+ const digest = sha1Hex(raw)
258
+ const entry = decodeEntry(raw)
259
+ if (!entry) {
260
+ deletions.push({ valueKey, member, digest, tagKeys: [tagKey] })
261
+ return
262
+ }
263
+ if (entry.tags.some((tag) => wanted.has(tag))) {
264
+ const tagKeys = new Set(entry.tags.map((tag) => layout.tagKey(tag)))
265
+ tagKeys.add(tagKey)
266
+ deletions.push({ valueKey, member, digest, tagKeys: Array.from(tagKeys) })
267
+ return
268
+ }
269
+ stale.push({ valueKey, member, digest })
270
+ })
271
+ const removed = await deleteIfUnchanged(deletions)
272
+ await reapMembers(tagKey, stale)
273
+ return removed
274
+ }
275
+
276
+ async function unlinkAll(match: string): Promise<number> {
277
+ let removed = 0
278
+ await scanEach(match, async (keys) => {
279
+ removed += await client.unlink(...keys)
280
+ })
281
+ return removed
282
+ }
283
+
284
+ async function reapMissingTagMembers(): Promise<void> {
285
+ await scanEach(layout.tagScanPattern(), async (tagKeys) => {
286
+ for (const tagKey of tagKeys) {
287
+ await sscanEach(tagKey, async (members) => {
288
+ const valueKeys = members.map((member) => layout.valueKey(member))
289
+ const raws = await readValues(valueKeys)
290
+ const missing: StaleMember[] = []
291
+ raws.forEach((raw, index) => {
292
+ if (!raw) missing.push({ valueKey: valueKeys[index], member: members[index], digest: '' })
293
+ })
294
+ await reapMembers(tagKey, missing)
295
+ })
296
+ }
297
+ })
298
+ }
299
+
300
+ let closing: Promise<void> | null = null
301
+
302
+ return {
303
+ async get(key: string, _options?: CacheGetOptions) {
304
+ const entry = await readEntry(key)
305
+ return entry ? entry.value : null
306
+ },
307
+
308
+ async set(key: string, value: CacheValue, setOptions?: CacheSetOptions) {
309
+ const valueKey = layout.valueKey(key)
310
+ const ttl = setOptions?.ttl ?? defaultTtl
311
+ const ttlMs = typeof ttl === 'number' && Number.isFinite(ttl) && ttl > 0 ? Math.ceil(ttl) : null
312
+ const tags = uniqueTags(setOptions?.tags)
313
+ const entry: RespEntry = {
314
+ v: RESP_LAYOUT_VERSION,
315
+ value: value === undefined ? null : value,
316
+ tags,
317
+ expiresAt: ttlMs !== null ? Date.now() + ttlMs : null,
318
+ }
319
+ const payload = helpers.encode(JSON.stringify(entry))
320
+ const size = typeof payload === 'string' ? Buffer.byteLength(payload) : payload.length
321
+ if (size > maxValueBytes) {
322
+ await client.del(valueKey)
323
+ logger.warn('cache entry exceeds maxValueBytes; previous value removed and the write skipped', { bytes: size, limit: maxValueBytes })
324
+ return
325
+ }
326
+ await runScript(
327
+ WRITE_ENTRY,
328
+ [valueKey, ...tags.map((tag) => layout.tagKey(tag))],
329
+ [payload, ttlMs === null ? '' : String(ttlMs), key],
330
+ )
331
+ },
332
+
333
+ async has(key: string) {
334
+ return (await readEntry(key)) !== null
335
+ },
336
+
337
+ async delete(key: string) {
338
+ return (await client.del(layout.valueKey(key))) > 0
339
+ },
340
+
341
+ async deleteByTags(tags: string[]) {
342
+ const wantedTags = uniqueTags(tags)
343
+ if (wantedTags.length === 0) return 0
344
+ const wanted = new Set(wantedTags)
345
+ const handled = new Set<string>()
346
+ let removed = 0
347
+ for (const tag of wantedTags) {
348
+ const tagKey = layout.tagKey(tag)
349
+ await sscanEach(tagKey, async (members) => {
350
+ const fresh = members.filter((member) => !handled.has(member))
351
+ for (const member of fresh) handled.add(member)
352
+ for (let start = 0; start < fresh.length; start += batchSize) {
353
+ removed += await invalidateMembers(tagKey, fresh.slice(start, start + batchSize), wanted)
354
+ }
355
+ })
356
+ }
357
+ return removed
358
+ },
359
+
360
+ async clear() {
361
+ const removed = await unlinkAll(layout.valueScanPattern())
362
+ await reapMissingTagMembers()
363
+ return removed
364
+ },
365
+
366
+ async keys(pattern?: string) {
367
+ const found = new Set<string>()
368
+ await scanEach(layout.valueScanPattern(pattern), async (valueKeys) => {
369
+ for (const valueKey of valueKeys) {
370
+ const physicalKey = layout.physicalKeyFromValueKey(valueKey)
371
+ if (physicalKey === null) continue
372
+ if (pattern && !helpers.matchPattern(physicalKey, pattern)) continue
373
+ found.add(physicalKey)
374
+ }
375
+ })
376
+ return Array.from(found)
377
+ },
378
+
379
+ async stats() {
380
+ let size = 0
381
+ await scanEach(layout.valueScanPattern(), async (valueKeys) => {
382
+ size += valueKeys.length
383
+ })
384
+ return { size, expired: 0 }
385
+ },
386
+
387
+ async cleanup() {
388
+ await reapMissingTagMembers()
389
+ return 0
390
+ },
391
+
392
+ async healthcheck() {
393
+ if (closing || client.status === 'end') throw new Error('[internal] RESP cache client is closed')
394
+ const reply = await client.ping()
395
+ if (reply !== 'PONG') throw new Error('[internal] RESP cache healthcheck returned an unexpected reply')
396
+ },
397
+
398
+ close() {
399
+ if (!closing) {
400
+ closing = (async () => {
401
+ dispose()
402
+ if (client.status === 'end') return
403
+ try {
404
+ await client.quit()
405
+ } catch {
406
+ client.disconnect()
407
+ }
408
+ })()
409
+ }
410
+ return closing
411
+ },
412
+ }
413
+ }