@open-mercato/cache-redis-protocol 0.0.0-stage → 0.11.1-develop.9002.1.e180dacef1

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/src/client.ts ADDED
@@ -0,0 +1,223 @@
1
+ import { Cluster, Redis } from 'ioredis'
2
+ import type { ClusterOptions, RedisOptions } from 'ioredis'
3
+ import type { RespSettings, RespTlsSettings } from './settings'
4
+ import { isClusterClient } from './cluster'
5
+
6
+ export type RespClient = Redis | Cluster
7
+
8
+ export type RespClientFactory = () => RespClient | Promise<RespClient>
9
+
10
+ export type RespCredentials = {
11
+ username?: string
12
+ password: string
13
+ }
14
+
15
+ /**
16
+ * Supplies fresh credentials (for example a short-lived cloud access token).
17
+ * Called before the first connection, on every reconnect (of the client and of
18
+ * every cluster node), when a cluster node joins and, with `refreshIntervalMs`,
19
+ * on a schedule to re-authenticate live connections.
20
+ */
21
+ export type RespCredentialsProvider = () => Promise<RespCredentials>
22
+
23
+ /**
24
+ * Re-`AUTH` schedule: a fixed interval, or a function evaluated after every
25
+ * refresh returning the delay until the next one (so a token-aware caller can
26
+ * re-authenticate before the current token expires).
27
+ */
28
+ export type RespRefreshSchedule = number | (() => number)
29
+
30
+ export type RespClientFactoryOptions = {
31
+ credentialsProvider?: RespCredentialsProvider
32
+ refreshIntervalMs?: RespRefreshSchedule
33
+ /** Extra ioredis options merged last (managed-service specifics such as `dnsLookup` or `natMap`). */
34
+ redisOptions?: RedisOptions
35
+ clusterOptions?: Omit<ClusterOptions, 'redisOptions'>
36
+ onError?: (error: Error) => void
37
+ }
38
+
39
+ export type RespManagedClient = {
40
+ client: RespClient
41
+ /** Stop credential refresh timers; the strategy calls this on close. */
42
+ dispose(): void
43
+ }
44
+
45
+ /** Lower bound for a scheduled re-`AUTH`, so a misbehaving schedule cannot spin. */
46
+ export const RESP_MIN_REFRESH_DELAY_MS = 100
47
+
48
+ const RECONNECT_BASE_DELAY_MS = 100
49
+ const RECONNECT_MAX_DELAY_MS = 2_000
50
+
51
+ export function respReconnectDelay(attempt: number): number {
52
+ return Math.min(RECONNECT_BASE_DELAY_MS * Math.max(1, attempt), RECONNECT_MAX_DELAY_MS)
53
+ }
54
+
55
+ function toTlsOptions(tls: RespTlsSettings | undefined): RedisOptions['tls'] {
56
+ if (!tls) return undefined
57
+ return {
58
+ ...(tls.ca !== undefined ? { ca: tls.ca } : {}),
59
+ ...(tls.cert !== undefined ? { cert: tls.cert } : {}),
60
+ ...(tls.key !== undefined ? { key: tls.key } : {}),
61
+ ...(tls.servername !== undefined ? { servername: tls.servername } : {}),
62
+ rejectUnauthorized: tls.rejectUnauthorized,
63
+ }
64
+ }
65
+
66
+ function baseRedisOptions(settings: RespSettings): RedisOptions {
67
+ const tls = toTlsOptions(settings.tls)
68
+ return {
69
+ lazyConnect: true,
70
+ connectTimeout: settings.connectTimeoutMs,
71
+ commandTimeout: settings.commandTimeoutMs,
72
+ maxRetriesPerRequest: settings.maxRetriesPerRequest,
73
+ enableReadyCheck: false,
74
+ autoResubscribe: false,
75
+ retryStrategy: respReconnectDelay,
76
+ ...(settings.username !== undefined ? { username: settings.username } : {}),
77
+ ...(settings.password !== undefined ? { password: settings.password } : {}),
78
+ ...(tls ? { tls } : {}),
79
+ }
80
+ }
81
+
82
+ type CredentialTarget = { options: RedisOptions }
83
+
84
+ function applyCredentials(target: CredentialTarget, credentials: RespCredentials): void {
85
+ target.options.username = credentials.username
86
+ target.options.password = credentials.password
87
+ }
88
+
89
+ function credentialTargets(client: RespClient): CredentialTarget[] {
90
+ if (isClusterClient(client)) {
91
+ const nodes: CredentialTarget[] = client.nodes('all')
92
+ const template = client.options.redisOptions
93
+ return template ? [...nodes, { options: template }] : nodes
94
+ }
95
+ return [client]
96
+ }
97
+
98
+ async function authenticate(connection: Redis, credentials: RespCredentials): Promise<void> {
99
+ if (credentials.username !== undefined) await connection.auth(credentials.username, credentials.password)
100
+ else await connection.auth(credentials.password)
101
+ }
102
+
103
+ async function reauthenticate(client: RespClient, credentials: RespCredentials): Promise<void> {
104
+ const connections: Redis[] = isClusterClient(client) ? client.nodes('all') : [client]
105
+ await Promise.all(connections.map(async (connection) => {
106
+ if (connection.status !== 'ready') return
107
+ await authenticate(connection, credentials)
108
+ }))
109
+ }
110
+
111
+ function credentialsOf(options: RedisOptions): RespCredentials {
112
+ return { ...(options.username !== undefined ? { username: options.username } : {}), password: options.password ?? '' }
113
+ }
114
+
115
+ function sameCredentials(left: RespCredentials, right: RespCredentials): boolean {
116
+ return left.username === right.username && left.password === right.password
117
+ }
118
+
119
+ function nextRefreshDelay(schedule: RespRefreshSchedule | undefined): number | null {
120
+ if (schedule === undefined) return null
121
+ const raw = typeof schedule === 'function' ? schedule() : schedule
122
+ if (typeof schedule === 'number' && !(raw > 0)) return null
123
+ return Number.isFinite(raw) ? Math.max(RESP_MIN_REFRESH_DELAY_MS, raw) : null
124
+ }
125
+
126
+ /**
127
+ * Build a RESP client factory over ioredis for standalone or cluster settings.
128
+ * Mutations and reads always go to primaries (`scaleReads: 'master'`).
129
+ */
130
+ export function createIoredisClientFactory(settings: RespSettings, options: RespClientFactoryOptions = {}): () => Promise<RespManagedClient> {
131
+ return async () => {
132
+ const redisOptions: RedisOptions = { ...baseRedisOptions(settings), ...(options.redisOptions ?? {}) }
133
+ if (options.credentialsProvider) applyCredentials({ options: redisOptions }, await options.credentialsProvider())
134
+
135
+ const client: RespClient = settings.mode === 'cluster'
136
+ ? new Cluster(settings.nodes.map((node) => ({ host: node.host, port: node.port })), {
137
+ lazyConnect: true,
138
+ scaleReads: 'master',
139
+ enableOfflineQueue: true,
140
+ maxRedirections: 16,
141
+ retryDelayOnFailover: 100,
142
+ retryDelayOnClusterDown: 100,
143
+ retryDelayOnTryAgain: 100,
144
+ slotsRefreshTimeout: settings.connectTimeoutMs,
145
+ clusterRetryStrategy: respReconnectDelay,
146
+ ...(options.clusterOptions ?? {}),
147
+ redisOptions,
148
+ })
149
+ : new Redis({ ...redisOptions, host: settings.host, port: settings.port, db: settings.db })
150
+
151
+ client.on('error', (error: Error) => options.onError?.(error))
152
+
153
+ let refreshTimer: ReturnType<typeof setTimeout> | null = null
154
+ let disposed = false
155
+ const provider = options.credentialsProvider
156
+ if (provider) {
157
+ const report = (error: unknown) => {
158
+ options.onError?.(error instanceof Error ? error : new Error('[internal] credential refresh failed'))
159
+ }
160
+ const refresh = async (live: boolean) => {
161
+ try {
162
+ const credentials = await provider()
163
+ for (const target of credentialTargets(client)) applyCredentials(target, credentials)
164
+ if (live) await reauthenticate(client, credentials)
165
+ } catch (error) {
166
+ report(error)
167
+ }
168
+ }
169
+ const watched = new WeakSet<Redis>()
170
+ const watchConnection = (connection: Redis) => {
171
+ if (watched.has(connection)) return
172
+ watched.add(connection)
173
+ let connectedWith = credentialsOf(connection.options)
174
+ connection.on('connecting', () => {
175
+ connectedWith = credentialsOf(connection.options)
176
+ })
177
+ connection.on('reconnecting', () => {
178
+ provider().then((credentials) => applyCredentials(connection, credentials), report)
179
+ })
180
+ connection.on('ready', () => {
181
+ provider().then(async (credentials) => {
182
+ applyCredentials(connection, credentials)
183
+ if (sameCredentials(connectedWith, credentials) || connection.status !== 'ready') return
184
+ await authenticate(connection, credentials)
185
+ connectedWith = credentials
186
+ }).catch(report)
187
+ })
188
+ }
189
+ if (isClusterClient(client)) {
190
+ client.on('+node', (node: Redis) => {
191
+ watchConnection(node)
192
+ provider().then((credentials) => applyCredentials(node, credentials), report)
193
+ })
194
+ for (const node of client.nodes('all')) watchConnection(node)
195
+ client.on('reconnecting', () => {
196
+ void refresh(false)
197
+ })
198
+ } else {
199
+ watchConnection(client)
200
+ }
201
+ const schedule = () => {
202
+ if (disposed) return
203
+ const delay = nextRefreshDelay(options.refreshIntervalMs)
204
+ if (delay === null) return
205
+ refreshTimer = setTimeout(() => {
206
+ refreshTimer = null
207
+ void refresh(true).finally(schedule)
208
+ }, delay)
209
+ refreshTimer.unref()
210
+ }
211
+ schedule()
212
+ }
213
+
214
+ return {
215
+ client,
216
+ dispose() {
217
+ disposed = true
218
+ if (refreshTimer) clearTimeout(refreshTimer)
219
+ refreshTimer = null
220
+ },
221
+ }
222
+ }
223
+ }
package/src/cluster.ts ADDED
@@ -0,0 +1,6 @@
1
+ import type { Cluster } from 'ioredis'
2
+ import type { RespClient } from './client'
3
+
4
+ export function isClusterClient(client: RespClient): client is Cluster {
5
+ return (client as { isCluster?: unknown }).isCluster === true
6
+ }
package/src/index.ts ADDED
@@ -0,0 +1,45 @@
1
+ export { createRespCacheStrategy } from './strategy'
2
+ export type {
3
+ RespCacheStrategy,
4
+ RespCacheStrategyOptions,
5
+ RespCacheStrategyTimeouts,
6
+ RespStrategyClientFactory,
7
+ } from './strategy'
8
+ export { createIoredisClientFactory, RESP_MIN_REFRESH_DELAY_MS, respReconnectDelay } from './client'
9
+ export type {
10
+ RespClient,
11
+ RespClientFactory,
12
+ RespClientFactoryOptions,
13
+ RespCredentials,
14
+ RespCredentialsProvider,
15
+ RespManagedClient,
16
+ RespRefreshSchedule,
17
+ } from './client'
18
+ export { isClusterClient } from './cluster'
19
+ export { buildRespKeyLayout, escapeRespGlob, literalPatternPrefix, RESP_KEY_ROOT, RESP_LAYOUT_VERSION } from './layout'
20
+ export type { RespKeyLayout } from './layout'
21
+ export { DELETE_IF_UNCHANGED, REAP_TAG_MEMBERS, RESP_SCRIPTS, WRITE_ENTRY, sha1Hex } from './scripts'
22
+ export type { RespScript } from './scripts'
23
+ export {
24
+ createRespSettingsSchema,
25
+ createRespStandaloneSettingsSchema,
26
+ redactRespSettings,
27
+ respClusterSettingsSchema,
28
+ respTransportWarnings,
29
+ respStandaloneSettingsSchema,
30
+ respTlsSettingsSchema,
31
+ RESP_DEFAULTS,
32
+ RESP_LIMITS,
33
+ } from './settings'
34
+ export type {
35
+ RespClusterSettings,
36
+ RespSettings,
37
+ RespSettingsInput,
38
+ RespStandaloneSettings,
39
+ RespTlsSettings,
40
+ RespTransportWarning,
41
+ } from './settings'
42
+ export { detectRespServer, parseRespServerInfo } from './server'
43
+ export type { RespServerEngine, RespServerInfo } from './server'
44
+ export { createRespCacheProvider } from './provider'
45
+ export type { RespCacheProviderOptions } from './provider'
package/src/layout.ts ADDED
@@ -0,0 +1,49 @@
1
+ export const RESP_LAYOUT_VERSION = 1
2
+ export const RESP_KEY_ROOT = 'om'
3
+
4
+ const GLOB_SPECIAL_CHARACTERS = /[*?[\]\\]/g
5
+ const NAMESPACE_PATTERN = /^[a-zA-Z0-9._-]{1,64}$/
6
+
7
+ export type RespKeyLayout = {
8
+ namespace: string
9
+ /** `om:{<namespace>}:` — the `{...}` hash tag pins every key of a namespace to one cluster slot. */
10
+ prefix: string
11
+ valuePrefix: string
12
+ tagPrefix: string
13
+ valueKey(physicalKey: string): string
14
+ tagKey(tag: string): string
15
+ physicalKeyFromValueKey(valueKey: string): string | null
16
+ /** SCAN MATCH pattern covering every value key whose physical key starts with the literal part of `pattern`. */
17
+ valueScanPattern(pattern?: string): string
18
+ tagScanPattern(): string
19
+ }
20
+
21
+ export function escapeRespGlob(literal: string): string {
22
+ return literal.replace(GLOB_SPECIAL_CHARACTERS, (character) => `\\${character}`)
23
+ }
24
+
25
+ export function literalPatternPrefix(pattern: string | undefined): string {
26
+ if (!pattern) return ''
27
+ const wildcard = pattern.search(/[*?]/)
28
+ return wildcard < 0 ? pattern : pattern.slice(0, wildcard)
29
+ }
30
+
31
+ export function buildRespKeyLayout(namespace: string): RespKeyLayout {
32
+ if (!NAMESPACE_PATTERN.test(namespace)) {
33
+ throw new Error('[internal] RESP cache namespace must be 1-64 characters of letters, digits, ".", "_" or "-"')
34
+ }
35
+ const prefix = `${RESP_KEY_ROOT}:{${namespace}}:`
36
+ const valuePrefix = `${prefix}v:`
37
+ const tagPrefix = `${prefix}t:`
38
+ return {
39
+ namespace,
40
+ prefix,
41
+ valuePrefix,
42
+ tagPrefix,
43
+ valueKey: (physicalKey) => `${valuePrefix}${physicalKey}`,
44
+ tagKey: (tag) => `${tagPrefix}${tag}`,
45
+ physicalKeyFromValueKey: (valueKey) => (valueKey.startsWith(valuePrefix) ? valueKey.slice(valuePrefix.length) : null),
46
+ valueScanPattern: (pattern) => `${escapeRespGlob(valuePrefix)}${escapeRespGlob(literalPatternPrefix(pattern))}*`,
47
+ tagScanPattern: () => `${escapeRespGlob(tagPrefix)}*`,
48
+ }
49
+ }
@@ -0,0 +1,86 @@
1
+ import type {
2
+ CacheProviderCapability,
3
+ CacheProviderDefinition,
4
+ CacheProviderHostContext,
5
+ CacheProviderSettingsSchema,
6
+ } from '@open-mercato/cache/provider'
7
+ import type { CacheStrategy } from '@open-mercato/cache/types'
8
+ import { createIoredisClientFactory } from './client'
9
+ import type { RespClientFactoryOptions } from './client'
10
+ import { detectRespServer } from './server'
11
+ import type { RespServerEngine } from './server'
12
+ import { redactRespSettings, respTransportWarnings } from './settings'
13
+ import type { RespSettings } from './settings'
14
+ import { createRespCacheStrategy } from './strategy'
15
+
16
+ export type RespCacheProviderOptions<TConfig extends RespSettings> = {
17
+ id: string
18
+ settings: CacheProviderSettingsSchema<TConfig>
19
+ /** Engine the package is qualified against; a different engine behind the endpoint is logged once. */
20
+ expectedEngine?: RespServerEngine
21
+ clientOptions?: (config: TConfig, context: CacheProviderHostContext) => RespClientFactoryOptions
22
+ }
23
+
24
+ const ERROR_LOG_INTERVAL_MS = 30_000
25
+
26
+ const TRANSPORT_WARNING_MESSAGES = {
27
+ tls_verification_disabled: 'TLS server certificate verification is disabled (tls.rejectUnauthorized: false); the connection is open to interception',
28
+ credentials_over_plaintext: 'credentials are sent over a plaintext connection; configure tls',
29
+ } as const
30
+
31
+ /**
32
+ * Build everything a RESP cache provider definition needs except `apiVersion`,
33
+ * so the provider package passes it to `defineCacheProvider` itself.
34
+ */
35
+ export function createRespCacheProvider<TConfig extends RespSettings>(
36
+ options: RespCacheProviderOptions<TConfig>,
37
+ ): Omit<CacheProviderDefinition<TConfig>, 'apiVersion'> {
38
+ return {
39
+ id: options.id,
40
+ settings: options.settings,
41
+ capability(): CacheProviderCapability {
42
+ return { placement: 'shared' }
43
+ },
44
+ async create(config: TConfig, context: CacheProviderHostContext): Promise<CacheStrategy> {
45
+ let lastErrorLoggedAt = 0
46
+ const extra = options.clientOptions ? options.clientOptions(config, context) : {}
47
+ for (const warning of respTransportWarnings(config, { externalCredentials: extra.credentialsProvider !== undefined })) {
48
+ context.logger.warn(TRANSPORT_WARNING_MESSAGES[warning])
49
+ }
50
+ const factory = createIoredisClientFactory(config, {
51
+ ...extra,
52
+ onError: (error) => {
53
+ extra.onError?.(error)
54
+ const now = Date.now()
55
+ if (now - lastErrorLoggedAt < ERROR_LOG_INTERVAL_MS) return
56
+ lastErrorLoggedAt = now
57
+ context.logger.warn('connection error; the client is reconnecting', { error })
58
+ },
59
+ })
60
+ const managed = await factory()
61
+ const strategy = await createRespCacheStrategy(() => managed, {
62
+ namespace: context.namespace,
63
+ helpers: context.helpers,
64
+ logger: context.logger,
65
+ ...(context.defaultTtl !== undefined ? { defaultTtl: context.defaultTtl } : {}),
66
+ batchSize: config.batchSize,
67
+ maxValueBytes: config.maxValueBytes,
68
+ timeouts: { connectMs: config.connectTimeoutMs },
69
+ })
70
+ if (options.expectedEngine) {
71
+ const server = await detectRespServer(managed.client)
72
+ if (server && server.engine !== options.expectedEngine) {
73
+ context.logger.warn('endpoint reports a different engine than this provider is qualified for', {
74
+ expected: options.expectedEngine,
75
+ reported: server.engine,
76
+ version: server.version,
77
+ })
78
+ }
79
+ }
80
+ return strategy
81
+ },
82
+ redact(config: TConfig): Record<string, unknown> {
83
+ return redactRespSettings(config)
84
+ },
85
+ }
86
+ }
package/src/scripts.ts ADDED
@@ -0,0 +1,103 @@
1
+ import { createHash } from 'node:crypto'
2
+
3
+ export type RespScript = {
4
+ name: string
5
+ source: string
6
+ sha: string
7
+ }
8
+
9
+ function defineScript(name: string, source: string): RespScript {
10
+ return { name, source, sha: createHash('sha1').update(source).digest('hex') }
11
+ }
12
+
13
+ /**
14
+ * Compare-and-delete a batch of entries. For every entry ARGV carries
15
+ * `(sha1 of the observed value bytes, member, tag-key count)` and KEYS carries
16
+ * the value key followed by that many tag keys. An entry is deleted, and its
17
+ * member removed from those tag sets, only while its stored bytes still hash to
18
+ * the observed digest; a concurrent rewrite or retag is left untouched.
19
+ */
20
+ export const DELETE_IF_UNCHANGED = defineScript('om_cache_delete_if_unchanged', `
21
+ local removed = 0
22
+ local keyIndex = 1
23
+ local argIndex = 1
24
+ while argIndex <= #ARGV do
25
+ local expected = ARGV[argIndex]
26
+ local member = ARGV[argIndex + 1]
27
+ local tagCount = tonumber(ARGV[argIndex + 2])
28
+ local current = redis.call('GET', KEYS[keyIndex])
29
+ if current and redis.sha1hex(current) == expected then
30
+ redis.call('DEL', KEYS[keyIndex])
31
+ for offset = 1, tagCount do
32
+ redis.call('SREM', KEYS[keyIndex + offset], member)
33
+ end
34
+ removed = removed + 1
35
+ end
36
+ keyIndex = keyIndex + 1 + tagCount
37
+ argIndex = argIndex + 3
38
+ end
39
+ return removed
40
+ `)
41
+
42
+ /**
43
+ * Drop stale members from ONE tag set. KEYS[1] is the tag key, KEYS[2..] the
44
+ * member value keys; ARGV holds `(member, expected digest)` pairs where an empty
45
+ * digest means "value key must be absent". A member is removed only while its
46
+ * value is still absent or still the observed bytes whose tags exclude this tag,
47
+ * so a concurrent write that re-adds the tag keeps its membership.
48
+ */
49
+ export const REAP_TAG_MEMBERS = defineScript('om_cache_reap_tag_members', `
50
+ local removed = 0
51
+ for keyIndex = 2, #KEYS do
52
+ local argIndex = (keyIndex - 1) * 2 - 1
53
+ local member = ARGV[argIndex]
54
+ local expected = ARGV[argIndex + 1]
55
+ local current = redis.call('GET', KEYS[keyIndex])
56
+ local stale
57
+ if expected == '' then
58
+ stale = (current == false)
59
+ else
60
+ stale = (current ~= false and redis.sha1hex(current) == expected)
61
+ end
62
+ if stale then
63
+ removed = removed + redis.call('SREM', KEYS[1], member)
64
+ end
65
+ end
66
+ return removed
67
+ `)
68
+
69
+ /**
70
+ * Write one entry and its tag memberships atomically. KEYS[1] is the value key,
71
+ * KEYS[2..] the tag keys; ARGV is `(payload, ttl ms or '' for no TTL, member)`.
72
+ * A tag set lives at least as long as its longest-lived member: a fresh set
73
+ * takes the entry TTL, an existing volatile set only ever extends, and a
74
+ * member without TTL makes the set persistent. Plain Lua instead of
75
+ * `PEXPIRE … GT` because KeyDB 6.3 (Redis 6.2 base) has no GT flag.
76
+ */
77
+ export const WRITE_ENTRY = defineScript('om_cache_write_entry', `
78
+ local ttl = tonumber(ARGV[2])
79
+ if ttl then
80
+ redis.call('SET', KEYS[1], ARGV[1], 'PX', ttl)
81
+ else
82
+ redis.call('SET', KEYS[1], ARGV[1])
83
+ end
84
+ for index = 2, #KEYS do
85
+ local tagKey = KEYS[index]
86
+ local current = redis.call('PTTL', tagKey)
87
+ redis.call('SADD', tagKey, ARGV[3])
88
+ if not ttl then
89
+ if current >= 0 then
90
+ redis.call('PERSIST', tagKey)
91
+ end
92
+ elseif current == -2 or (current >= 0 and current < ttl) then
93
+ redis.call('PEXPIRE', tagKey, ttl)
94
+ end
95
+ end
96
+ return 1
97
+ `)
98
+
99
+ export const RESP_SCRIPTS: ReadonlyArray<RespScript> = [DELETE_IF_UNCHANGED, REAP_TAG_MEMBERS, WRITE_ENTRY]
100
+
101
+ export function sha1Hex(raw: Buffer | string): string {
102
+ return createHash('sha1').update(raw).digest('hex')
103
+ }
package/src/server.ts ADDED
@@ -0,0 +1,41 @@
1
+ import type { RespClient } from './client'
2
+ import { isClusterClient } from './cluster'
3
+
4
+ export type RespServerEngine = 'valkey' | 'redis' | 'keydb' | 'unknown'
5
+
6
+ export type RespServerInfo = {
7
+ engine: RespServerEngine
8
+ version: string | null
9
+ }
10
+
11
+ export function parseRespServerInfo(info: string): RespServerInfo {
12
+ const fields = new Map<string, string>()
13
+ for (const line of info.split(/\r?\n/)) {
14
+ const separator = line.indexOf(':')
15
+ if (separator <= 0 || line.startsWith('#')) continue
16
+ fields.set(line.slice(0, separator).trim(), line.slice(separator + 1).trim())
17
+ }
18
+ const serverName = (fields.get('server_name') ?? '').toLowerCase()
19
+ if (fields.has('valkey_version') || serverName === 'valkey') {
20
+ return { engine: 'valkey', version: fields.get('valkey_version') ?? fields.get('redis_version') ?? null }
21
+ }
22
+ if (serverName === 'keydb' || fields.has('keydb_version') || /keydb/i.test(fields.get('executable') ?? '')) {
23
+ return { engine: 'keydb', version: fields.get('keydb_version') ?? fields.get('redis_version') ?? null }
24
+ }
25
+ if (fields.has('redis_version')) return { engine: 'redis', version: fields.get('redis_version') ?? null }
26
+ return { engine: 'unknown', version: null }
27
+ }
28
+
29
+ /**
30
+ * Best-effort server identification through `INFO server`. Returns `null` when
31
+ * the ACL user may not run INFO (it belongs to the `@dangerous` category).
32
+ */
33
+ export async function detectRespServer(client: RespClient): Promise<RespServerInfo | null> {
34
+ try {
35
+ const target = isClusterClient(client) ? client.nodes('master')[0] : client
36
+ if (!target) return null
37
+ return parseRespServerInfo(await target.info('server'))
38
+ } catch {
39
+ return null
40
+ }
41
+ }
@@ -0,0 +1,127 @@
1
+ import { z } from 'zod'
2
+
3
+ export const RESP_DEFAULTS = {
4
+ port: 6379,
5
+ connectTimeoutMs: 5_000,
6
+ commandTimeoutMs: 2_000,
7
+ maxRetriesPerRequest: 1,
8
+ batchSize: 500,
9
+ maxValueBytes: 8 * 1024 * 1024,
10
+ tryAgainAttempts: 40,
11
+ } as const
12
+
13
+ export const RESP_LIMITS = {
14
+ maxTimeoutMs: 120_000,
15
+ maxBatchSize: 5_000,
16
+ maxValueBytes: 512 * 1024 * 1024,
17
+ maxRetriesPerRequest: 10,
18
+ } as const
19
+
20
+ const hostSchema = z.string().trim().min(1).max(255)
21
+ const portSchema = z.number().int().min(1).max(65535)
22
+ const pemSchema = z.string().min(1).max(64 * 1024)
23
+
24
+ export const respTlsSettingsSchema = z.object({
25
+ ca: pemSchema.optional(),
26
+ cert: pemSchema.optional(),
27
+ key: pemSchema.optional(),
28
+ servername: z.string().trim().min(1).max(255).optional(),
29
+ rejectUnauthorized: z.boolean().default(true),
30
+ }).strict().superRefine((value, context) => {
31
+ if ((value.cert === undefined) !== (value.key === undefined)) {
32
+ context.addIssue({ code: 'custom', path: [value.cert === undefined ? 'cert' : 'key'], message: 'Client certificate and key must be configured together' })
33
+ }
34
+ })
35
+
36
+ const credentialShape = {
37
+ username: z.string().min(1).max(256).optional(),
38
+ password: z.string().min(1).max(4096).optional(),
39
+ }
40
+
41
+ const tuningShape = {
42
+ tls: respTlsSettingsSchema.optional(),
43
+ connectTimeoutMs: z.number().int().min(100).max(RESP_LIMITS.maxTimeoutMs).default(RESP_DEFAULTS.connectTimeoutMs),
44
+ commandTimeoutMs: z.number().int().min(50).max(RESP_LIMITS.maxTimeoutMs).default(RESP_DEFAULTS.commandTimeoutMs),
45
+ maxRetriesPerRequest: z.number().int().min(0).max(RESP_LIMITS.maxRetriesPerRequest).default(RESP_DEFAULTS.maxRetriesPerRequest),
46
+ batchSize: z.number().int().min(1).max(RESP_LIMITS.maxBatchSize).default(RESP_DEFAULTS.batchSize),
47
+ maxValueBytes: z.number().int().min(1024).max(RESP_LIMITS.maxValueBytes).default(RESP_DEFAULTS.maxValueBytes),
48
+ }
49
+
50
+ function requirePasswordWithUsername(value: { username?: string; password?: string }, context: z.RefinementCtx): void {
51
+ if (value.username !== undefined && value.password === undefined) {
52
+ context.addIssue({ code: 'custom', path: ['password'], message: 'An ACL username requires a password' })
53
+ }
54
+ }
55
+
56
+ export const respStandaloneSettingsSchema = z.object({
57
+ mode: z.literal('standalone').default('standalone'),
58
+ host: hostSchema,
59
+ port: portSchema.default(RESP_DEFAULTS.port),
60
+ db: z.number().int().min(0).max(255).default(0),
61
+ ...credentialShape,
62
+ ...tuningShape,
63
+ }).strict().superRefine(requirePasswordWithUsername)
64
+
65
+ export const respClusterSettingsSchema = z.object({
66
+ mode: z.literal('cluster'),
67
+ nodes: z.array(z.object({ host: hostSchema, port: portSchema.default(RESP_DEFAULTS.port) }).strict()).min(1).max(64),
68
+ ...credentialShape,
69
+ ...tuningShape,
70
+ }).strict().superRefine(requirePasswordWithUsername)
71
+
72
+ /** Standalone-only settings: the first supported profile of every OSS RESP provider. */
73
+ export function createRespStandaloneSettingsSchema() {
74
+ return respStandaloneSettingsSchema
75
+ }
76
+
77
+ /** Standalone or cluster settings, for providers whose matrix includes a qualified cluster profile. */
78
+ export function createRespSettingsSchema() {
79
+ return z.union([respStandaloneSettingsSchema, respClusterSettingsSchema])
80
+ }
81
+
82
+ export type RespTlsSettings = z.infer<typeof respTlsSettingsSchema>
83
+ export type RespStandaloneSettings = z.infer<typeof respStandaloneSettingsSchema>
84
+ export type RespClusterSettings = z.infer<typeof respClusterSettingsSchema>
85
+ export type RespSettings = RespStandaloneSettings | RespClusterSettings
86
+ export type RespSettingsInput = z.input<typeof respStandaloneSettingsSchema> | z.input<typeof respClusterSettingsSchema>
87
+
88
+ const REDACTED = '[redacted]'
89
+
90
+ /** Operator-safe view of RESP settings: endpoints and tuning only, never secrets or key material. */
91
+ export function redactRespSettings(settings: RespSettings): Record<string, unknown> {
92
+ const endpoint = settings.mode === 'cluster'
93
+ ? { nodes: settings.nodes.map((node) => `${node.host}:${node.port}`) }
94
+ : { host: settings.host, port: settings.port, db: settings.db }
95
+ return {
96
+ mode: settings.mode,
97
+ ...endpoint,
98
+ username: settings.username !== undefined ? REDACTED : null,
99
+ password: settings.password !== undefined ? REDACTED : null,
100
+ tls: settings.tls
101
+ ? {
102
+ enabled: true,
103
+ ca: settings.tls.ca !== undefined ? 'configured' : 'system',
104
+ clientCertificate: settings.tls.cert !== undefined,
105
+ servername: settings.tls.servername ?? null,
106
+ rejectUnauthorized: settings.tls.rejectUnauthorized,
107
+ }
108
+ : { enabled: false },
109
+ connectTimeoutMs: settings.connectTimeoutMs,
110
+ commandTimeoutMs: settings.commandTimeoutMs,
111
+ maxRetriesPerRequest: settings.maxRetriesPerRequest,
112
+ batchSize: settings.batchSize,
113
+ maxValueBytes: settings.maxValueBytes,
114
+ }
115
+ }
116
+
117
+ export type RespTransportWarning = 'tls_verification_disabled' | 'credentials_over_plaintext'
118
+
119
+ export function respTransportWarnings(
120
+ settings: Pick<RespSettings, 'tls' | 'password'>,
121
+ options: { externalCredentials?: boolean } = {},
122
+ ): RespTransportWarning[] {
123
+ const warnings: RespTransportWarning[] = []
124
+ if (settings.tls && settings.tls.rejectUnauthorized === false) warnings.push('tls_verification_disabled')
125
+ if (!settings.tls && (settings.password !== undefined || options.externalCredentials)) warnings.push('credentials_over_plaintext')
126
+ return warnings
127
+ }