@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.
- package/.turbo/turbo-build.log +1 -1
- package/AGENTS.md +27 -21
- package/README.md +30 -0
- package/dist/codec.js +1 -74
- package/dist/codec.js.map +2 -2
- package/dist/defaults.js +1 -6
- package/dist/defaults.js.map +2 -2
- package/dist/errors.js +1 -12
- package/dist/errors.js.map +2 -2
- package/dist/index.js.map +1 -1
- package/dist/patterns.js +1 -35
- package/dist/patterns.js.map +2 -2
- package/dist/provider.js +440 -0
- package/dist/provider.js.map +7 -0
- package/dist/redisConnection.js +2 -0
- package/dist/redisConnection.js.map +7 -0
- package/dist/service.js +320 -80
- package/dist/service.js.map +3 -3
- package/dist/strategies/jsonfile.js +1 -186
- package/dist/strategies/jsonfile.js.map +3 -3
- package/dist/strategies/memory.js +1 -196
- package/dist/strategies/memory.js.map +3 -3
- package/dist/strategies/redis.js +1 -443
- package/dist/strategies/redis.js.map +3 -3
- package/dist/strategies/sqlite.js +1 -196
- package/dist/strategies/sqlite.js.map +3 -3
- package/dist/testing/conformance.js +448 -0
- package/dist/testing/conformance.js.map +7 -0
- package/dist/testing/index.js +12 -0
- package/dist/testing/index.js.map +7 -0
- package/dist/testing/remote.js +182 -0
- package/dist/testing/remote.js.map +7 -0
- package/fixtures/build-conformance-host.mjs +58 -0
- package/fixtures/cache-provider-fixture/index.d.ts +18 -0
- package/fixtures/cache-provider-fixture/index.js +307 -0
- package/fixtures/cache-provider-fixture/package.json +25 -0
- package/fixtures/conformance-child.mjs +41 -0
- package/jest.config.cjs +3 -1
- package/package.json +10 -2
- package/src/__tests__/cache-di-contract-docs.test.ts +2 -2
- package/src/__tests__/conformance.memory-provider.test.ts +77 -0
- package/src/__tests__/provider-fixture.packed.test.ts +178 -0
- package/src/__tests__/provider.test.ts +469 -0
- package/src/__tests__/service.provider.test.ts +513 -0
- package/src/__tests__/service.test.ts +94 -3
- package/src/codec.ts +1 -94
- package/src/defaults.ts +1 -2
- package/src/errors.ts +1 -14
- package/src/index.ts +4 -0
- package/src/patterns.ts +1 -40
- package/src/provider.ts +641 -0
- package/src/redisConnection.ts +1 -0
- package/src/service.ts +396 -89
- package/src/strategies/jsonfile.ts +1 -242
- package/src/strategies/memory.ts +1 -275
- package/src/strategies/redis.ts +1 -615
- package/src/strategies/sqlite.ts +1 -292
- package/src/testing/conformance.ts +569 -0
- package/src/testing/index.ts +11 -0
- package/src/testing/remote.ts +240 -0
- package/src/types.ts +8 -106
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process'
|
|
2
|
+
import type { CacheStrategy } from '../types'
|
|
3
|
+
import { runWithCacheTenant } from '../tenantContext'
|
|
4
|
+
|
|
5
|
+
export type ConformanceRemoteOp =
|
|
6
|
+
| { op: 'get'; tenant: string | null; key: string; returnExpired?: boolean }
|
|
7
|
+
| { op: 'set'; tenant: string | null; key: string; value: unknown; tags?: string[]; ttl?: number }
|
|
8
|
+
| { op: 'has'; tenant: string | null; key: string }
|
|
9
|
+
| { op: 'delete'; tenant: string | null; key: string }
|
|
10
|
+
| { op: 'deleteByTags'; tenant: string | null; tags: string[] }
|
|
11
|
+
| { op: 'clear'; tenant: string | null }
|
|
12
|
+
| { op: 'keys'; tenant: string | null; pattern?: string }
|
|
13
|
+
| { op: 'stats'; tenant: string | null }
|
|
14
|
+
|
|
15
|
+
export type ConformanceRemoteProcess = {
|
|
16
|
+
run(operation: ConformanceRemoteOp): Promise<unknown>
|
|
17
|
+
close(): Promise<void>
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export type ConformanceRemoteRequest = { id: number; operation: ConformanceRemoteOp }
|
|
21
|
+
|
|
22
|
+
export type ConformanceRemoteResponse =
|
|
23
|
+
| { id: number; ok: true; result: unknown }
|
|
24
|
+
| { id: number; ok: false; error: string }
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Execute one serializable conformance operation against a cache service inside
|
|
28
|
+
* the operation's tenant scope. Child-process runners use this so the parent
|
|
29
|
+
* suite can drive an independent process with the same semantics.
|
|
30
|
+
*/
|
|
31
|
+
export function executeConformanceRemoteOp(service: CacheStrategy, operation: ConformanceRemoteOp): Promise<unknown> {
|
|
32
|
+
return runWithCacheTenant(operation.tenant, async (): Promise<unknown> => {
|
|
33
|
+
switch (operation.op) {
|
|
34
|
+
case 'get':
|
|
35
|
+
return service.get(operation.key, operation.returnExpired ? { returnExpired: true } : undefined)
|
|
36
|
+
case 'set':
|
|
37
|
+
await service.set(operation.key, operation.value, {
|
|
38
|
+
...(operation.tags ? { tags: operation.tags } : {}),
|
|
39
|
+
...(operation.ttl !== undefined ? { ttl: operation.ttl } : {}),
|
|
40
|
+
})
|
|
41
|
+
return null
|
|
42
|
+
case 'has':
|
|
43
|
+
return service.has(operation.key)
|
|
44
|
+
case 'delete':
|
|
45
|
+
return service.delete(operation.key)
|
|
46
|
+
case 'deleteByTags':
|
|
47
|
+
return service.deleteByTags(operation.tags)
|
|
48
|
+
case 'clear':
|
|
49
|
+
return service.clear()
|
|
50
|
+
case 'keys':
|
|
51
|
+
return service.keys(operation.pattern)
|
|
52
|
+
case 'stats':
|
|
53
|
+
return service.stats()
|
|
54
|
+
default:
|
|
55
|
+
throw new Error('[internal] unknown conformance remote operation')
|
|
56
|
+
}
|
|
57
|
+
})
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Serve conformance operations over newline-delimited JSON (one request per
|
|
62
|
+
* line on `input`, one response per line on `output`). Resolves when `input`
|
|
63
|
+
* ends. Used by independent-process runners.
|
|
64
|
+
*/
|
|
65
|
+
export async function serveConformanceRemoteOps(
|
|
66
|
+
service: CacheStrategy,
|
|
67
|
+
input: AsyncIterable<string | Buffer>,
|
|
68
|
+
write: (line: string) => void,
|
|
69
|
+
): Promise<void> {
|
|
70
|
+
let buffer = ''
|
|
71
|
+
const handleLine = async (line: string) => {
|
|
72
|
+
if (!line.trim()) return
|
|
73
|
+
const request = JSON.parse(line) as ConformanceRemoteRequest
|
|
74
|
+
let response: ConformanceRemoteResponse
|
|
75
|
+
try {
|
|
76
|
+
const result = await executeConformanceRemoteOp(service, request.operation)
|
|
77
|
+
response = { id: request.id, ok: true, result: result === undefined ? null : result }
|
|
78
|
+
} catch (error) {
|
|
79
|
+
response = { id: request.id, ok: false, error: error instanceof Error ? error.message : String(error) }
|
|
80
|
+
}
|
|
81
|
+
write(`${JSON.stringify(response)}\n`)
|
|
82
|
+
}
|
|
83
|
+
for await (const chunk of input) {
|
|
84
|
+
buffer += typeof chunk === 'string' ? chunk : chunk.toString('utf8')
|
|
85
|
+
let newline = buffer.indexOf('\n')
|
|
86
|
+
while (newline >= 0) {
|
|
87
|
+
const line = buffer.slice(0, newline)
|
|
88
|
+
buffer = buffer.slice(newline + 1)
|
|
89
|
+
await handleLine(line)
|
|
90
|
+
newline = buffer.indexOf('\n')
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
if (buffer.trim()) await handleLine(buffer)
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export type SpawnConformanceRemoteOptions = {
|
|
97
|
+
command: string
|
|
98
|
+
args: string[]
|
|
99
|
+
env?: Record<string, string | undefined>
|
|
100
|
+
cwd?: string
|
|
101
|
+
readyTimeoutMs?: number
|
|
102
|
+
operationTimeoutMs?: number
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
type PendingRemoteCall = {
|
|
106
|
+
resolve(value: unknown): void
|
|
107
|
+
reject(error: Error): void
|
|
108
|
+
timer: ReturnType<typeof setTimeout>
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Spawn a child process that serves `serveConformanceRemoteOps` over stdio and
|
|
113
|
+
* return a `ConformanceRemoteProcess` handle for `createIndependentProcess`.
|
|
114
|
+
* The child must print the line `ready` on stdout once its service is built.
|
|
115
|
+
*/
|
|
116
|
+
export async function spawnConformanceRemoteProcess(options: SpawnConformanceRemoteOptions): Promise<ConformanceRemoteProcess> {
|
|
117
|
+
const child = spawn(options.command, options.args, {
|
|
118
|
+
cwd: options.cwd,
|
|
119
|
+
env: options.env ? { ...process.env, ...options.env } : process.env,
|
|
120
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
121
|
+
})
|
|
122
|
+
const operationTimeoutMs = options.operationTimeoutMs ?? 30_000
|
|
123
|
+
const pending = new Map<number, PendingRemoteCall>()
|
|
124
|
+
let stderr = ''
|
|
125
|
+
let stdoutBuffer = ''
|
|
126
|
+
let ready = false
|
|
127
|
+
let exited = false
|
|
128
|
+
let nextId = 1
|
|
129
|
+
let settleReady: { resolve(): void; reject(error: Error): void } | null = null
|
|
130
|
+
const readyPromise = new Promise<void>((resolve, reject) => {
|
|
131
|
+
settleReady = { resolve, reject }
|
|
132
|
+
})
|
|
133
|
+
|
|
134
|
+
const failAll = (error: Error) => {
|
|
135
|
+
settleReady?.reject(error)
|
|
136
|
+
for (const entry of pending.values()) {
|
|
137
|
+
clearTimeout(entry.timer)
|
|
138
|
+
entry.reject(error)
|
|
139
|
+
}
|
|
140
|
+
pending.clear()
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
const handleLine = (line: string) => {
|
|
144
|
+
if (!line) return
|
|
145
|
+
if (!ready) {
|
|
146
|
+
if (line === 'ready') {
|
|
147
|
+
ready = true
|
|
148
|
+
settleReady?.resolve()
|
|
149
|
+
}
|
|
150
|
+
return
|
|
151
|
+
}
|
|
152
|
+
let response: ConformanceRemoteResponse
|
|
153
|
+
try {
|
|
154
|
+
response = JSON.parse(line) as ConformanceRemoteResponse
|
|
155
|
+
} catch {
|
|
156
|
+
return
|
|
157
|
+
}
|
|
158
|
+
const entry = pending.get(response.id)
|
|
159
|
+
if (!entry) return
|
|
160
|
+
pending.delete(response.id)
|
|
161
|
+
clearTimeout(entry.timer)
|
|
162
|
+
if (response.ok) entry.resolve(response.result)
|
|
163
|
+
else entry.reject(new Error(`[internal] remote conformance operation failed: ${response.error}`))
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
child.stderr.setEncoding('utf8')
|
|
167
|
+
child.stderr.on('data', (chunk: string) => {
|
|
168
|
+
stderr = `${stderr}${chunk}`.slice(-4000)
|
|
169
|
+
})
|
|
170
|
+
child.stdout.setEncoding('utf8')
|
|
171
|
+
child.stdout.on('data', (chunk: string) => {
|
|
172
|
+
stdoutBuffer += chunk
|
|
173
|
+
let newline = stdoutBuffer.indexOf('\n')
|
|
174
|
+
while (newline >= 0) {
|
|
175
|
+
const line = stdoutBuffer.slice(0, newline).trim()
|
|
176
|
+
stdoutBuffer = stdoutBuffer.slice(newline + 1)
|
|
177
|
+
newline = stdoutBuffer.indexOf('\n')
|
|
178
|
+
handleLine(line)
|
|
179
|
+
}
|
|
180
|
+
})
|
|
181
|
+
child.on('exit', (code) => {
|
|
182
|
+
exited = true
|
|
183
|
+
failAll(new Error(`[internal] conformance remote process exited with code ${code}: ${stderr.trim()}`))
|
|
184
|
+
})
|
|
185
|
+
child.on('error', (error) => {
|
|
186
|
+
exited = true
|
|
187
|
+
failAll(error)
|
|
188
|
+
})
|
|
189
|
+
|
|
190
|
+
const readyTimeoutMs = options.readyTimeoutMs ?? 30_000
|
|
191
|
+
let readyTimer: ReturnType<typeof setTimeout> | null = null
|
|
192
|
+
try {
|
|
193
|
+
await Promise.race([
|
|
194
|
+
readyPromise,
|
|
195
|
+
new Promise<never>((_, reject) => {
|
|
196
|
+
readyTimer = setTimeout(
|
|
197
|
+
() => reject(new Error(`[internal] conformance remote process not ready within ${readyTimeoutMs}ms: ${stderr.trim()}`)),
|
|
198
|
+
readyTimeoutMs,
|
|
199
|
+
)
|
|
200
|
+
}),
|
|
201
|
+
])
|
|
202
|
+
} catch (error) {
|
|
203
|
+
child.kill('SIGKILL')
|
|
204
|
+
throw error
|
|
205
|
+
} finally {
|
|
206
|
+
if (readyTimer) clearTimeout(readyTimer)
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
let closing: Promise<void> | null = null
|
|
210
|
+
return {
|
|
211
|
+
run(operation) {
|
|
212
|
+
if (exited || closing) return Promise.reject(new Error('[internal] conformance remote process is closed'))
|
|
213
|
+
const id = nextId++
|
|
214
|
+
return new Promise<unknown>((resolve, reject) => {
|
|
215
|
+
const timer = setTimeout(() => {
|
|
216
|
+
pending.delete(id)
|
|
217
|
+
reject(new Error(`[internal] conformance remote operation "${operation.op}" timed out after ${operationTimeoutMs}ms`))
|
|
218
|
+
}, operationTimeoutMs)
|
|
219
|
+
pending.set(id, { resolve, reject, timer })
|
|
220
|
+
const request: ConformanceRemoteRequest = { id, operation }
|
|
221
|
+
child.stdin.write(`${JSON.stringify(request)}\n`)
|
|
222
|
+
})
|
|
223
|
+
},
|
|
224
|
+
close() {
|
|
225
|
+
if (!closing) {
|
|
226
|
+
closing = exited
|
|
227
|
+
? Promise.resolve()
|
|
228
|
+
: new Promise<void>((resolve) => {
|
|
229
|
+
const killTimer = setTimeout(() => child.kill('SIGKILL'), 5_000)
|
|
230
|
+
child.once('exit', () => {
|
|
231
|
+
clearTimeout(killTimer)
|
|
232
|
+
resolve()
|
|
233
|
+
})
|
|
234
|
+
child.stdin.end()
|
|
235
|
+
})
|
|
236
|
+
}
|
|
237
|
+
return closing
|
|
238
|
+
},
|
|
239
|
+
}
|
|
240
|
+
}
|
package/src/types.ts
CHANGED
|
@@ -1,113 +1,15 @@
|
|
|
1
|
-
|
|
1
|
+
import type { ResolvedCacheProvider } from './provider'
|
|
2
2
|
|
|
3
|
-
export type CacheEntry
|
|
4
|
-
key: string
|
|
5
|
-
value: CacheValue
|
|
6
|
-
tags: string[]
|
|
7
|
-
expiresAt: number | null
|
|
8
|
-
/**
|
|
9
|
-
* Wall-clock creation time. Informational/diagnostic only — LRU recency and
|
|
10
|
-
* eviction rely purely on Map insertion order, not on this field.
|
|
11
|
-
*/
|
|
12
|
-
createdAt: number
|
|
13
|
-
}
|
|
14
|
-
|
|
15
|
-
export type CacheOptions = {
|
|
16
|
-
ttl?: number // Time to live in milliseconds
|
|
17
|
-
tags?: string[] // Tags for invalidation
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
export type CacheGetOptions = {
|
|
21
|
-
returnExpired?: boolean // Return expired values (default: false)
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
export type CacheSetOptions = CacheOptions
|
|
25
|
-
|
|
26
|
-
export type CacheStrategy = {
|
|
27
|
-
/**
|
|
28
|
-
* Get a value from cache
|
|
29
|
-
* @param key - Cache key
|
|
30
|
-
* @param options - Get options
|
|
31
|
-
* @returns The cached value or null if not found or expired
|
|
32
|
-
*/
|
|
33
|
-
get(key: string, options?: CacheGetOptions): Promise<CacheValue | null>
|
|
34
|
-
|
|
35
|
-
/**
|
|
36
|
-
* Set a value in cache
|
|
37
|
-
* @param key - Cache key
|
|
38
|
-
* @param value - Value to cache
|
|
39
|
-
* @param options - Cache options (ttl, tags)
|
|
40
|
-
*/
|
|
41
|
-
set(key: string, value: CacheValue, options?: CacheSetOptions): Promise<void>
|
|
42
|
-
|
|
43
|
-
/**
|
|
44
|
-
* Check if a key exists in cache (and is not expired)
|
|
45
|
-
* @param key - Cache key
|
|
46
|
-
* @returns true if key exists and is not expired
|
|
47
|
-
*/
|
|
48
|
-
has(key: string): Promise<boolean>
|
|
49
|
-
|
|
50
|
-
/**
|
|
51
|
-
* Delete a specific key from cache
|
|
52
|
-
* @param key - Cache key
|
|
53
|
-
* @returns true if key was deleted, false if not found
|
|
54
|
-
*/
|
|
55
|
-
delete(key: string): Promise<boolean>
|
|
56
|
-
|
|
57
|
-
/**
|
|
58
|
-
* Delete all keys with specified tags
|
|
59
|
-
* @param tags - Tags to match (any key with ANY of these tags will be deleted)
|
|
60
|
-
* @returns Number of keys deleted
|
|
61
|
-
*/
|
|
62
|
-
deleteByTags(tags: string[]): Promise<number>
|
|
63
|
-
|
|
64
|
-
/**
|
|
65
|
-
* Clear all cache entries
|
|
66
|
-
* @returns Number of keys deleted
|
|
67
|
-
*/
|
|
68
|
-
clear(): Promise<number>
|
|
69
|
-
|
|
70
|
-
/**
|
|
71
|
-
* Get all keys matching a pattern
|
|
72
|
-
* @param pattern - Pattern to match (supports wildcards: * and ?)
|
|
73
|
-
* @returns Array of matching keys
|
|
74
|
-
*/
|
|
75
|
-
keys(pattern?: string): Promise<string[]>
|
|
76
|
-
|
|
77
|
-
/**
|
|
78
|
-
* Get cache statistics
|
|
79
|
-
* @returns Statistics object
|
|
80
|
-
*/
|
|
81
|
-
stats(): Promise<{
|
|
82
|
-
size: number // Total number of entries
|
|
83
|
-
expired: number // Number of expired entries
|
|
84
|
-
// Optional process-global counters surfaced by bounded strategies (memory)
|
|
85
|
-
// so operators can tell whether the LRU cap / sweep is actively protecting
|
|
86
|
-
// the process. Strategies that do not track them omit these fields.
|
|
87
|
-
evictions?: number // Entries dropped by LRU eviction since process start
|
|
88
|
-
sweeps?: number // Amortized expired-entry sweep passes run since process start
|
|
89
|
-
lastSweepReclaimed?: number // Entries reclaimed by the most recent sweep pass
|
|
90
|
-
}>
|
|
91
|
-
|
|
92
|
-
/**
|
|
93
|
-
* Verify the configured backend is reachable without activating a fallback.
|
|
94
|
-
*/
|
|
95
|
-
healthcheck?(): Promise<void>
|
|
96
|
-
|
|
97
|
-
/**
|
|
98
|
-
* Clean up expired entries (optional, some strategies may auto-cleanup)
|
|
99
|
-
* @returns Number of entries removed
|
|
100
|
-
*/
|
|
101
|
-
cleanup?(): Promise<number>
|
|
102
|
-
|
|
103
|
-
/**
|
|
104
|
-
* Close/disconnect the cache strategy
|
|
105
|
-
*/
|
|
106
|
-
close?(): Promise<void>
|
|
107
|
-
}
|
|
3
|
+
export type { CacheEntry, CacheGetOptions, CacheOptions, CacheSetOptions, CacheStrategy, CacheValue } from '@open-mercato/cache-provider-kit'
|
|
108
4
|
|
|
109
5
|
export type CacheServiceOptions = {
|
|
110
6
|
strategy?: 'memory' | 'redis' | 'sqlite' | 'jsonfile'
|
|
7
|
+
/**
|
|
8
|
+
* Explicitly resolved npm cache provider (see `@open-mercato/cache/provider`).
|
|
9
|
+
* Takes precedence over the ambient `CACHE_PROVIDER` selection; combining it
|
|
10
|
+
* with an explicit `strategy` is a `conflicting_selection` error.
|
|
11
|
+
*/
|
|
12
|
+
provider?: ResolvedCacheProvider
|
|
111
13
|
redisUrl?: string
|
|
112
14
|
sqlitePath?: string
|
|
113
15
|
jsonFilePath?: string
|