@open-mercato/cache 0.11.1-develop.8593.1.50784dae35 → 0.11.1-develop.8687.1.adb16f62b3

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.
Files changed (61) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/AGENTS.md +27 -21
  3. package/README.md +30 -0
  4. package/dist/codec.js +1 -74
  5. package/dist/codec.js.map +2 -2
  6. package/dist/defaults.js +1 -6
  7. package/dist/defaults.js.map +2 -2
  8. package/dist/errors.js +1 -12
  9. package/dist/errors.js.map +2 -2
  10. package/dist/index.js.map +1 -1
  11. package/dist/patterns.js +1 -35
  12. package/dist/patterns.js.map +2 -2
  13. package/dist/provider.js +440 -0
  14. package/dist/provider.js.map +7 -0
  15. package/dist/redisConnection.js +2 -0
  16. package/dist/redisConnection.js.map +7 -0
  17. package/dist/service.js +320 -80
  18. package/dist/service.js.map +3 -3
  19. package/dist/strategies/jsonfile.js +1 -186
  20. package/dist/strategies/jsonfile.js.map +3 -3
  21. package/dist/strategies/memory.js +1 -196
  22. package/dist/strategies/memory.js.map +3 -3
  23. package/dist/strategies/redis.js +1 -443
  24. package/dist/strategies/redis.js.map +3 -3
  25. package/dist/strategies/sqlite.js +1 -196
  26. package/dist/strategies/sqlite.js.map +3 -3
  27. package/dist/testing/conformance.js +448 -0
  28. package/dist/testing/conformance.js.map +7 -0
  29. package/dist/testing/index.js +12 -0
  30. package/dist/testing/index.js.map +7 -0
  31. package/dist/testing/remote.js +182 -0
  32. package/dist/testing/remote.js.map +7 -0
  33. package/fixtures/build-conformance-host.mjs +58 -0
  34. package/fixtures/cache-provider-fixture/index.d.ts +18 -0
  35. package/fixtures/cache-provider-fixture/index.js +307 -0
  36. package/fixtures/cache-provider-fixture/package.json +25 -0
  37. package/fixtures/conformance-child.mjs +41 -0
  38. package/jest.config.cjs +3 -1
  39. package/package.json +10 -2
  40. package/src/__tests__/cache-di-contract-docs.test.ts +2 -2
  41. package/src/__tests__/conformance.memory-provider.test.ts +77 -0
  42. package/src/__tests__/provider-fixture.packed.test.ts +178 -0
  43. package/src/__tests__/provider.test.ts +469 -0
  44. package/src/__tests__/service.provider.test.ts +513 -0
  45. package/src/__tests__/service.test.ts +94 -3
  46. package/src/codec.ts +1 -94
  47. package/src/defaults.ts +1 -2
  48. package/src/errors.ts +1 -14
  49. package/src/index.ts +4 -0
  50. package/src/patterns.ts +1 -40
  51. package/src/provider.ts +641 -0
  52. package/src/redisConnection.ts +1 -0
  53. package/src/service.ts +396 -89
  54. package/src/strategies/jsonfile.ts +1 -242
  55. package/src/strategies/memory.ts +1 -275
  56. package/src/strategies/redis.ts +1 -615
  57. package/src/strategies/sqlite.ts +1 -292
  58. package/src/testing/conformance.ts +569 -0
  59. package/src/testing/index.ts +11 -0
  60. package/src/testing/remote.ts +240 -0
  61. package/src/types.ts +8 -106
