@whiteplusms/dsh-redis 0.0.0-stage → 0.1.3

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 (146) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +184 -2
  3. package/README.zh.md +185 -0
  4. package/cordis.patch.yml +4 -0
  5. package/icon.svg +1 -0
  6. package/lib/client/index.d.ts +4 -0
  7. package/lib/client.js +7684 -0
  8. package/lib/connection-errors.d.ts +66 -0
  9. package/lib/connection-errors.js +21 -0
  10. package/lib/domain.d.ts +451 -0
  11. package/lib/domain.js +20 -0
  12. package/lib/host/ai-answer.d.ts +7 -0
  13. package/lib/host/ai-answer.js +132 -0
  14. package/lib/host/ai-budget.d.ts +43 -0
  15. package/lib/host/ai-budget.js +78 -0
  16. package/lib/host/ai-connection-tools.d.ts +8 -0
  17. package/lib/host/ai-connection-tools.js +49 -0
  18. package/lib/host/ai-hash-filter.d.ts +13 -0
  19. package/lib/host/ai-hash-filter.js +97 -0
  20. package/lib/host/ai-hash-pages.d.ts +15 -0
  21. package/lib/host/ai-hash-pages.js +42 -0
  22. package/lib/host/ai-key-pages.d.ts +14 -0
  23. package/lib/host/ai-key-pages.js +27 -0
  24. package/lib/host/ai-locate-tool.d.ts +6 -0
  25. package/lib/host/ai-locate-tool.js +234 -0
  26. package/lib/host/ai-match-tools.d.ts +7 -0
  27. package/lib/host/ai-match-tools.js +112 -0
  28. package/lib/host/ai-page-coordinator.d.ts +21 -0
  29. package/lib/host/ai-page-coordinator.js +81 -0
  30. package/lib/host/ai-page-store.d.ts +40 -0
  31. package/lib/host/ai-page-store.js +104 -0
  32. package/lib/host/ai-profile-tools.d.ts +7 -0
  33. package/lib/host/ai-profile-tools.js +44 -0
  34. package/lib/host/ai-query-scope.d.ts +42 -0
  35. package/lib/host/ai-query-scope.js +104 -0
  36. package/lib/host/ai-reader.d.ts +219 -0
  37. package/lib/host/ai-reader.js +1221 -0
  38. package/lib/host/ai-report-samples.d.ts +26 -0
  39. package/lib/host/ai-report-samples.js +77 -0
  40. package/lib/host/ai-report-tools.d.ts +11 -0
  41. package/lib/host/ai-report-tools.js +70 -0
  42. package/lib/host/ai-set-pages.d.ts +15 -0
  43. package/lib/host/ai-set-pages.js +40 -0
  44. package/lib/host/ai-stream-pages.d.ts +15 -0
  45. package/lib/host/ai-stream-pages.js +42 -0
  46. package/lib/host/ai-tools.d.ts +4 -0
  47. package/lib/host/ai-tools.js +106 -0
  48. package/lib/host/ai-ui-tools.d.ts +10 -0
  49. package/lib/host/ai-ui-tools.js +72 -0
  50. package/lib/host/ai-value.d.ts +12 -0
  51. package/lib/host/ai-value.js +15 -0
  52. package/lib/host/ai-write-tools.d.ts +5 -0
  53. package/lib/host/ai-write-tools.js +101 -0
  54. package/lib/host/ai-writer.d.ts +25 -0
  55. package/lib/host/ai-writer.js +77 -0
  56. package/lib/host/ai-zset-pages.d.ts +15 -0
  57. package/lib/host/ai-zset-pages.js +40 -0
  58. package/lib/host/byte-identity.d.ts +3 -0
  59. package/lib/host/byte-identity.js +12 -0
  60. package/lib/host/client-list.d.ts +13 -0
  61. package/lib/host/client-list.js +35 -0
  62. package/lib/host/connection-service.d.ts +71 -0
  63. package/lib/host/connection-service.js +468 -0
  64. package/lib/host/database-reader.d.ts +10 -0
  65. package/lib/host/database-reader.js +62 -0
  66. package/lib/host/hash-reader.d.ts +12 -0
  67. package/lib/host/hash-reader.js +91 -0
  68. package/lib/host/key-reader.d.ts +20 -0
  69. package/lib/host/key-reader.js +65 -0
  70. package/lib/host/list-reader.d.ts +8 -0
  71. package/lib/host/list-reader.js +61 -0
  72. package/lib/host/match-preset-store.d.ts +36 -0
  73. package/lib/host/match-preset-store.js +201 -0
  74. package/lib/host/profile-snapshots.d.ts +32 -0
  75. package/lib/host/profile-snapshots.js +187 -0
  76. package/lib/host/profile-store.d.ts +15 -0
  77. package/lib/host/profile-store.js +120 -0
  78. package/lib/host/read-context.d.ts +23 -0
  79. package/lib/host/read-context.js +41 -0
  80. package/lib/host/redis-transport.d.ts +34 -0
  81. package/lib/host/redis-transport.js +262 -0
  82. package/lib/host/redis-write-transaction.d.ts +28 -0
  83. package/lib/host/redis-write-transaction.js +180 -0
  84. package/lib/host/resp.d.ts +38 -0
  85. package/lib/host/resp.js +174 -0
  86. package/lib/host/scan-cursors.d.ts +25 -0
  87. package/lib/host/scan-cursors.js +59 -0
  88. package/lib/host/selected-reader.d.ts +22 -0
  89. package/lib/host/selected-reader.js +84 -0
  90. package/lib/host/set-reader.d.ts +12 -0
  91. package/lib/host/set-reader.js +85 -0
  92. package/lib/host/stream-groups.d.ts +17 -0
  93. package/lib/host/stream-groups.js +42 -0
  94. package/lib/host/stream-reader.d.ts +12 -0
  95. package/lib/host/stream-reader.js +105 -0
  96. package/lib/host/string-reader.d.ts +9 -0
  97. package/lib/host/string-reader.js +81 -0
  98. package/lib/host/ui-action-channel.d.ts +4 -0
  99. package/lib/host/ui-action-channel.js +182 -0
  100. package/lib/host/ui-action-coordinator.d.ts +28 -0
  101. package/lib/host/ui-action-coordinator.js +188 -0
  102. package/lib/host/value-prefix.d.ts +5 -0
  103. package/lib/host/value-prefix.js +11 -0
  104. package/lib/host/write-bytes.d.ts +3 -0
  105. package/lib/host/write-bytes.js +9 -0
  106. package/lib/host/write-history.d.ts +18 -0
  107. package/lib/host/write-history.js +79 -0
  108. package/lib/host/write-proposals.d.ts +46 -0
  109. package/lib/host/write-proposals.js +132 -0
  110. package/lib/host/zset-reader.d.ts +12 -0
  111. package/lib/host/zset-reader.js +103 -0
  112. package/lib/host/zset-values.d.ts +6 -0
  113. package/lib/host/zset-values.js +26 -0
  114. package/lib/index.d.ts +6 -0
  115. package/lib/index.js +5 -0
  116. package/lib/redis-answer.d.ts +32 -0
  117. package/lib/redis-answer.js +215 -0
  118. package/lib/redis-databases.d.ts +3 -0
  119. package/lib/redis-databases.js +21 -0
  120. package/lib/redis-read-tools.d.ts +2 -0
  121. package/lib/redis-read-tools.js +7 -0
  122. package/lib/redis-result.d.ts +4 -0
  123. package/lib/redis-result.js +18 -0
  124. package/lib/redis-score.d.ts +2 -0
  125. package/lib/redis-score.js +6 -0
  126. package/lib/remote-service.d.ts +69 -0
  127. package/lib/remote-service.js +187 -0
  128. package/lib/runtime.d.ts +3 -0
  129. package/lib/runtime.js +29 -0
  130. package/lib/stream-id.d.ts +7 -0
  131. package/lib/stream-id.js +19 -0
  132. package/lib/typert.host.d.ts +13 -0
  133. package/lib/typert.host.js +7 -0
  134. package/lib/typert.remote-client.d.ts +98 -0
  135. package/lib/typert.remote-client.js +3 -0
  136. package/lib/typert.shared.d.ts +62 -0
  137. package/lib/typert.shared.js +735 -0
  138. package/lib/ui-action-selection.d.ts +3 -0
  139. package/lib/ui-action-selection.js +12 -0
  140. package/licenses/THIRD_PARTY_NOTICES.txt +9 -0
  141. package/licenses/deepseek-harness-MIT.txt +21 -0
  142. package/licenses/dsh-database-MIT.txt +21 -0
  143. package/licenses/dsh-git-graph-MIT.txt +21 -0
  144. package/licenses/lucide-react-LICENSE.txt +43 -0
  145. package/licenses/phosphor-icons-MIT.txt +21 -0
  146. package/package.json +132 -3
