@zxlll/dsh-integration-env 0.0.0-stage → 0.1.1

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/lib/redis.js ADDED
@@ -0,0 +1,317 @@
1
+ /**
2
+ * 极简 Redis RESP2 客户端:只用 `node:net`(可选 `node:tls`),不依赖第三方库。
3
+ *
4
+ * 契约 §7.4 / §8:AUTH(有 username 时两参数)→ SELECT → 执行一个只读动作 → 读一条完整回复 → end()。
5
+ * 支持 `+ - : $ *` 五种回复;`$-1` / `*-1` 表示 null。
6
+ */
7
+ import net from 'node:net'
8
+ import tls from 'node:tls'
9
+
10
+ const CRLF = Buffer.from('\r\n')
11
+ const DEFAULT_TIMEOUT_MS = 8000
12
+ const DEFAULT_SCAN_COUNT = 100
13
+ const MAX_SCAN_COUNT = 1000
14
+
15
+ function userError(code, message) {
16
+ const error = new Error(message)
17
+ error.code = code
18
+ return error
19
+ }
20
+
21
+ function withTimeout(promise, timeoutMs, message) {
22
+ let timer
23
+ const timeout = new Promise((_resolve, reject) => {
24
+ timer = setTimeout(() => reject(userError('connection-failed', message)), timeoutMs)
25
+ if (typeof timer.unref === 'function') timer.unref()
26
+ })
27
+ return Promise.race([promise, timeout]).finally(() => clearTimeout(timer))
28
+ }
29
+
30
+ function mapNetError(error, host, port) {
31
+ if (error?.code === 'connection-failed' || error?.code === 'bad-request') return error
32
+ switch (error?.code) {
33
+ case 'ECONNREFUSED':
34
+ return userError('connection-failed', `无法连接 Redis ${host}:${port}:连接被拒绝(服务未启动或端口不对)。`)
35
+ case 'ENOTFOUND':
36
+ case 'EAI_AGAIN':
37
+ return userError('connection-failed', `无法解析 Redis 主机「${host}」,请检查地址是否正确。`)
38
+ case 'ETIMEDOUT':
39
+ case 'ESOCKETTIMEDOUT':
40
+ return userError('connection-failed', `连接 Redis 超时:${host}:${port}`)
41
+ case 'ECONNRESET':
42
+ return userError('connection-failed', `Redis 连接被重置:${host}:${port}`)
43
+ default:
44
+ return userError('connection-failed', `Redis 连接失败(${host}:${port}):${error?.message ?? String(error)}`)
45
+ }
46
+ }
47
+
48
+ /** RESP2 编码:`*N\r\n` + 每个参数的 `$len\r\n<bytes>\r\n`。 */
49
+ function encodeCommand(args) {
50
+ const chunks = [Buffer.from(`*${args.length}\r\n`, 'utf8')]
51
+ for (const arg of args) {
52
+ const body = Buffer.from(String(arg), 'utf8')
53
+ chunks.push(Buffer.from(`$${body.length}\r\n`, 'utf8'), body, CRLF)
54
+ }
55
+ return Buffer.concat(chunks)
56
+ }
57
+
58
+ /**
59
+ * 尝试从 buffer 里解析一条完整回复。
60
+ * @returns `{ value, offset }`;数据不完整时返回 null。
61
+ */
62
+ function parseReply(buffer, offset = 0) {
63
+ if (offset >= buffer.length) return null
64
+ const marker = buffer[offset]
65
+ const lineEnd = buffer.indexOf(CRLF, offset + 1)
66
+ if (marker === 0x2b || marker === 0x2d) {
67
+ if (lineEnd < 0) return null
68
+ const line = buffer.toString('utf8', offset + 1, lineEnd)
69
+ if (marker === 0x2d) throw userError('connection-failed', `Redis 返回错误:${line}`)
70
+ return { value: line, offset: lineEnd + 2 }
71
+ }
72
+ if (marker === 0x3a) {
73
+ if (lineEnd < 0) return null
74
+ return { value: Number(buffer.toString('utf8', offset + 1, lineEnd)), offset: lineEnd + 2 }
75
+ }
76
+ if (marker === 0x24) {
77
+ if (lineEnd < 0) return null
78
+ const length = Number(buffer.toString('utf8', offset + 1, lineEnd))
79
+ if (!Number.isFinite(length)) throw userError('connection-failed', 'Redis 回复格式错误(bulk length 非法)')
80
+ if (length === -1) return { value: null, offset: lineEnd + 2 }
81
+ const start = lineEnd + 2
82
+ const end = start + length
83
+ if (buffer.length < end + 2) return null
84
+ return { value: buffer.toString('utf8', start, end), offset: end + 2 }
85
+ }
86
+ if (marker === 0x2a) {
87
+ if (lineEnd < 0) return null
88
+ const count = Number(buffer.toString('utf8', offset + 1, lineEnd))
89
+ if (!Number.isFinite(count)) throw userError('connection-failed', 'Redis 回复格式错误(array length 非法)')
90
+ if (count === -1) return { value: null, offset: lineEnd + 2 }
91
+ const values = []
92
+ let cursor = lineEnd + 2
93
+ for (let index = 0; index < count; index += 1) {
94
+ const child = parseReply(buffer, cursor)
95
+ if (!child) return null
96
+ values.push(child.value)
97
+ cursor = child.offset
98
+ }
99
+ return { value: values, offset: cursor }
100
+ }
101
+ throw userError('connection-failed', `Redis 回复格式错误:未知类型标记 0x${marker.toString(16)}`)
102
+ }
103
+
104
+ /** 把 socket 数据流变成可 await 的 RESP 回复。 */
105
+ class RespReader {
106
+ constructor(socket) {
107
+ this.socket = socket
108
+ this.buffer = Buffer.alloc(0)
109
+ this.waiters = []
110
+ this.failure = null
111
+ socket.on('data', (chunk) => {
112
+ if (this.failure) return
113
+ this.buffer = this.buffer.length === 0 ? chunk : Buffer.concat([this.buffer, chunk])
114
+ const waiters = this.waiters
115
+ this.waiters = []
116
+ for (const waiter of waiters) waiter.resolve()
117
+ })
118
+ socket.on('error', (error) => this.fail(error))
119
+ socket.on('close', () => this.fail(userError('connection-failed', 'Redis 连接已关闭')))
120
+ }
121
+
122
+ fail(error) {
123
+ if (this.failure) return
124
+ this.failure = error
125
+ const waiters = this.waiters
126
+ this.waiters = []
127
+ for (const waiter of waiters) waiter.reject(error)
128
+ }
129
+
130
+ async readReply() {
131
+ for (;;) {
132
+ const parsed = parseReply(this.buffer)
133
+ if (parsed) {
134
+ this.buffer = this.buffer.subarray(parsed.offset)
135
+ return parsed.value
136
+ }
137
+ if (this.failure) throw this.failure
138
+ await new Promise((resolve, reject) => this.waiters.push({ resolve, reject }))
139
+ }
140
+ }
141
+ }
142
+
143
+ class RedisClient {
144
+ constructor(options) {
145
+ this.host = options.host
146
+ this.port = options.port
147
+ this.username = options.username
148
+ this.password = options.password
149
+ this.database = options.database
150
+ this.useTls = options.tls
151
+ this.socket = null
152
+ this.reader = null
153
+ }
154
+
155
+ async open() {
156
+ const socket = this.useTls
157
+ ? tls.connect({ host: this.host, port: this.port, servername: this.host })
158
+ : net.createConnection({ host: this.host, port: this.port })
159
+ this.socket = socket
160
+ this.reader = new RespReader(socket)
161
+ socket.setNoDelay?.(true)
162
+ try {
163
+ await new Promise((resolve, reject) => {
164
+ socket.once(this.useTls ? 'secureConnect' : 'connect', resolve)
165
+ socket.once('error', reject)
166
+ })
167
+ } catch (error) {
168
+ throw mapNetError(error, this.host, this.port)
169
+ }
170
+ }
171
+
172
+ async command(...args) {
173
+ this.socket.write(encodeCommand(args))
174
+ return this.reader.readReply()
175
+ }
176
+
177
+ /** AUTH(有 username 两参数)→ SELECT。 */
178
+ async prepare() {
179
+ if (this.password) {
180
+ const reply = this.username
181
+ ? await this.command('AUTH', this.username, this.password)
182
+ : await this.command('AUTH', this.password)
183
+ if (reply !== 'OK') {
184
+ throw userError('connection-failed', `Redis 认证失败:${String(reply)}。请检查用户名和密码。`)
185
+ }
186
+ }
187
+ if (this.database !== 0) {
188
+ const reply = await this.command('SELECT', String(this.database))
189
+ if (reply !== 'OK') throw userError('connection-failed', `Redis 选择 db${this.database} 失败:${String(reply)}`)
190
+ }
191
+ }
192
+
193
+ /** 读完后优雅关闭:先 end(),再用 unref 定时器兜底 destroy()。 */
194
+ destroy() {
195
+ const socket = this.socket
196
+ if (!socket) return
197
+ try {
198
+ socket.end()
199
+ } catch {
200
+ // 忽略关闭异常。
201
+ }
202
+ const timer = setTimeout(() => {
203
+ try {
204
+ socket.destroy()
205
+ } catch {
206
+ // 忽略销毁异常。
207
+ }
208
+ }, 100)
209
+ if (typeof timer.unref === 'function') timer.unref()
210
+ }
211
+ }
212
+
213
+ /** INFO 文本 → 键值对象(`# Section` 行丢弃)。 */
214
+ function parseInfo(text) {
215
+ const info = {}
216
+ for (const line of String(text ?? '').split(/\r?\n/)) {
217
+ const trimmed = line.trim()
218
+ if (!trimmed || trimmed.startsWith('#')) continue
219
+ const index = trimmed.indexOf(':')
220
+ if (index <= 0) continue
221
+ info[trimmed.slice(0, index)] = trimmed.slice(index + 1)
222
+ }
223
+ return info
224
+ }
225
+
226
+ function clampCount(value) {
227
+ const number = Number(value)
228
+ if (!Number.isFinite(number)) return DEFAULT_SCAN_COUNT
229
+ return Math.min(MAX_SCAN_COUNT, Math.max(1, Math.trunc(number)))
230
+ }
231
+
232
+ /**
233
+ * 连接器统一入口:`run(instance, payload)` → 结果对象;失败抛 Error。
234
+ * 只暴露只读动作(info/scan/get/type/ttl),因此 readOnly 开关在工具层天然满足。
235
+ */
236
+ export async function runRedis(instance, payload = {}) {
237
+ const config = instance?.config ?? {}
238
+ const host = String(config.host ?? '').trim()
239
+ if (!host) throw userError('bad-request', `实例「${instance?.name ?? ''}」缺少主机地址,请先在面板里补全。`)
240
+ const port = Number(config.port ?? 6379)
241
+ if (!Number.isFinite(port) || port <= 0) {
242
+ throw userError('bad-request', `实例「${instance?.name ?? ''}」的端口不合法:${config.port}`)
243
+ }
244
+ const database = config.database === undefined || config.database === '' ? 0 : Number(config.database)
245
+ if (!Number.isFinite(database) || database < 0 || database > 15) {
246
+ throw userError('bad-request', `实例「${instance?.name ?? ''}」的数据库编号必须在 0..15。`)
247
+ }
248
+ const action = String(payload.action ?? 'info')
249
+ const key = String(payload.key ?? '').trim()
250
+ let command
251
+ switch (action) {
252
+ case 'info':
253
+ command = ['INFO']
254
+ break
255
+ case 'scan': {
256
+ const pattern = String(payload.pattern ?? '*') || '*'
257
+ const cursor = String(payload.cursor ?? '0') || '0'
258
+ command = ['SCAN', cursor, 'MATCH', pattern, 'COUNT', String(clampCount(payload.count))]
259
+ break
260
+ }
261
+ case 'get':
262
+ if (!key) throw userError('bad-request', 'get 动作需要 key 参数。')
263
+ command = ['GET', key]
264
+ break
265
+ case 'type':
266
+ if (!key) throw userError('bad-request', 'type 动作需要 key 参数。')
267
+ command = ['TYPE', key]
268
+ break
269
+ case 'ttl':
270
+ if (!key) throw userError('bad-request', 'ttl 动作需要 key 参数。')
271
+ command = ['TTL', key]
272
+ break
273
+ default:
274
+ throw userError('bad-request', `未知的 redis 动作「${action}」,可用:info / scan / get / type / ttl。`)
275
+ }
276
+
277
+ const client = new RedisClient({
278
+ host,
279
+ port,
280
+ username: String(config.username ?? '').trim(),
281
+ password: String(config.password ?? ''),
282
+ database,
283
+ tls: config.tls === true,
284
+ })
285
+ const timeoutMs = Number(payload.timeoutMs) > 0 ? Number(payload.timeoutMs) : DEFAULT_TIMEOUT_MS
286
+ try {
287
+ const reply = await withTimeout(
288
+ (async () => {
289
+ await client.open()
290
+ await client.prepare()
291
+ return client.command(...command)
292
+ })(),
293
+ timeoutMs,
294
+ `连接 Redis 超时(${timeoutMs}ms):${host}:${port}`,
295
+ )
296
+ switch (action) {
297
+ case 'info':
298
+ return { action, info: parseInfo(reply) }
299
+ case 'scan': {
300
+ const list = Array.isArray(reply) ? reply : []
301
+ const cursor = String(list[0] ?? '0')
302
+ const keys = Array.isArray(list[1]) ? list[1].map((item) => String(item)) : []
303
+ return { action, cursor, keys, truncated: cursor !== '0' }
304
+ }
305
+ case 'get':
306
+ return { action, key, value: reply === null ? null : String(reply) }
307
+ case 'type':
308
+ return { action, key, type: String(reply ?? '') }
309
+ case 'ttl':
310
+ return { action, key, ttl: Number(reply) }
311
+ default:
312
+ return { action, value: reply }
313
+ }
314
+ } finally {
315
+ client.destroy()
316
+ }
317
+ }