@@ -0,0 +1,569 @@
1
+ import assert from 'node:assert/strict'
2
+ import { randomBytes } from 'node:crypto'
3
+ import type { CacheStrategy, CacheValue } from '../types'
4
+ import { runWithCacheTenant } from '../tenantContext'
5
+ import { validateCacheProviderNamespace } from '../provider'
6
+ import { resolvePhysicalCacheValueKey } from '../service'
7
+ import type { ConformanceRemoteOp, ConformanceRemoteProcess } from './remote'
8
+
9
+ export type { ConformanceRemoteOp, ConformanceRemoteProcess } from './remote'
10
+
11
+ export type ConformanceServiceOptions = {
12
+ /** Forward to `createCacheService({ provider, defaultTtl })`. */
13
+ defaultTtl?: number
14
+ }
15
+
16
+ export type ConformanceCorruptTarget = {
17
+ namespace: string
18
+ tenant: string | null
19
+ /** Logical key passed to the tenant-aware service. */
20
+ key: string
21
+ /** Physical key the tenant-aware wrapper hands to the provider strategy for the value record. */
22
+ physicalKey: string
23
+ }
24
+
25
+ export type CreateConformanceService = (
26
+ namespace: string,
27
+ options?: ConformanceServiceOptions,
28
+ ) => CacheStrategy | Promise<CacheStrategy>
29
+
30
+ export type CacheProviderConformanceOptions = {
31
+ name: string
32
+ /**
33
+ * Build a full tenant-aware service (`createCacheService({ provider })`) for
34
+ * the given deployment namespace. Called several times per test: separate
35
+ * calls with the same namespace MUST share the backing store.
36
+ */
37
+ createService: CreateConformanceService
38
+ /** Spawn an independent process serving operations for the same backing store and namespace. */
39
+ createIndependentProcess?: (namespace: string) => Promise<ConformanceRemoteProcess>
40
+ /** Make the provider's stored value for `physicalKey` undecodable. Enables the corrupt-value test. */
41
+ corrupt?: (target: ConformanceCorruptTarget) => Promise<void>
42
+ /** Number of logical entries written by the batch-boundary test (one more is added to cross it). Default 600. */
43
+ batchSize?: number
44
+ /** Short TTL used by expiry tests, in milliseconds. Default 150. */
45
+ ttlMs?: number
46
+ /** Extra wait after a TTL elapses before asserting expiry. Default 100. */
47
+ ttlGraceMs?: number
48
+ /** Provider retains logically expired records until cleanup (enables `returnExpired` and exact cleanup counts). */
49
+ supportsReturnExpired?: boolean
50
+ /** Per-test timeout in milliseconds. Default 120000. */
51
+ testTimeoutMs?: number
52
+ }
53
+
54
+ type TestBody = () => Promise<void>
55
+
56
+ type TestRunnerGlobals = {
57
+ describe(name: string, body: () => void): void
58
+ it(name: string, body: TestBody, timeout?: number): void
59
+ }
60
+
61
+ function resolveTestRunner(): TestRunnerGlobals {
62
+ const scope = globalThis as unknown as Partial<TestRunnerGlobals>
63
+ if (typeof scope.describe !== 'function' || typeof scope.it !== 'function') {
64
+ throw new Error('[internal] defineCacheProviderConformance requires jest-compatible describe/it globals')
65
+ }
66
+ return { describe: scope.describe, it: scope.it }
67
+ }
68
+
69
+ const DEFAULT_BATCH_SIZE = 600
70
+ const DEFAULT_TTL_MS = 150
71
+ const DEFAULT_TTL_GRACE_MS = 100
72
+ const DEFAULT_TEST_TIMEOUT_MS = 120_000
73
+ const WRITE_CONCURRENCY = 25
74
+
75
+ export function sleep(ms: number): Promise<void> {
76
+ return new Promise((resolve) => setTimeout(resolve, ms))
77
+ }
78
+
79
+ export function randomNamespace(prefix = 'conf'): string {
80
+ const safePrefix = prefix.replace(/[^a-zA-Z0-9._-]/g, '_').slice(0, 40) || 'conf'
81
+ return validateCacheProviderNamespace(`${safePrefix}-${randomBytes(6).toString('hex')}`)
82
+ }
83
+
84
+ function randomTenant(label: string): string {
85
+ return `${label}-${randomBytes(4).toString('hex')}`
86
+ }
87
+
88
+ /**
89
+ * Physical value-record key the tenant-aware wrapper writes for a logical key.
90
+ * Mirrors the wrapper layout in `service.ts`; used only to target corruption.
91
+ */
92
+ export function conformancePhysicalValueKey(key: string, tenant: string | null): string {
93
+ return resolvePhysicalCacheValueKey(key, tenant)
94
+ }
95
+
96
+ export function inCacheTenant<T>(tenant: string | null, fn: () => Promise<T>): Promise<T> {
97
+ return runWithCacheTenant(tenant, fn)
98
+ }
99
+
100
+ export type ConformanceNamespaceContext = {
101
+ namespace: string
102
+ /** Open a tracked service on this namespace (or another tracked namespace). */
103
+ open(options?: ConformanceServiceOptions & { namespace?: string }): Promise<CacheStrategy>
104
+ /** Allocate and track a fresh namespace (closed and cleared on teardown). */
105
+ foreignNamespace(): string
106
+ /** Allocate and track a unique tenant id (cleared on teardown). */
107
+ tenant(label: string): string
108
+ /** Track an independent process; closed on teardown. */
109
+ track(remote: ConformanceRemoteProcess): ConformanceRemoteProcess
110
+ }
111
+
112
+ /**
113
+ * Run `body` with a fresh random namespace. On exit (success or failure) every
114
+ * tracked tenant (plus the global scope) is cleared on every tracked namespace,
115
+ * then all opened services and remotes are closed. Teardown errors are swallowed
116
+ * so they never mask the test failure.
117
+ */
118
+ export async function withConformanceNamespace<T>(
119
+ createService: CreateConformanceService,
120
+ body: (context: ConformanceNamespaceContext) => Promise<T>,
121
+ options: { prefix?: string } = {},
122
+ ): Promise<T> {
123
+ const namespace = randomNamespace(options.prefix)
124
+ const namespaces = new Set<string>([namespace])
125
+ const tenants = new Set<string | null>([null])
126
+ const services: CacheStrategy[] = []
127
+ const remotes: ConformanceRemoteProcess[] = []
128
+
129
+ const context: ConformanceNamespaceContext = {
130
+ namespace,
131
+ async open(openOptions = {}) {
132
+ const target = openOptions.namespace ?? namespace
133
+ namespaces.add(target)
134
+ const service = await createService(target, openOptions.defaultTtl !== undefined ? { defaultTtl: openOptions.defaultTtl } : undefined)
135
+ services.push(service)
136
+ return service
137
+ },
138
+ foreignNamespace() {
139
+ const foreign = randomNamespace(options.prefix)
140
+ namespaces.add(foreign)
141
+ return foreign
142
+ },
143
+ tenant(label) {
144
+ const tenant = randomTenant(label)
145
+ tenants.add(tenant)
146
+ return tenant
147
+ },
148
+ track(remote) {
149
+ remotes.push(remote)
150
+ return remote
151
+ },
152
+ }
153
+
154
+ try {
155
+ return await body(context)
156
+ } finally {
157
+ for (const remote of remotes) {
158
+ await remote.close().catch(() => undefined)
159
+ }
160
+ for (const target of namespaces) {
161
+ let cleaner: CacheStrategy | null = null
162
+ try {
163
+ cleaner = await createService(target)
164
+ for (const tenant of tenants) {
165
+ await runWithCacheTenant(tenant, () => cleaner!.clear()).catch(() => undefined)
166
+ }
167
+ } catch {
168
+ // teardown must not mask the test outcome
169
+ } finally {
170
+ await cleaner?.close?.().catch(() => undefined)
171
+ }
172
+ }
173
+ for (const service of services) {
174
+ await service.close?.().catch(() => undefined)
175
+ }
176
+ }
177
+ }
178
+
179
+ export async function assertCacheHit(service: CacheStrategy, key: string, expected: CacheValue, message?: string): Promise<void> {
180
+ assert.deepEqual(await service.get(key), expected, message ?? `expected cache hit for "${key}"`)
181
+ assert.equal(await service.has(key), true, message ?? `expected has("${key}") to be true`)
182
+ }
183
+
184
+ export async function assertCacheMiss(service: CacheStrategy, key: string, message?: string): Promise<void> {
185
+ assert.equal(await service.get(key), null, message ?? `expected cache miss for "${key}"`)
186
+ assert.equal(await service.has(key), false, message ?? `expected has("${key}") to be false`)
187
+ }
188
+
189
+ function sorted(values: string[]): string[] {
190
+ return [...values].sort((left, right) => (left < right ? -1 : left > right ? 1 : 0))
191
+ }
192
+
193
+ async function writeInChunks(count: number, write: (index: number) => Promise<void>): Promise<void> {
194
+ for (let start = 0; start < count; start += WRITE_CONCURRENCY) {
195
+ const end = Math.min(count, start + WRITE_CONCURRENCY)
196
+ const batch: Promise<void>[] = []
197
+ for (let index = start; index < end; index++) batch.push(write(index))
198
+ await Promise.all(batch)
199
+ }
200
+ }
201
+
202
+ function runRemote(remote: ConformanceRemoteProcess, operation: ConformanceRemoteOp): Promise<unknown> {
203
+ return remote.run(operation)
204
+ }
205
+
206
+ async function settleWithin<T>(promise: Promise<T>, ms: number): Promise<{ status: 'fulfilled'; value: T } | { status: 'rejected'; reason: unknown }> {
207
+ let timer: ReturnType<typeof setTimeout> | null = null
208
+ const timeout = new Promise<never>((_, reject) => {
209
+ timer = setTimeout(() => reject(new Error(`[internal] operation did not settle within ${ms}ms`)), ms)
210
+ })
211
+ try {
212
+ const value = await Promise.race([promise, timeout])
213
+ return { status: 'fulfilled', value }
214
+ } catch (reason) {
215
+ if (reason instanceof Error && reason.message.startsWith('[internal] operation did not settle')) throw reason
216
+ return { status: 'rejected', reason }
217
+ } finally {
218
+ if (timer) clearTimeout(timer)
219
+ }
220
+ }
221
+
222
+ /**
223
+ * Register the provider conformance suite with the ambient jest-compatible
224
+ * `describe`/`it` globals. Every test uses a fresh random namespace and clears
225
+ * the tenants it touched on teardown.
226
+ */
227
+ export function defineCacheProviderConformance(options: CacheProviderConformanceOptions): void {
228
+ const { describe, it } = resolveTestRunner()
229
+ const batchSize = options.batchSize ?? DEFAULT_BATCH_SIZE
230
+ const ttlMs = options.ttlMs ?? DEFAULT_TTL_MS
231
+ const ttlGraceMs = options.ttlGraceMs ?? DEFAULT_TTL_GRACE_MS
232
+ const timeout = options.testTimeoutMs ?? DEFAULT_TEST_TIMEOUT_MS
233
+ const supportsReturnExpired = options.supportsReturnExpired === true
234
+ const createService = options.createService
235
+ const scoped = <T>(body: (context: ConformanceNamespaceContext) => Promise<T>) =>
236
+ withConformanceNamespace(createService, body, { prefix: 'conf' })
237
+
238
+ describe(`cache provider conformance: ${options.name}`, () => {
239
+ it('reports healthy through the service healthcheck', () => scoped(async (ctx) => {
240
+ const service = await ctx.open()
241
+ assert.equal(typeof service.healthcheck, 'function', 'provider-backed services must expose healthcheck()')
242
+ await service.healthcheck!()
243
+ }), timeout)
244
+
245
+ it('round-trips get/set/has/delete for JSON values', () => scoped(async (ctx) => {
246
+ const service = await ctx.open()
247
+ const tenant = ctx.tenant('crud')
248
+ await inCacheTenant(tenant, async () => {
249
+ const values: Array<[string, CacheValue]> = [
250
+ ['object', { id: 1, name: 'Zażółć', nested: { list: [1, 'two', true], empty: {} } }],
251
+ ['array', [1, 2, { three: 3 }]],
252
+ ['string', 'plain text with "quotes" and \n newline'],
253
+ ['number', 42.5],
254
+ ['zero', 0],
255
+ ['boolean', false],
256
+ ]
257
+ await assertCacheMiss(service, 'object')
258
+ for (const [key, value] of values) await service.set(key, value)
259
+ for (const [key, value] of values) await assertCacheHit(service, key, value)
260
+
261
+ await service.set('object', { replaced: true })
262
+ await assertCacheHit(service, 'object', { replaced: true })
263
+
264
+ assert.equal(await service.delete('object'), true)
265
+ await assertCacheMiss(service, 'object')
266
+ assert.equal(await service.delete('object'), false, 'second delete must report nothing removed')
267
+ assert.equal(await service.delete('never-set'), false)
268
+ await assertCacheHit(service, 'array', [1, 2, { three: 3 }])
269
+ })
270
+ }), timeout)
271
+
272
+ it('expires entries after a per-entry TTL', () => scoped(async (ctx) => {
273
+ const service = await ctx.open()
274
+ const tenant = ctx.tenant('ttl')
275
+ await inCacheTenant(tenant, async () => {
276
+ await service.set('short', 'value', { ttl: ttlMs })
277
+ await service.set('forever', 'value')
278
+ await assertCacheHit(service, 'short', 'value')
279
+ await sleep(ttlMs + ttlGraceMs)
280
+ await assertCacheMiss(service, 'short')
281
+ await assertCacheHit(service, 'forever', 'value')
282
+ })
283
+ }), timeout)
284
+
285
+ it('applies the default TTL and lets a per-entry TTL override it', () => scoped(async (ctx) => {
286
+ const service = await ctx.open({ defaultTtl: ttlMs })
287
+ const tenant = ctx.tenant('default-ttl')
288
+ await inCacheTenant(tenant, async () => {
289
+ await service.set('defaulted', 'a')
290
+ await service.set('overridden', 'b', { ttl: 60_000 })
291
+ await assertCacheHit(service, 'defaulted', 'a')
292
+ await sleep(ttlMs + ttlGraceMs)
293
+ await assertCacheMiss(service, 'defaulted')
294
+ await assertCacheHit(service, 'overridden', 'b')
295
+ })
296
+ }), timeout)
297
+
298
+ it('cleanup removes expired entries and keeps live ones', () => scoped(async (ctx) => {
299
+ const service = await ctx.open()
300
+ const tenant = ctx.tenant('cleanup')
301
+ await inCacheTenant(tenant, async () => {
302
+ await service.set('expiring-1', 1, { ttl: ttlMs })
303
+ await service.set('expiring-2', 2, { ttl: ttlMs })
304
+ await service.set('live', 3)
305
+ await sleep(ttlMs + ttlGraceMs)
306
+ if (supportsReturnExpired) {
307
+ assert.equal(await service.get('expiring-1', { returnExpired: true }), 1, 'retained expired value must be readable with returnExpired')
308
+ const before = await service.stats()
309
+ assert.equal(before.size, 3)
310
+ assert.equal(before.expired, 2)
311
+ }
312
+ assert.equal(typeof service.cleanup, 'function', 'provider-backed services must expose cleanup()')
313
+ const removed = await service.cleanup!()
314
+ assert.ok(Number.isInteger(removed) && removed >= 0, 'cleanup must return a non-negative count')
315
+ if (supportsReturnExpired) assert.equal(removed, 2)
316
+ assert.equal(await service.get('expiring-1', { returnExpired: true }), null)
317
+ assert.deepEqual(sorted(await service.keys()), ['live'])
318
+ const after = await service.stats()
319
+ assert.equal(after.size, 1)
320
+ assert.equal(after.expired, 0)
321
+ await assertCacheHit(service, 'live', 3)
322
+ })
323
+ }), timeout)
324
+
325
+ it('deleteByTags removes each entry carrying any tag exactly once', () => scoped(async (ctx) => {
326
+ const service = await ctx.open()
327
+ const tenant = ctx.tenant('tags')
328
+ await inCacheTenant(tenant, async () => {
329
+ await service.set('a', 'a', { tags: ['t1', 't2'] })
330
+ await service.set('b', 'b', { tags: ['t2', 't3'] })
331
+ await service.set('c', 'c', { tags: ['t3'] })
332
+ await service.set('d', 'd')
333
+ assert.equal(await service.deleteByTags(['t1', 't2']), 2, 'overlapping tags must count each entry once')
334
+ await assertCacheMiss(service, 'a')
335
+ await assertCacheMiss(service, 'b')
336
+ await assertCacheHit(service, 'c', 'c')
337
+ await assertCacheHit(service, 'd', 'd')
338
+ assert.equal(await service.deleteByTags(['t1', 't2']), 0, 'repeated invalidation removes nothing')
339
+ assert.equal(await service.deleteByTags(['unknown-tag']), 0)
340
+ assert.equal(await service.deleteByTags([]), 0)
341
+ })
342
+ }), timeout)
343
+
344
+ it('retagging an entry drops its old tag membership', () => scoped(async (ctx) => {
345
+ const service = await ctx.open()
346
+ const tenant = ctx.tenant('retag')
347
+ await inCacheTenant(tenant, async () => {
348
+ await service.set('record', 'v1', { tags: ['old'] })
349
+ await service.set('record', 'v2', { tags: ['new'] })
350
+ assert.equal(await service.deleteByTags(['old']), 0, 'old tag must no longer invalidate the entry')
351
+ await assertCacheHit(service, 'record', 'v2')
352
+ assert.equal(await service.deleteByTags(['new']), 1)
353
+ await assertCacheMiss(service, 'record')
354
+
355
+ await service.set('untagged', 'v1', { tags: ['gone'] })
356
+ await service.set('untagged', 'v2')
357
+ assert.equal(await service.deleteByTags(['gone']), 0)
358
+ assert.equal(await service.clear(), 1, 'an entry overwritten without tags must stay in its tenant scope')
359
+ await assertCacheMiss(service, 'untagged')
360
+ })
361
+ }), timeout)
362
+
363
+ it('enumerates logical keys with glob patterns and reports scoped stats', () => scoped(async (ctx) => {
364
+ const service = await ctx.open()
365
+ const tenant = ctx.tenant('glob')
366
+ const other = ctx.tenant('glob-other')
367
+ await inCacheTenant(other, () => service.set('user:other', 'x'))
368
+ await inCacheTenant(tenant, async () => {
369
+ for (const key of ['user:1', 'user:2', 'user:10', 'order:1']) await service.set(key, key)
370
+ assert.deepEqual(sorted(await service.keys()), ['order:1', 'user:1', 'user:10', 'user:2'])
371
+ assert.deepEqual(sorted(await service.keys('user:*')), ['user:1', 'user:10', 'user:2'])
372
+ assert.deepEqual(sorted(await service.keys('user:?')), ['user:1', 'user:2'])
373
+ assert.deepEqual(await service.keys('missing:*'), [])
374
+ const stats = await service.stats()
375
+ assert.equal(stats.size, 4)
376
+ assert.equal(stats.expired, 0)
377
+ })
378
+ }), timeout)
379
+
380
+ it('scoped clear leaves other tenants and foreign namespaces intact', () => scoped(async (ctx) => {
381
+ const service = await ctx.open()
382
+ const foreign = await ctx.open({ namespace: ctx.foreignNamespace() })
383
+ const tenantA = ctx.tenant('clear-a')
384
+ const tenantB = ctx.tenant('clear-b')
385
+ await inCacheTenant(tenantA, async () => {
386
+ await service.set('one', 1, { tags: ['x'] })
387
+ await service.set('two', 2)
388
+ await service.set('three', 3, { ttl: 60_000 })
389
+ await foreign.set('one', 'foreign')
390
+ })
391
+ await inCacheTenant(tenantB, () => service.set('one', 'b'))
392
+ await inCacheTenant(null, () => service.set('one', 'global'))
393
+
394
+ assert.equal(await inCacheTenant(tenantA, () => service.clear()), 3)
395
+ await inCacheTenant(tenantA, async () => {
396
+ await assertCacheMiss(service, 'one')
397
+ await assertCacheMiss(service, 'two')
398
+ assert.deepEqual(await service.keys(), [])
399
+ assert.equal((await service.stats()).size, 0)
400
+ await assertCacheHit(foreign, 'one', 'foreign')
401
+ })
402
+ await inCacheTenant(tenantB, () => assertCacheHit(service, 'one', 'b'))
403
+ await inCacheTenant(null, () => assertCacheHit(service, 'one', 'global'))
404
+ }), timeout)
405
+
406
+ it('isolates foreign namespaces on the same backing store', () => scoped(async (ctx) => {
407
+ const first = await ctx.open()
408
+ const second = await ctx.open({ namespace: ctx.foreignNamespace() })
409
+ const tenant = ctx.tenant('ns')
410
+ await inCacheTenant(tenant, async () => {
411
+ await first.set('shared-key', 'first', { tags: ['shared-tag'] })
412
+ await second.set('shared-key', 'second', { tags: ['shared-tag'] })
413
+ await second.set('second-only', true)
414
+ await assertCacheHit(first, 'shared-key', 'first')
415
+ await assertCacheHit(second, 'shared-key', 'second')
416
+ assert.deepEqual(sorted(await first.keys()), ['shared-key'])
417
+ assert.equal((await first.stats()).size, 1)
418
+ assert.equal(await first.deleteByTags(['shared-tag']), 1)
419
+ await assertCacheMiss(first, 'shared-key')
420
+ await assertCacheHit(second, 'shared-key', 'second')
421
+ assert.equal(await first.clear(), 0)
422
+ await assertCacheHit(second, 'second-only', true)
423
+ })
424
+ }), timeout)
425
+
426
+ it('keeps interleaved tenant contexts isolated', () => scoped(async (ctx) => {
427
+ const service = await ctx.open()
428
+ const tenants: Array<string | null> = [ctx.tenant('inter-a'), ctx.tenant('inter-b'), null]
429
+ await Promise.all(tenants.map((tenant, index) => inCacheTenant(tenant, async () => {
430
+ for (let round = 0; round < 5; round++) {
431
+ await service.set('same-key', { tenant, round }, { tags: ['round'] })
432
+ await new Promise((resolve) => setImmediate(resolve))
433
+ assert.deepEqual(await service.get('same-key'), { tenant, round })
434
+ }
435
+ await service.set(`only-${index}`, index)
436
+ })))
437
+ const [tenantA, tenantB] = tenants
438
+ assert.equal(await inCacheTenant(tenantA, () => service.deleteByTags(['round'])), 1)
439
+ await inCacheTenant(tenantA, () => assertCacheMiss(service, 'same-key'))
440
+ await inCacheTenant(tenantB, () => assertCacheHit(service, 'same-key', { tenant: tenantB, round: 4 }))
441
+ await inCacheTenant(null, () => assertCacheHit(service, 'same-key', { tenant: null, round: 4 }))
442
+ await inCacheTenant(tenantB, async () => {
443
+ assert.deepEqual(sorted(await service.keys()), ['only-1', 'same-key'])
444
+ })
445
+ }), timeout)
446
+
447
+ it('propagates writes and invalidations across separate service instances', () => scoped(async (ctx) => {
448
+ const writer = await ctx.open()
449
+ const reader = await ctx.open()
450
+ const tenant = ctx.tenant('cross')
451
+ await inCacheTenant(tenant, async () => {
452
+ await writer.set('record', 'v1', { tags: ['records'] })
453
+ await assertCacheHit(reader, 'record', 'v1')
454
+ assert.equal(await reader.deleteByTags(['records']), 1)
455
+ await assertCacheMiss(writer, 'record')
456
+
457
+ await writer.set('retagged', 'v1', { tags: ['old'] })
458
+ await reader.set('retagged', 'v2', { tags: ['new'] })
459
+ assert.equal(await writer.deleteByTags(['old']), 0)
460
+ await assertCacheHit(writer, 'retagged', 'v2')
461
+ assert.equal(await writer.deleteByTags(['old', 'new', 'other']), 1)
462
+ await assertCacheMiss(reader, 'retagged')
463
+
464
+ await reader.set('deleted', 1)
465
+ assert.equal(await writer.delete('deleted'), true)
466
+ await assertCacheMiss(reader, 'deleted')
467
+ })
468
+ }), timeout)
469
+
470
+ if (options.createIndependentProcess) {
471
+ const createIndependentProcess = options.createIndependentProcess
472
+ it('propagates writes and invalidations to and from an independent process', () => scoped(async (ctx) => {
473
+ const local = await ctx.open()
474
+ const remote = ctx.track(await createIndependentProcess(ctx.namespace))
475
+ const tenant = ctx.tenant('remote')
476
+ const other = ctx.tenant('remote-other')
477
+
478
+ await inCacheTenant(tenant, () => local.set('from-parent', { by: 'parent' }, { tags: ['parent-tag'] }))
479
+ assert.deepEqual(await runRemote(remote, { op: 'get', tenant, key: 'from-parent' }), { by: 'parent' })
480
+ assert.equal(await runRemote(remote, { op: 'deleteByTags', tenant, tags: ['parent-tag'] }), 1)
481
+ await inCacheTenant(tenant, () => assertCacheMiss(local, 'from-parent'))
482
+
483
+ await runRemote(remote, { op: 'set', tenant, key: 'from-child', value: { by: 'child' }, tags: ['child-tag'] })
484
+ await runRemote(remote, { op: 'set', tenant: other, key: 'from-child', value: 'other-tenant', tags: ['child-tag'] })
485
+ await inCacheTenant(tenant, async () => {
486
+ await assertCacheHit(local, 'from-child', { by: 'child' })
487
+ assert.deepEqual(await local.keys('from-*'), ['from-child'])
488
+ assert.equal(await local.deleteByTags(['child-tag']), 1)
489
+ })
490
+ assert.equal(await runRemote(remote, { op: 'has', tenant, key: 'from-child' }), false)
491
+ assert.equal(await runRemote(remote, { op: 'get', tenant: other, key: 'from-child' }), 'other-tenant')
492
+
493
+ await inCacheTenant(tenant, async () => {
494
+ await local.set('record', 'v1', { tags: ['old'] })
495
+ await local.set('unrelated', 'keep', { tags: ['unrelated'] })
496
+ })
497
+ await runRemote(remote, { op: 'set', tenant, key: 'record', value: 'v2', tags: ['new-1'] })
498
+ await inCacheTenant(tenant, async () => {
499
+ assert.equal(await local.deleteByTags(['old', 'new-1', 'new-2']), 1, 'remote retag must be honoured exactly once')
500
+ await assertCacheMiss(local, 'record')
501
+ await assertCacheHit(local, 'unrelated', 'keep')
502
+ })
503
+
504
+ assert.equal(await runRemote(remote, { op: 'clear', tenant: other }), 1)
505
+ await inCacheTenant(tenant, () => assertCacheHit(local, 'unrelated', 'keep'))
506
+ await inCacheTenant(other, () => assertCacheMiss(local, 'from-child'))
507
+ }), timeout)
508
+ }
509
+
510
+ if (options.corrupt) {
511
+ const corrupt = options.corrupt
512
+ it('treats a corrupt stored value as a miss and recovers on rewrite', () => scoped(async (ctx) => {
513
+ const service = await ctx.open()
514
+ const tenant = ctx.tenant('corrupt')
515
+ await inCacheTenant(tenant, async () => {
516
+ await service.set('broken', { ok: true }, { tags: ['corrupt-tag'] })
517
+ await service.set('healthy', { ok: true })
518
+ await corrupt({ namespace: ctx.namespace, tenant, key: 'broken', physicalKey: conformancePhysicalValueKey('broken', tenant) })
519
+ await assertCacheMiss(service, 'broken')
520
+ await assertCacheHit(service, 'healthy', { ok: true })
521
+ await service.set('broken', { ok: 'again' })
522
+ await assertCacheHit(service, 'broken', { ok: 'again' })
523
+ })
524
+ }), timeout)
525
+ }
526
+
527
+ it(`crosses the batch boundary with ${batchSize + 1} entries`, () => scoped(async (ctx) => {
528
+ const service = await ctx.open()
529
+ const tenant = ctx.tenant('batch')
530
+ const other = ctx.tenant('batch-other')
531
+ const count = batchSize + 1
532
+ await inCacheTenant(other, () => service.set('bulk:0', 'other', { tags: ['bulk', 'even'] }))
533
+ await inCacheTenant(tenant, async () => {
534
+ await writeInChunks(count, (index) => service.set(`bulk:${index}`, index, { tags: index % 2 === 0 ? ['bulk', 'even'] : ['bulk'] }))
535
+ assert.equal((await service.keys('bulk:*')).length, count)
536
+ assert.equal((await service.stats()).size, count)
537
+ const evens = Math.ceil(count / 2)
538
+ assert.equal(await service.deleteByTags(['even']), evens)
539
+ assert.equal((await service.keys('bulk:*')).length, count - evens)
540
+ await assertCacheMiss(service, 'bulk:0')
541
+ await assertCacheHit(service, 'bulk:1', 1)
542
+ assert.equal(await service.deleteByTags(['bulk', 'even']), count - evens)
543
+ assert.equal((await service.stats()).size, 0)
544
+ })
545
+ await inCacheTenant(other, () => assertCacheHit(service, 'bulk:0', 'other'))
546
+ }), timeout)
547
+
548
+ it('closes idempotently and a closed service reconnects or fails cleanly', () => scoped(async (ctx) => {
549
+ const service = await ctx.open()
550
+ const tenant = ctx.tenant('close')
551
+ await inCacheTenant(tenant, () => service.set('persisted', 'value'))
552
+ assert.equal(typeof service.close, 'function', 'provider-backed services must expose close()')
553
+ await service.close!()
554
+ await service.close!()
555
+ await Promise.all([service.close!(), service.close!()])
556
+
557
+ const outcome = await settleWithin(inCacheTenant(tenant, () => service.get('persisted')), 15_000)
558
+ if (outcome.status === 'rejected') {
559
+ assert.ok(outcome.reason instanceof Error, 'a closed service must fail with an Error')
560
+ } else {
561
+ assert.ok(outcome.value === 'value' || outcome.value === null, 'a reconnected service returns the stored value or a miss')
562
+ }
563
+ await service.close!()
564
+
565
+ const reopened = await ctx.open()
566
+ await inCacheTenant(tenant, () => assertCacheHit(reopened, 'persisted', 'value'))
567
+ }), timeout)
568
+ })
569
+ }
@@ -0,0 +1,11 @@
1
+ export * from './conformance'
2
+ export {
3
+ executeConformanceRemoteOp,
4
+ serveConformanceRemoteOps,
5
+ spawnConformanceRemoteProcess,
6
+ } from './remote'
7
+ export type {
8
+ ConformanceRemoteRequest,
9
+ ConformanceRemoteResponse,
10
+ SpawnConformanceRemoteOptions,
11
+ } from './remote'