@@ -0,0 +1,120 @@
1
+ /** Profile-owned configuration only. No credential protection or network code belongs here. */
2
+ import { randomUUID } from 'node:crypto';
3
+ import { mkdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';
4
+ import { dirname, resolve } from 'node:path';
5
+ import { MAX_PROFILES } from "../domain.js";
6
+ import { profileCollectionSchema, profileIdSchema, saveProfileSchema } from "../typert.shared.js";
7
+ const MAX_FILE_BYTES = 4 * 1024 * 1024;
8
+ const storageError = () => new Error('Redis connection profiles could not be read or saved.');
9
+ // Only plugin instances in this process participate; external file writers do not.
10
+ const pendingByPath = new Map();
11
+ export class RedisProfiles {
12
+ file;
13
+ queueKey;
14
+ constructor(profileDirectory) {
15
+ this.file = resolve(profileDirectory, 'data', 'dsh-redis', 'connections.json');
16
+ this.queueKey = process.platform === 'win32' ? this.file.toLowerCase() : this.file;
17
+ }
18
+ /** Serialize cooperating instances using the same normalized file path. */
19
+ queue(signal, operation) {
20
+ const result = (pendingByPath.get(this.queueKey) ?? Promise.resolve()).then(() => { signal.throwIfAborted(); return operation(); });
21
+ const tail = result.then(() => undefined, () => undefined);
22
+ pendingByPath.set(this.queueKey, tail);
23
+ void tail.then(() => { if (pendingByPath.get(this.queueKey) === tail)
24
+ pendingByPath.delete(this.queueKey); });
25
+ return result;
26
+ }
27
+ async read() {
28
+ try {
29
+ if ((await stat(this.file)).size > MAX_FILE_BYTES)
30
+ throw storageError();
31
+ const data = JSON.parse(await readFile(this.file, 'utf8'));
32
+ if (typeof data !== 'object' || data === null || Array.isArray(data))
33
+ throw storageError();
34
+ const record = data;
35
+ if (record.version !== 1 || Object.keys(record).some(key => key !== 'version' && key !== 'profiles'))
36
+ throw storageError();
37
+ return profileCollectionSchema.parse({ profiles: record.profiles, selectedId: null });
38
+ }
39
+ catch (error) {
40
+ if (error instanceof Error && 'code' in error && error.code === 'ENOENT')
41
+ return { profiles: [], selectedId: null };
42
+ console.warn('[dsh-redis] Connection profile storage unavailable');
43
+ throw storageError();
44
+ }
45
+ }
46
+ async write(collection) {
47
+ const checked = profileCollectionSchema.parse(collection);
48
+ const content = JSON.stringify({ version: 1, profiles: checked.profiles }, null, 2) + '\n';
49
+ if (Buffer.byteLength(content) > MAX_FILE_BYTES)
50
+ throw storageError();
51
+ const temporary = this.file + '.' + randomUUID() + '.tmp';
52
+ try {
53
+ await mkdir(dirname(this.file), { recursive: true, mode: 0o700 });
54
+ await writeFile(temporary, content, { encoding: 'utf8', flag: 'wx', mode: 0o600 });
55
+ await rename(temporary, this.file);
56
+ }
57
+ catch {
58
+ console.warn('[dsh-redis] Connection profile save failed');
59
+ throw storageError();
60
+ }
61
+ finally {
62
+ try {
63
+ await rm(temporary, { force: true });
64
+ }
65
+ catch {
66
+ console.warn('[dsh-redis] Temporary profile cleanup failed');
67
+ throw storageError();
68
+ }
69
+ }
70
+ }
71
+ list(signal) { return this.queue(signal, () => this.read()); }
72
+ /** Caller prepares its candidate first. No asynchronous work is allowed in commit. */
73
+ withVerifiedProfile(expected, signal, commit) {
74
+ // Parse now to snapshot nested settings before this operation enters the queue.
75
+ const snapshot = profileCollectionSchema.parse({ profiles: [expected], selectedId: null }).profiles[0];
76
+ const normalized = JSON.stringify(snapshot);
77
+ return this.queue(signal, async () => {
78
+ const current = (await this.read()).profiles.find(value => value.id === snapshot.id);
79
+ signal.throwIfAborted();
80
+ if (current === undefined || JSON.stringify(current) !== normalized)
81
+ return false;
82
+ if (commit() !== undefined)
83
+ throw new TypeError('Redis profile commit must be synchronous.');
84
+ return true;
85
+ });
86
+ }
87
+ save(request, signal) {
88
+ const input = saveProfileSchema.parse(request);
89
+ return this.queue(signal, async () => {
90
+ const current = await this.read();
91
+ const id = input.id ?? randomUUID();
92
+ if (input.id !== null && !current.profiles.some(value => value.id === id))
93
+ throw new Error('The saved Redis connection no longer exists.');
94
+ if (input.id === null && current.profiles.length >= MAX_PROFILES)
95
+ throw new Error('The saved Redis connection limit was reached.');
96
+ if (current.profiles.some(value => value.id !== id && value.name === input.name && (value.group ?? '') === (input.group ?? '')))
97
+ throw new Error('A Redis connection with this group and name already exists.');
98
+ const value = { id, name: input.name, ...(input.group === undefined ? {} : { group: input.group }), settings: input.settings };
99
+ const profiles = input.id === null ? [...current.profiles, value] : current.profiles.map(item => item.id === id ? value : item);
100
+ signal.throwIfAborted();
101
+ const result = { profiles, selectedId: id };
102
+ await this.write(result);
103
+ console.info('[dsh-redis] Connection profile saved');
104
+ return result;
105
+ });
106
+ }
107
+ remove(request, signal) {
108
+ const input = profileIdSchema.parse(request);
109
+ return this.queue(signal, async () => {
110
+ const current = await this.read();
111
+ if (!current.profiles.some(value => value.id === input.id))
112
+ throw new Error('The saved Redis connection no longer exists.');
113
+ const result = { profiles: current.profiles.filter(value => value.id !== input.id), selectedId: null };
114
+ signal.throwIfAborted();
115
+ await this.write(result);
116
+ console.info('[dsh-redis] Connection profile removed');
117
+ return result;
118
+ });
119
+ }
120
+ }
@@ -0,0 +1,23 @@
1
+ import type { ConnectionErrorCode, DatabaseTarget } from '../domain.js';
2
+ import { type RedisConnections } from './connection-service.js';
3
+ import { type RedisArgument, type RedisReply } from './resp.js';
4
+ import type { RedisReadCommand } from './redis-transport.js';
5
+ /** One operation owns one absolute deadline across metadata and value commands. */
6
+ export declare class RedisReadContext {
7
+ private readonly connections;
8
+ private readonly sessionId;
9
+ private readonly target;
10
+ private readonly caller;
11
+ private readonly validate;
12
+ private readonly timeout;
13
+ private readonly deadline;
14
+ private readonly timer;
15
+ readonly signal: AbortSignal;
16
+ constructor(connections: RedisConnections, sessionId: string, target: DatabaseTarget, caller: AbortSignal, validate?: () => void);
17
+ command(command: Exclude<RedisReadCommand, 'SELECT'>, arguments_: readonly RedisArgument[]): Promise<RedisReply>;
18
+ type(key: Buffer): Promise<string>;
19
+ integer(command: Exclude<RedisReadCommand, 'SELECT'>, args: readonly RedisArgument[], minimum?: bigint): Promise<bigint>;
20
+ ttl(key: Buffer): Promise<bigint>;
21
+ error(error: unknown): ConnectionErrorCode;
22
+ dispose(): void;
23
+ }
@@ -0,0 +1,41 @@
1
+ import { connectionErrorCode } from "./connection-service.js";
2
+ import { RedisFrameError } from "./resp.js";
3
+ /** One operation owns one absolute deadline across metadata and value commands. */
4
+ export class RedisReadContext {
5
+ connections;
6
+ sessionId;
7
+ target;
8
+ caller;
9
+ validate;
10
+ timeout = new AbortController();
11
+ deadline = Date.now() + 10000;
12
+ timer = setTimeout(() => this.timeout.abort(), 10000);
13
+ signal;
14
+ constructor(connections, sessionId, target, caller, validate = () => undefined) {
15
+ this.connections = connections;
16
+ this.sessionId = sessionId;
17
+ this.target = target;
18
+ this.caller = caller;
19
+ this.validate = validate;
20
+ this.timer.unref();
21
+ this.signal = AbortSignal.any([caller, this.timeout.signal]);
22
+ }
23
+ command(command, arguments_) {
24
+ return this.connections.read(this.sessionId, this.target, command, arguments_, this.signal, this.validate, this.deadline);
25
+ }
26
+ async type(key) {
27
+ const reply = await this.command('TYPE', [key]);
28
+ if (typeof reply !== 'string' || !/^[\w-]{1,128}$/u.test(reply))
29
+ throw new RedisFrameError('protocol');
30
+ return reply;
31
+ }
32
+ async integer(command, args, minimum = 0n) {
33
+ const reply = await this.command(command, args);
34
+ if (typeof reply !== 'bigint' || reply < minimum)
35
+ throw new RedisFrameError('protocol');
36
+ return reply;
37
+ }
38
+ ttl(key) { return this.integer('PTTL', [key], -2n); }
39
+ error(error) { return this.caller.aborted ? 'cancelled' : this.timeout.signal.aborted ? 'timeout' : connectionErrorCode(error); }
40
+ dispose() { clearTimeout(this.timer); }
41
+ }
@@ -0,0 +1,34 @@
1
+ import { type ConnectionRequest } from '../domain.js';
2
+ import { type RedisArgument, type RedisReply } from './resp.js';
3
+ import { type RedisReplaceRequest, type RedisSampleRequest, type RedisWriteResult } from './redis-write-transaction.js';
4
+ export type RedisReadCommand = 'DBSIZE' | 'CONFIG' | 'INFO' | 'MEMORY' | 'SLOWLOG' | 'XINFO' | 'CLIENT' | 'SELECT' | 'SCAN' | 'TYPE' | 'PTTL' | 'STRLEN' | 'GETRANGE' | 'HLEN' | 'HSCAN' | 'HGET' | 'LLEN' | 'LRANGE' | 'SCARD' | 'SSCAN' | 'SISMEMBER' | 'ZCARD' | 'ZRANGE' | 'ZSCAN' | 'ZSCORE' | 'XLEN' | 'XRANGE' | 'XREVRANGE' | 'GEOPOS' | 'GEODIST' | 'JSON.GET' | 'TS.RANGE';
5
+ export declare class RedisTransportError extends Error {
6
+ readonly code: 'network' | 'timeout' | 'cancelled' | 'busy' | 'auth';
7
+ constructor(code: 'network' | 'timeout' | 'cancelled' | 'busy' | 'auth');
8
+ }
9
+ export declare class RedisTransport {
10
+ private readonly socket;
11
+ private readonly tls;
12
+ private failure;
13
+ private active;
14
+ private readonly failures;
15
+ private pending;
16
+ private queued;
17
+ private constructor();
18
+ static open(settings: ConnectionRequest, signal: AbortSignal): Promise<RedisTransport>;
19
+ private ready;
20
+ private fail;
21
+ close(): void;
22
+ onFailure(listener: (error: Error) => void): () => void;
23
+ execute(command: RedisReadCommand, arguments_: readonly RedisArgument[], signal: AbortSignal, beforeDispatch: () => void, deadline?: number): Promise<RedisReply>;
24
+ /** Queue a whole bounded operation, so later commands cannot interleave its frames. */
25
+ private enqueue;
26
+ /** Send one frame inside the owned queue slot; a stalled reply closes the socket. */
27
+ private frame;
28
+ /** A cancelled caller returns promptly, while the queue drains its active frame. */
29
+ private request;
30
+ /** Preview keeps WATCH and its read-only validation in the same queue slot. */
31
+ sampleExisting(request: RedisSampleRequest, signal: AbortSignal, guard: () => void): Promise<Buffer>;
32
+ /** One Host-owned transaction occupies the queue until cleanup or readback settles. */
33
+ replaceExisting(request: RedisReplaceRequest, signal: AbortSignal, guard: (submitted: boolean) => void, submitted: () => void, readback: (sampledAt: string) => void): Promise<RedisWriteResult>;
34
+ }
@@ -0,0 +1,262 @@
1
+ /** One bounded RESP2 command at a time on an owned TCP/TLS connection. */
2
+ import { createConnection, isIP } from 'node:net';
3
+ import { connect as connectTls } from 'node:tls';
4
+ import { MAX_REDIS_WRITE_BYTES } from "../domain.js";
5
+ import { encodeCommand, RedisFrameError, RedisReplyError, RespDecoder } from "./resp.js";
6
+ import { runRedisReplace, runRedisSample } from "./redis-write-transaction.js";
7
+ const READ_COMMANDS = new Set(['DBSIZE', 'CONFIG', 'INFO', 'MEMORY', 'SLOWLOG', 'XINFO', 'CLIENT', 'SELECT', 'SCAN', 'TYPE', 'PTTL', 'STRLEN', 'GETRANGE', 'HLEN', 'HSCAN', 'HGET', 'LLEN', 'LRANGE', 'SCARD', 'SSCAN', 'SISMEMBER', 'ZCARD', 'ZRANGE', 'ZSCAN', 'ZSCORE', 'XLEN', 'XRANGE', 'XREVRANGE', 'GEOPOS', 'GEODIST', 'JSON.GET', 'TS.RANGE']);
8
+ const CONNECT_TIMEOUT = 8000;
9
+ const READ_TIMEOUT = 10000;
10
+ const MAX_QUEUE = 16;
11
+ export class RedisTransportError extends Error {
12
+ code;
13
+ constructor(code) {
14
+ super(code);
15
+ this.code = code;
16
+ }
17
+ }
18
+ export class RedisTransport {
19
+ socket;
20
+ tls;
21
+ failure = null;
22
+ active = null;
23
+ failures = new Set();
24
+ pending = Promise.resolve();
25
+ queued = 0;
26
+ constructor(settings) {
27
+ this.tls = settings.tls !== null;
28
+ const address = { host: settings.host, port: settings.port };
29
+ this.socket = settings.tls === null ? createConnection(address) : connectTls({
30
+ ...address, rejectUnauthorized: true,
31
+ ...(isIP(settings.host) === 0 ? { servername: settings.host } : {}),
32
+ ...(settings.tls.caPem === '' ? {} : { ca: settings.tls.caPem }),
33
+ });
34
+ this.socket.setNoDelay(true);
35
+ this.socket.setKeepAlive(true, 5000);
36
+ this.socket.on('error', (error) => { this.fail(error); });
37
+ this.socket.on('close', () => { this.fail(new RedisTransportError('network')); });
38
+ this.socket.on('data', (chunk) => {
39
+ const active = this.active;
40
+ if (active === null) {
41
+ this.fail(new RedisFrameError('protocol'));
42
+ return;
43
+ }
44
+ try {
45
+ const result = active.decoder.write(chunk);
46
+ if (!result.done)
47
+ return;
48
+ if (result.value instanceof RedisReplyError)
49
+ active.reject(result.value);
50
+ else
51
+ active.resolve(result.value);
52
+ }
53
+ catch (error) {
54
+ this.fail(error instanceof Error ? error : new RedisFrameError('protocol'));
55
+ }
56
+ });
57
+ }
58
+ static async open(settings, signal) {
59
+ if (signal.aborted)
60
+ throw new RedisTransportError('cancelled');
61
+ const deadline = Date.now() + CONNECT_TIMEOUT;
62
+ const transport = new RedisTransport(settings);
63
+ try {
64
+ await transport.ready(deadline, signal);
65
+ if (settings.username !== '' || settings.password !== '') {
66
+ const auth = settings.username === '' ? ['AUTH', settings.password] : ['AUTH', settings.username, settings.password];
67
+ let reply;
68
+ try {
69
+ reply = await transport.request(auth, signal, deadline, () => undefined);
70
+ }
71
+ catch (error) {
72
+ // Redis 5 reports these generic ERR strings specifically for AUTH.
73
+ // Interpret them only here, never in errors that may echo Key names.
74
+ if (error instanceof RedisReplyError && /^(?:ERR invalid password|ERR Client sent AUTH, but no password is set)\.?$/u.test(error.message))
75
+ throw new RedisTransportError('auth');
76
+ throw error;
77
+ }
78
+ if (reply !== 'OK')
79
+ throw new RedisFrameError('protocol');
80
+ }
81
+ if (await transport.request(['PING'], signal, deadline, () => undefined) !== 'PONG')
82
+ throw new RedisFrameError('protocol');
83
+ if (signal.aborted)
84
+ throw new RedisTransportError('cancelled');
85
+ if (transport.failure !== null)
86
+ throw transport.failure;
87
+ return transport;
88
+ }
89
+ catch (error) {
90
+ transport.close();
91
+ throw error;
92
+ }
93
+ }
94
+ ready(deadline, signal) {
95
+ return new Promise((resolve, reject) => {
96
+ let settled = false;
97
+ const event = this.tls ? 'secureConnect' : 'connect';
98
+ const finish = (error) => {
99
+ if (settled)
100
+ return;
101
+ settled = true;
102
+ clearTimeout(timer);
103
+ this.socket.off(event, connected);
104
+ this.socket.off('error', failed);
105
+ this.socket.off('close', closed);
106
+ signal.removeEventListener('abort', cancelled);
107
+ if (error === null)
108
+ resolve();
109
+ else
110
+ reject(error);
111
+ };
112
+ const connected = () => { finish(null); };
113
+ const failed = (error) => { finish(error); };
114
+ const closed = () => { finish(this.failure ?? new RedisTransportError('network')); };
115
+ const cancelled = () => { finish(new RedisTransportError('cancelled')); };
116
+ const timer = setTimeout(() => { finish(new RedisTransportError('timeout')); }, Math.max(0, deadline - Date.now()));
117
+ timer.unref();
118
+ this.socket.once(event, connected);
119
+ this.socket.once('error', failed);
120
+ this.socket.once('close', closed);
121
+ signal.addEventListener('abort', cancelled, { once: true });
122
+ if (signal.aborted)
123
+ cancelled();
124
+ });
125
+ }
126
+ fail(error, notify = true) {
127
+ if (this.failure !== null)
128
+ return;
129
+ this.failure = error;
130
+ this.active?.reject(error);
131
+ this.socket.destroy();
132
+ if (notify)
133
+ for (const listener of this.failures)
134
+ listener(error);
135
+ }
136
+ close() { this.fail(new RedisTransportError('cancelled'), false); }
137
+ onFailure(listener) {
138
+ this.failures.add(listener);
139
+ const failure = this.failure;
140
+ if (failure !== null)
141
+ queueMicrotask(() => { if (this.failures.has(listener))
142
+ listener(failure); });
143
+ return () => { this.failures.delete(listener); };
144
+ }
145
+ execute(command, arguments_, signal, beforeDispatch, deadline = Date.now() + READ_TIMEOUT) {
146
+ // Only an explicit finite time window and bounded raw sample count are allowed.
147
+ if (command === 'TS.RANGE' && !(arguments_.length === 5 && Buffer.isBuffer(arguments_[0]) && typeof arguments_[1] === 'string' && typeof arguments_[2] === 'string' && /^(?:0|[1-9]\d{0,18})$/u.test(arguments_[1]) && /^(?:0|[1-9]\d{0,18})$/u.test(arguments_[2]) && BigInt(arguments_[1]) <= BigInt(arguments_[2]) && BigInt(arguments_[2]) <= 9223372036854775807n && arguments_[3] === 'COUNT' && typeof arguments_[4] === 'string' && /^(?:[1-9]\d?|10[01])$/u.test(arguments_[4])))
148
+ return Promise.reject(new RedisFrameError('protocol'));
149
+ // One explicit JSONPath only; reject formatting options and additional paths.
150
+ if (command === 'JSON.GET' && !(arguments_.length === 2 && Buffer.isBuffer(arguments_[0]) && typeof arguments_[1] === 'string' && arguments_[1].startsWith('$') && Buffer.byteLength(arguments_[1]) <= 1024 && Buffer.from(arguments_[1], 'utf8').toString('utf8') === arguments_[1]))
151
+ return Promise.reject(new RedisFrameError('protocol'));
152
+ // CLIENT contains administrative subcommands: permit only its read-only LIST form.
153
+ if (command === 'CLIENT' && !(arguments_.length === 1 && arguments_[0] === 'LIST'))
154
+ return Promise.reject(new RedisFrameError('protocol'));
155
+ // GEO reads accept only one member or one fixed member pair, never an open search.
156
+ if (command === 'GEOPOS' && !(arguments_.length === 2 && arguments_.every(Buffer.isBuffer)))
157
+ return Promise.reject(new RedisFrameError('protocol'));
158
+ if (command === 'GEODIST' && !(arguments_.length === 4 && arguments_.slice(0, 3).every(Buffer.isBuffer) && typeof arguments_[3] === 'string' && ['m', 'km', 'ft', 'mi'].includes(arguments_[3])))
159
+ return Promise.reject(new RedisFrameError('protocol'));
160
+ if (!READ_COMMANDS.has(command) || (command === 'DBSIZE' && arguments_.length !== 0) || (command === 'CONFIG' && (arguments_.length !== 2 || arguments_[0] !== 'GET' || arguments_[1] !== 'databases')) || (command === 'INFO' && !(arguments_.length === 1 && typeof arguments_[0] === 'string' && ['keyspace', 'server', 'memory', 'clients', 'stats'].includes(arguments_[0]))) || (command === 'MEMORY' && !(arguments_.length === 4 && arguments_[0] === 'USAGE' && Buffer.isBuffer(arguments_[1]) && arguments_[2] === 'SAMPLES' && arguments_[3] === '5')) || (command === 'SLOWLOG' && !(arguments_.length === 2 && arguments_[0] === 'GET' && typeof arguments_[1] === 'string' && /^(?:[1-9]|10)$/u.test(arguments_[1]))) || (command === 'XINFO' && !(arguments_.length === 2 && arguments_[0] === 'GROUPS' && Buffer.isBuffer(arguments_[1]))))
161
+ return Promise.reject(new RedisFrameError('protocol'));
162
+ return this.request([command, ...arguments_], signal, Math.min(deadline, Date.now() + READ_TIMEOUT), beforeDispatch);
163
+ }
164
+ /** Queue a whole bounded operation, so later commands cannot interleave its frames. */
165
+ enqueue(signal, deadline, run, awaitSettlement = false) {
166
+ if (signal.aborted)
167
+ return Promise.reject(new RedisTransportError('cancelled'));
168
+ if (this.queued >= MAX_QUEUE)
169
+ return Promise.reject(new RedisTransportError('busy'));
170
+ this.queued++;
171
+ let started = false;
172
+ const operation = this.pending.then(() => {
173
+ if (signal.aborted)
174
+ throw new RedisTransportError('cancelled');
175
+ if (Date.now() >= deadline)
176
+ throw new RedisTransportError('timeout');
177
+ if (this.failure !== null)
178
+ throw this.failure;
179
+ started = true;
180
+ return run();
181
+ }).finally(() => { this.queued--; });
182
+ this.pending = operation.then(() => undefined, () => undefined);
183
+ let abort = () => undefined;
184
+ let timer;
185
+ const interrupted = new Promise((_resolve, reject) => {
186
+ abort = () => { if (!awaitSettlement || !started)
187
+ reject(new RedisTransportError('cancelled')); };
188
+ signal.addEventListener('abort', abort, { once: true });
189
+ timer = setTimeout(() => { if (!awaitSettlement || !started)
190
+ reject(new RedisTransportError('timeout')); }, Math.max(0, deadline - Date.now()));
191
+ timer.unref();
192
+ if (signal.aborted)
193
+ abort();
194
+ });
195
+ return Promise.race([operation, interrupted]).finally(() => {
196
+ signal.removeEventListener('abort', abort);
197
+ if (timer !== undefined)
198
+ clearTimeout(timer);
199
+ });
200
+ }
201
+ /** Send one frame inside the owned queue slot; a stalled reply closes the socket. */
202
+ frame(encoded, deadline, beforeDispatch) {
203
+ if (Date.now() >= deadline)
204
+ return Promise.reject(new RedisTransportError('timeout'));
205
+ if (this.failure !== null)
206
+ return Promise.reject(this.failure);
207
+ beforeDispatch();
208
+ return new Promise((resolve, reject) => {
209
+ let timer;
210
+ const finish = () => { if (timer !== undefined)
211
+ clearTimeout(timer); if (this.active === active)
212
+ this.active = null; };
213
+ const active = {
214
+ decoder: new RespDecoder(),
215
+ resolve: value => { finish(); resolve(value); },
216
+ reject: error => { finish(); reject(error); },
217
+ };
218
+ this.active = active;
219
+ timer = setTimeout(() => { this.fail(new RedisTransportError('timeout')); }, Math.max(0, deadline - Date.now()));
220
+ timer.unref();
221
+ this.socket.write(encoded, error => { if (error !== null && error !== undefined)
222
+ this.fail(error); });
223
+ });
224
+ }
225
+ /** A cancelled caller returns promptly, while the queue drains its active frame. */
226
+ request(arguments_, signal, deadline, beforeDispatch) {
227
+ if (signal.aborted)
228
+ return Promise.reject(new RedisTransportError('cancelled'));
229
+ if (this.queued >= MAX_QUEUE)
230
+ return Promise.reject(new RedisTransportError('busy'));
231
+ // Snapshot the arguments before waiting, so queued mutable buffers cannot change.
232
+ const encoded = encodeCommand(arguments_);
233
+ return this.enqueue(signal, deadline, () => this.frame(encoded, deadline, beforeDispatch));
234
+ }
235
+ /** Preview keeps WATCH and its read-only validation in the same queue slot. */
236
+ sampleExisting(request, signal, guard) {
237
+ if (!Buffer.isBuffer(request.key) || request.key.length > MAX_REDIS_WRITE_BYTES || (request.type === 'hash' && (!Buffer.isBuffer(request.field) || request.field.length > MAX_REDIS_WRITE_BYTES)) || (request.type !== 'string' && request.type !== 'hash'))
238
+ return Promise.reject(new RedisFrameError('protocol'));
239
+ const snapshot = request.type === 'string' ? { type: 'string', key: Buffer.from(request.key) } : { type: 'hash', key: Buffer.from(request.key), field: Buffer.from(request.field) };
240
+ const deadline = Date.now() + READ_TIMEOUT;
241
+ return this.enqueue(signal, deadline, () => runRedisSample(snapshot, (args, beforeDispatch) => this.frame(encodeCommand(args), deadline, beforeDispatch), () => this.fail(new RedisTransportError('network')), signal, guard));
242
+ }
243
+ /** One Host-owned transaction occupies the queue until cleanup or readback settles. */
244
+ async replaceExisting(request, signal, guard, submitted, readback) {
245
+ if (!Buffer.isBuffer(request.key) || !Buffer.isBuffer(request.before) || !Buffer.isBuffer(request.after)
246
+ || request.key.length > MAX_REDIS_WRITE_BYTES || request.before.length > MAX_REDIS_WRITE_BYTES || request.after.length > MAX_REDIS_WRITE_BYTES
247
+ || (request.type === 'hash' && (!Buffer.isBuffer(request.field) || request.field.length > MAX_REDIS_WRITE_BYTES))
248
+ || (request.type !== 'string' && request.type !== 'hash'))
249
+ return 'not-executed';
250
+ const snapshot = request.type === 'string'
251
+ ? { type: 'string', key: Buffer.from(request.key), before: Buffer.from(request.before), after: Buffer.from(request.after) }
252
+ : { type: 'hash', key: Buffer.from(request.key), field: Buffer.from(request.field), before: Buffer.from(request.before), after: Buffer.from(request.after) };
253
+ const deadline = Date.now() + READ_TIMEOUT;
254
+ let wasSubmitted = false;
255
+ try {
256
+ return await this.enqueue(signal, deadline, () => runRedisReplace(snapshot, (args, beforeDispatch) => this.frame(encodeCommand(args), deadline, beforeDispatch), () => this.fail(new RedisTransportError('network')), signal, guard, () => { submitted(); wasSubmitted = true; }, readback), true);
257
+ }
258
+ catch {
259
+ return wasSubmitted ? 'unknown' : 'not-executed';
260
+ }
261
+ }
262
+ }
@@ -0,0 +1,28 @@
1
+ import { type RedisArgument, type RedisReply } from './resp.js';
2
+ export type RedisReplaceRequest = {
3
+ readonly type: 'string';
4
+ readonly key: Buffer;
5
+ readonly before: Buffer;
6
+ readonly after: Buffer;
7
+ } | {
8
+ readonly type: 'hash';
9
+ readonly key: Buffer;
10
+ readonly field: Buffer;
11
+ readonly before: Buffer;
12
+ readonly after: Buffer;
13
+ };
14
+ export type RedisSampleRequest = {
15
+ readonly type: 'string';
16
+ readonly key: Buffer;
17
+ } | {
18
+ readonly type: 'hash';
19
+ readonly key: Buffer;
20
+ readonly field: Buffer;
21
+ };
22
+ export type RedisWriteResult = 'not-executed' | 'conflict' | 'rejected' | 'written-verified' | 'written-unverified' | 'written-mismatch' | 'unknown';
23
+ type Send = (args: readonly RedisArgument[], beforeDispatch: () => void) => Promise<RedisReply>;
24
+ /** Sample the full target under WATCH and reject any concurrent change. */
25
+ export declare function runRedisSample(request: RedisSampleRequest, send: Send, close: () => void, signal: AbortSignal, guard: () => void): Promise<Buffer>;
26
+ /** Fixed single-target transaction; caller owns the connection for the entire operation. */
27
+ export declare function runRedisReplace(request: RedisReplaceRequest, send: Send, close: () => void, signal: AbortSignal, guard: (submitted: boolean) => void, submitted: () => void, readback: (sampledAt: string) => void): Promise<RedisWriteResult>;
28
+ export {};