@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,180 @@
1
+ import { MAX_REDIS_WRITE_BYTES } from "../domain.js";
2
+ import { RedisReplyError } from "./resp.js";
3
+ class RedisSampleError extends Error {
4
+ }
5
+ async function supportsWrite(command) {
6
+ const info = await command(['INFO', 'server']);
7
+ const version = Buffer.isBuffer(info) ? /^redis_version:(\d+)\.(\d+)\.(\d+)(?:\D|$)/mu.exec(info.toString('utf8')) : null;
8
+ return version !== null && (Number(version[1]) > 7 || Number(version[1]) === 7 && Number(version[2]) >= 4);
9
+ }
10
+ /** Every observation checks the same persistent target before reading bytes. */
11
+ async function persistentTarget(request, command) {
12
+ if (await command(['TYPE', request.key]) !== request.type || await command(['PTTL', request.key]) !== -1n)
13
+ return 'key';
14
+ if (request.type === 'hash') {
15
+ const ttl = await command(['HPTTL', request.key, 'FIELDS', '1', request.field]);
16
+ if (!Array.isArray(ttl) || ttl.length !== 1 || ttl[0] !== -1n)
17
+ return 'field';
18
+ }
19
+ return 'ready';
20
+ }
21
+ function readBytes(request, length, command) {
22
+ return request.type === 'string' ? command(['GETRANGE', request.key, '0', String(length)]) : command(['HGET', request.key, request.field]);
23
+ }
24
+ /** Cleanup runs even after caller cancellation; an uncertain socket is retired. */
25
+ async function cleanTransaction(state, send, close) {
26
+ if (state === 'none')
27
+ return;
28
+ if (state === 'watch' || state === 'multi') {
29
+ try {
30
+ if (await send([state === 'watch' ? 'UNWATCH' : 'DISCARD'], () => undefined) === 'OK')
31
+ return;
32
+ }
33
+ catch { /* retire below */ }
34
+ }
35
+ try {
36
+ close();
37
+ }
38
+ catch { /* preserve the operation's outcome */ }
39
+ }
40
+ /** Sample the full target under WATCH and reject any concurrent change. */
41
+ export async function runRedisSample(request, send, close, signal, guard) {
42
+ let state = 'none';
43
+ const phase = () => state;
44
+ const check = () => { signal.throwIfAborted(); guard(); };
45
+ const command = (args) => send(args, check);
46
+ try {
47
+ if (!await supportsWrite(command))
48
+ throw new RedisSampleError('Redis 版本不支持写入前态检查。');
49
+ state = 'watch';
50
+ if (await command(['WATCH', request.key]) !== 'OK')
51
+ throw new RedisSampleError('Redis 前态监听失败。');
52
+ const target = await persistentTarget(request, command);
53
+ if (target === 'key')
54
+ throw new RedisSampleError('Redis 目标不存在、类型不匹配或有过期时间。');
55
+ if (target === 'field')
56
+ throw new RedisSampleError('Redis 字段不存在或有过期时间。');
57
+ const length = request.type === 'string' ? await command(['STRLEN', request.key]) : await command(['HSTRLEN', request.key, request.field]);
58
+ if (typeof length !== 'bigint' || length < 0n || length > BigInt(MAX_REDIS_WRITE_BYTES))
59
+ throw new RedisSampleError('Redis 前态值超过限制或不可用。');
60
+ const value = await readBytes(request, Number(length), command);
61
+ if (!Buffer.isBuffer(value) || value.length !== Number(length))
62
+ throw new RedisSampleError('Redis 前态值不完整或已变化。');
63
+ state = 'multi';
64
+ if (await command(['MULTI']) !== 'OK')
65
+ throw new RedisSampleError('Redis 前态验证失败。');
66
+ const receipt = await send(['EXEC'], () => { check(); state = 'uncertain'; });
67
+ if (receipt === null) {
68
+ state = 'none';
69
+ throw new RedisSampleError('Redis 前态发生并发变化,请重新发起。');
70
+ }
71
+ if (!Array.isArray(receipt) || receipt.length !== 0)
72
+ throw new RedisSampleError('Redis 前态验证回执异常。');
73
+ state = 'none';
74
+ check();
75
+ return value;
76
+ }
77
+ catch (error) {
78
+ if (error instanceof RedisSampleError)
79
+ throw error;
80
+ throw new RedisSampleError('Redis 前态采样失败,请检查连接、权限和当前目标。');
81
+ }
82
+ finally {
83
+ await cleanTransaction(phase(), send, close);
84
+ }
85
+ }
86
+ /** Fixed single-target transaction; caller owns the connection for the entire operation. */
87
+ export async function runRedisReplace(request, send, close, signal, guard, submitted, readback) {
88
+ let state = 'none';
89
+ let wasSubmitted = false;
90
+ let written = false;
91
+ const phase = () => state;
92
+ const check = () => {
93
+ if (!wasSubmitted)
94
+ signal.throwIfAborted();
95
+ guard(wasSubmitted);
96
+ };
97
+ const command = (args) => send(args, check);
98
+ const matches = async (expected) => {
99
+ if (await persistentTarget(request, command) !== 'ready')
100
+ return false;
101
+ if (request.type === 'string' && await command(['STRLEN', request.key]) !== BigInt(expected.length))
102
+ return false;
103
+ const value = await readBytes(request, expected.length, command);
104
+ return Buffer.isBuffer(value) && value.equals(expected);
105
+ };
106
+ try {
107
+ if (!await supportsWrite(command))
108
+ return 'not-executed';
109
+ // Mark uncertain state before dispatch: a lost response must close or unwatch.
110
+ state = 'watch';
111
+ if (await command(['WATCH', request.key]) !== 'OK')
112
+ return 'not-executed';
113
+ if (!await matches(request.before))
114
+ return 'conflict';
115
+ state = 'multi';
116
+ if (await command(['MULTI']) !== 'OK')
117
+ return 'not-executed';
118
+ const queued = request.type === 'string'
119
+ ? await command(['SET', request.key, request.after])
120
+ : await command(['HSET', request.key, request.field, request.after]);
121
+ if (queued !== 'QUEUED')
122
+ return 'not-executed';
123
+ const reply = await send(['EXEC'], () => {
124
+ check();
125
+ submitted();
126
+ wasSubmitted = true;
127
+ state = 'uncertain';
128
+ });
129
+ if (reply === null) {
130
+ state = 'none';
131
+ return 'conflict';
132
+ }
133
+ if (!Array.isArray(reply) || reply.length !== 1)
134
+ return 'unknown';
135
+ state = 'none';
136
+ if (reply[0] instanceof RedisReplyError)
137
+ return 'rejected';
138
+ if (request.type === 'string' ? reply[0] !== 'OK' : reply[0] !== 0n) {
139
+ // A positive HSET receipt means a write happened but not the expected update.
140
+ if (request.type === 'hash' && reply[0] === 1n)
141
+ return 'written-mismatch';
142
+ return 'unknown';
143
+ }
144
+ written = true;
145
+ // WATCH the readback as a unit: independent reads alone can combine a value
146
+ // and TTL that never coexisted. An empty transaction proves no watched
147
+ // change occurred between the reads and the validation EXEC.
148
+ state = 'watch';
149
+ if (await command(['WATCH', request.key]) !== 'OK')
150
+ return 'written-unverified';
151
+ const matched = await matches(request.after);
152
+ const sampledAt = new Date().toISOString();
153
+ state = 'multi';
154
+ if (await command(['MULTI']) !== 'OK')
155
+ return 'written-unverified';
156
+ const receipt = await send(['EXEC'], () => { check(); state = 'uncertain'; });
157
+ if (receipt === null) {
158
+ state = 'none';
159
+ return 'written-unverified';
160
+ }
161
+ if (!Array.isArray(receipt) || receipt.length !== 0)
162
+ return 'written-unverified';
163
+ state = 'none';
164
+ try {
165
+ readback(sampledAt);
166
+ }
167
+ catch {
168
+ return matched ? 'written-unverified' : 'written-mismatch';
169
+ }
170
+ return matched ? 'written-verified' : 'written-mismatch';
171
+ }
172
+ catch {
173
+ if (wasSubmitted)
174
+ return written ? 'written-unverified' : 'unknown';
175
+ return 'not-executed';
176
+ }
177
+ finally {
178
+ await cleanTransaction(phase(), send, close);
179
+ }
180
+ }
@@ -0,0 +1,38 @@
1
+ /** The RESP2 subset used by fixed Redis reads. Bulk values remain binary-safe. */
2
+ export declare const MAX_REPLY_BYTES: number;
3
+ export declare const MAX_REQUEST_BYTES: number;
4
+ export declare class RedisReplyError extends Error {
5
+ }
6
+ export declare class RedisFrameError extends Error {
7
+ readonly code: 'oversize' | 'protocol';
8
+ constructor(code: 'oversize' | 'protocol');
9
+ }
10
+ export type RedisArgument = string | Buffer;
11
+ export type RedisReply = string | bigint | Buffer | null | RedisReplyError | RedisReply[];
12
+ export type DecodedReply = {
13
+ readonly done: false;
14
+ } | {
15
+ readonly done: true;
16
+ readonly value: RedisReply;
17
+ };
18
+ /** Reject declarations before allocation; never concatenate an unbounded input stream. */
19
+ export declare class RespDecoder {
20
+ private readonly maxBytes;
21
+ private readonly line;
22
+ private lineLength;
23
+ private carriageReturn;
24
+ private bulk;
25
+ private readonly arrays;
26
+ private result;
27
+ private bytes;
28
+ private nodes;
29
+ constructor(maxBytes?: number);
30
+ private consume;
31
+ private accept;
32
+ private integer;
33
+ private header;
34
+ private decoded;
35
+ write(chunk: Buffer): DecodedReply;
36
+ }
37
+ /** Encode only a bounded argument array; Redis command selection stays in Host readers. */
38
+ export declare function encodeCommand(arguments_: readonly RedisArgument[]): Buffer;
@@ -0,0 +1,174 @@
1
+ /** The RESP2 subset used by fixed Redis reads. Bulk values remain binary-safe. */
2
+ export const MAX_REPLY_BYTES = 1024 * 1024;
3
+ export const MAX_REQUEST_BYTES = 128 * 1024;
4
+ const MAX_NODES = 8192;
5
+ const MAX_DEPTH = 32;
6
+ const MAX_LINE_BYTES = 4096;
7
+ const MIN_INTEGER = -(1n << 63n);
8
+ const MAX_INTEGER = (1n << 63n) - 1n;
9
+ export class RedisReplyError extends Error {
10
+ }
11
+ export class RedisFrameError extends Error {
12
+ code;
13
+ constructor(code) {
14
+ super(code);
15
+ this.code = code;
16
+ }
17
+ }
18
+ /** Reject declarations before allocation; never concatenate an unbounded input stream. */
19
+ export class RespDecoder {
20
+ maxBytes;
21
+ line = Buffer.allocUnsafe(MAX_LINE_BYTES);
22
+ lineLength = 0;
23
+ carriageReturn = false;
24
+ bulk = null;
25
+ arrays = [];
26
+ result = null;
27
+ bytes = 0;
28
+ nodes = 0;
29
+ constructor(maxBytes = MAX_REPLY_BYTES) {
30
+ this.maxBytes = maxBytes;
31
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 1 || maxBytes > MAX_REPLY_BYTES)
32
+ throw new RedisFrameError('oversize');
33
+ }
34
+ consume(count) {
35
+ if (this.bytes + count > this.maxBytes)
36
+ throw new RedisFrameError('oversize');
37
+ this.bytes += count;
38
+ }
39
+ accept(value) {
40
+ let next = value;
41
+ // Close nested arrays iteratively, so input depth cannot exhaust the JS stack.
42
+ while (true) {
43
+ const parent = this.arrays.at(-1);
44
+ if (parent === undefined) {
45
+ this.result = { value: next };
46
+ return;
47
+ }
48
+ parent.values.push(next);
49
+ if (--parent.remaining > 0)
50
+ return;
51
+ this.arrays.pop();
52
+ next = parent.values;
53
+ }
54
+ }
55
+ integer(text) {
56
+ if (!/^[+-]?\d{1,20}$/u.test(text))
57
+ throw new RedisFrameError('protocol');
58
+ const value = BigInt(text);
59
+ if (value < MIN_INTEGER || value > MAX_INTEGER)
60
+ throw new RedisFrameError('protocol');
61
+ return value;
62
+ }
63
+ header(line) {
64
+ if (++this.nodes > MAX_NODES)
65
+ throw new RedisFrameError('oversize');
66
+ const prefix = line[0];
67
+ const text = line.subarray(1).toString('utf8');
68
+ if (prefix === 43) {
69
+ this.accept(text);
70
+ return;
71
+ }
72
+ if (prefix === 45) {
73
+ this.accept(new RedisReplyError(text));
74
+ return;
75
+ }
76
+ if (prefix === 58) {
77
+ this.accept(this.integer(text));
78
+ return;
79
+ }
80
+ if (prefix !== 36 && prefix !== 42)
81
+ throw new RedisFrameError('protocol');
82
+ if (!/^(?:-1|\d{1,20})$/u.test(text))
83
+ throw new RedisFrameError('protocol');
84
+ const length = this.integer(text);
85
+ if (length === -1n) {
86
+ this.accept(null);
87
+ return;
88
+ }
89
+ if (length < 0n)
90
+ throw new RedisFrameError('protocol');
91
+ if (prefix === 36) {
92
+ if (length + BigInt(this.bytes) + 2n > BigInt(this.maxBytes))
93
+ throw new RedisFrameError('oversize');
94
+ this.bulk = { value: Buffer.allocUnsafe(Number(length)), offset: 0, ending: 0 };
95
+ }
96
+ else {
97
+ if (length > BigInt(MAX_NODES - this.nodes) || this.arrays.length >= MAX_DEPTH)
98
+ throw new RedisFrameError('oversize');
99
+ if (length === 0n)
100
+ this.accept([]);
101
+ else
102
+ this.arrays.push({ remaining: Number(length), values: [] });
103
+ }
104
+ }
105
+ decoded() {
106
+ const result = this.result;
107
+ return result === null ? { done: false } : { done: true, value: result.value };
108
+ }
109
+ write(chunk) {
110
+ if (this.result !== null)
111
+ throw new RedisFrameError('protocol');
112
+ let offset = 0;
113
+ while (offset < chunk.length) {
114
+ if (this.result !== null)
115
+ throw new RedisFrameError('protocol');
116
+ const bulk = this.bulk;
117
+ if (bulk !== null) {
118
+ if (bulk.offset < bulk.value.length) {
119
+ const count = Math.min(chunk.length - offset, bulk.value.length - bulk.offset);
120
+ this.consume(count);
121
+ chunk.copy(bulk.value, bulk.offset, offset, offset + count);
122
+ offset += count;
123
+ bulk.offset += count;
124
+ if (offset === chunk.length)
125
+ continue;
126
+ }
127
+ this.consume(1);
128
+ if (chunk[offset++] !== (bulk.ending === 0 ? 13 : 10))
129
+ throw new RedisFrameError('protocol');
130
+ if (++bulk.ending === 2) {
131
+ this.bulk = null;
132
+ this.accept(bulk.value);
133
+ }
134
+ continue;
135
+ }
136
+ const byte = chunk[offset++];
137
+ this.consume(1);
138
+ if (this.carriageReturn) {
139
+ if (byte !== 10)
140
+ throw new RedisFrameError('protocol');
141
+ const line = this.line.subarray(0, this.lineLength);
142
+ this.lineLength = 0;
143
+ this.carriageReturn = false;
144
+ this.header(line);
145
+ }
146
+ else if (byte === 13)
147
+ this.carriageReturn = true;
148
+ else {
149
+ if (byte === undefined || byte === 10)
150
+ throw new RedisFrameError('protocol');
151
+ if (this.lineLength === MAX_LINE_BYTES)
152
+ throw new RedisFrameError('oversize');
153
+ this.line[this.lineLength++] = byte;
154
+ }
155
+ }
156
+ return this.decoded();
157
+ }
158
+ }
159
+ /** Encode only a bounded argument array; Redis command selection stays in Host readers. */
160
+ export function encodeCommand(arguments_) {
161
+ if (arguments_.length === 0 || arguments_.length > 1024)
162
+ throw new RedisFrameError('oversize');
163
+ const parts = [Buffer.from('*' + arguments_.length + '\r\n')];
164
+ let bytes = parts[0]?.length ?? 0;
165
+ for (const argument of arguments_) {
166
+ const length = Buffer.isBuffer(argument) ? argument.length : Buffer.byteLength(argument);
167
+ const header = Buffer.from('$' + length + '\r\n');
168
+ if (bytes + header.length + length + 2 > MAX_REQUEST_BYTES)
169
+ throw new RedisFrameError('oversize');
170
+ parts.push(header, Buffer.isBuffer(argument) ? argument : Buffer.from(argument), Buffer.from('\r\n'));
171
+ bytes += header.length + length + 2;
172
+ }
173
+ return Buffer.concat(parts, bytes);
174
+ }
@@ -0,0 +1,25 @@
1
+ import { type RedisReply } from './resp.js';
2
+ export interface ScanState {
3
+ readonly binding: string;
4
+ cursor: string;
5
+ token: string | null;
6
+ }
7
+ /** All SCAN-family cursors are unsigned-64-bit bulk strings, not JS numbers. */
8
+ export declare function scanReply(reply: RedisReply): {
9
+ readonly cursor: string;
10
+ readonly values: readonly RedisReply[];
11
+ };
12
+ /** One in-flight scan per owner, with a consumed token and a reader-defined binding.
13
+ * Each reader owns a store, so different collection views do not invalidate one another.
14
+ */
15
+ export declare class RedisScanCursors {
16
+ private readonly sessions;
17
+ begin(sessionId: string, binding: string, token: string | null): ScanState;
18
+ validate(sessionId: string, state: ScanState): void;
19
+ /** A cancelled SCAN can retry the same stateless cursor after its reply drains. */
20
+ restore(sessionId: string, state: ScanState, token: string | null): boolean;
21
+ advance(sessionId: string, state: ScanState, cursor: string): string | null;
22
+ discard(sessionId: string, state: ScanState): void;
23
+ disposeSession(sessionId: string): void;
24
+ dispose(): void;
25
+ }
@@ -0,0 +1,59 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { ConnectionFailure } from "./connection-service.js";
3
+ import { RedisFrameError } from "./resp.js";
4
+ /** All SCAN-family cursors are unsigned-64-bit bulk strings, not JS numbers. */
5
+ export function scanReply(reply) {
6
+ if (!Array.isArray(reply) || reply.length !== 2 || !Buffer.isBuffer(reply[0]) || !Array.isArray(reply[1]))
7
+ throw new RedisFrameError('protocol');
8
+ const cursor = reply[0].toString('utf8');
9
+ if (!/^(?:0|[1-9]\d{0,19})$/u.test(cursor) || BigInt(cursor) > (1n << 64n) - 1n)
10
+ throw new RedisFrameError('protocol');
11
+ return { cursor, values: reply[1] };
12
+ }
13
+ /** One in-flight scan per owner, with a consumed token and a reader-defined binding.
14
+ * Each reader owns a store, so different collection views do not invalidate one another.
15
+ */
16
+ export class RedisScanCursors {
17
+ sessions = new Map();
18
+ begin(sessionId, binding, token) {
19
+ if (token === null) {
20
+ const state = { binding, cursor: '0', token: null };
21
+ this.sessions.set(sessionId, state);
22
+ return state;
23
+ }
24
+ const state = this.sessions.get(sessionId);
25
+ if (state === undefined || state.binding !== binding || state.token !== token)
26
+ throw new ConnectionFailure('stale');
27
+ state.token = null;
28
+ return state;
29
+ }
30
+ validate(sessionId, state) {
31
+ if (this.sessions.get(sessionId) !== state)
32
+ throw new ConnectionFailure('stale');
33
+ }
34
+ /** A cancelled SCAN can retry the same stateless cursor after its reply drains. */
35
+ restore(sessionId, state, token) {
36
+ if (this.sessions.get(sessionId) !== state || state.token !== null)
37
+ return false;
38
+ if (token === null)
39
+ this.sessions.delete(sessionId);
40
+ else
41
+ state.token = token;
42
+ return true;
43
+ }
44
+ advance(sessionId, state, cursor) {
45
+ this.validate(sessionId, state);
46
+ const token = cursor === '0' ? null : randomUUID();
47
+ if (token === null)
48
+ this.sessions.delete(sessionId);
49
+ else {
50
+ state.cursor = cursor;
51
+ state.token = token;
52
+ }
53
+ return token;
54
+ }
55
+ discard(sessionId, state) { if (this.sessions.get(sessionId) === state)
56
+ this.sessions.delete(sessionId); }
57
+ disposeSession(sessionId) { this.sessions.delete(sessionId); }
58
+ dispose() { this.sessions.clear(); }
59
+ }
@@ -0,0 +1,22 @@
1
+ import type { BytePrefix, ConnectionErrorCode, DatabaseTarget, KeyMetadata, RedisSelectionItem, StreamMessage } from '../domain.js';
2
+ import type { RedisConnections } from './connection-service.js';
3
+ export interface SelectedResult {
4
+ readonly state: 'value' | 'selection-missing' | 'selection-changed' | 'missing' | 'unsupported' | 'changed' | 'failed';
5
+ readonly error: ConnectionErrorCode | null;
6
+ readonly metadata: KeyMetadata | null;
7
+ readonly cell: BytePrefix | null;
8
+ readonly score: string | null;
9
+ readonly sampledAt: string;
10
+ }
11
+ export interface StreamSelectedResult {
12
+ readonly selected: SelectedResult;
13
+ readonly message: StreamMessage | null;
14
+ }
15
+ /** Fixed read commands address exact raw identities; never rescan to find a row. */
16
+ export declare class RedisSelectedReader {
17
+ private readonly connections;
18
+ constructor(connections: RedisConnections);
19
+ read(sessionId: string, target: DatabaseTarget, keyBase64: string, item: RedisSelectionItem, signal: AbortSignal, validate?: () => void, firstMismatch?: 'changed' | 'unsupported'): Promise<SelectedResult>;
20
+ /** Keep a bounded full message internal; ordinary selected-value replies expose only the chosen cell. */
21
+ readStream(sessionId: string, target: DatabaseTarget, keyBase64: string, id: string, fieldIndex: number, expectedFieldBase64: string | null, signal: AbortSignal, validate?: () => void): Promise<StreamSelectedResult>;
22
+ }
@@ -0,0 +1,84 @@
1
+ import { isRedisScore } from "../redis-score.js";
2
+ import { RedisReadContext } from "./read-context.js";
3
+ import { RedisFrameError } from "./resp.js";
4
+ import { RedisLists } from "./list-reader.js";
5
+ import { RedisStreams } from "./stream-reader.js";
6
+ import { valuePrefix } from "./value-prefix.js";
7
+ /** Fixed read commands address exact raw identities; never rescan to find a row. */
8
+ export class RedisSelectedReader {
9
+ connections;
10
+ constructor(connections) {
11
+ this.connections = connections;
12
+ }
13
+ async read(sessionId, target, keyBase64, item, signal, validate = () => undefined, firstMismatch = 'changed') {
14
+ const result = (state, metadata = null, cell = null, score = null, error = null, sampledAt = new Date().toISOString()) => ({ state, error, metadata, cell, score, sampledAt });
15
+ if (item.kind === 'list') {
16
+ const page = await new RedisLists(this.connections).read(sessionId, { target, keyBase64, offset: item.index, count: 1 }, signal, validate);
17
+ return result(page.state === 'page' ? page.entries.length === 0 ? 'selection-missing' : 'value' : page.state === 'unsupported' ? 'changed' : page.state, page.metadata, page.entries[0]?.value ?? null, null, page.error, page.sampledAt);
18
+ }
19
+ if (item.kind === 'stream') {
20
+ return (await this.readStream(sessionId, target, keyBase64, item.id, item.fieldIndex, item.fieldBase64, signal, validate)).selected;
21
+ }
22
+ const context = new RedisReadContext(this.connections, sessionId, target, signal, validate);
23
+ try {
24
+ const key = Buffer.from(keyBase64, 'base64'), firstType = await context.type(key);
25
+ if (firstType === 'none')
26
+ return result('missing');
27
+ // A previously selected row implies a change; an explicit query only establishes a mismatch.
28
+ if (firstType !== item.kind)
29
+ return result(firstMismatch);
30
+ const raw = item.kind === 'hash'
31
+ ? await context.command('HGET', [key, Buffer.from(item.fieldBase64, 'base64')])
32
+ : await context.command(item.kind === 'set' ? 'SISMEMBER' : 'ZSCORE', [key, Buffer.from(item.memberBase64, 'base64')]);
33
+ // Later type and TTL checks may wait in the connection queue.
34
+ const sampledAt = new Date().toISOString();
35
+ const lastType = await context.type(key), ttl = await context.ttl(key);
36
+ if (lastType === 'none' || ttl === -2n)
37
+ return result('missing');
38
+ if (lastType !== firstType)
39
+ return result('changed');
40
+ const metadata = { type: lastType, ttlMs: String(ttl), length: null };
41
+ if (item.kind === 'set') {
42
+ if (raw !== 0n && raw !== 1n)
43
+ throw new RedisFrameError('protocol');
44
+ return result(raw === 0n ? 'selection-missing' : 'value', metadata, raw === 0n ? null : valuePrefix(Buffer.from(item.memberBase64, 'base64')), null, null, sampledAt);
45
+ }
46
+ if (raw === null)
47
+ return result('selection-missing', metadata, null, null, null, sampledAt);
48
+ if (!Buffer.isBuffer(raw))
49
+ throw new RedisFrameError('protocol');
50
+ if (item.kind === 'hash')
51
+ return result('value', metadata, valuePrefix(raw), null, null, sampledAt);
52
+ const score = raw.toString('utf8');
53
+ if (!isRedisScore(score))
54
+ throw new RedisFrameError('protocol');
55
+ return result('value', metadata, valuePrefix(Buffer.from(item.memberBase64, 'base64')), score, null, sampledAt);
56
+ }
57
+ catch (error) {
58
+ const code = context.error(error);
59
+ return result(code === 'type-changed' ? 'changed' : 'failed', null, null, null, code === 'type-changed' ? null : code);
60
+ }
61
+ finally {
62
+ context.dispose();
63
+ }
64
+ }
65
+ /** Keep a bounded full message internal; ordinary selected-value replies expose only the chosen cell. */
66
+ async readStream(sessionId, target, keyBase64, id, fieldIndex, expectedFieldBase64, signal, validate = () => undefined) {
67
+ const reader = new RedisStreams(this.connections);
68
+ try {
69
+ const page = await reader.read(sessionId, { target, keyBase64, direction: 'forward', start: id, end: id, count: 1, cursor: null }, signal, validate);
70
+ const make = (state, cell = null, message = null) => ({ selected: { state, error: page.error, metadata: page.metadata, cell, score: null, sampledAt: page.sampledAt }, message });
71
+ if (page.state !== 'page')
72
+ return make(page.state === 'unsupported' ? 'changed' : page.state);
73
+ const message = page.messages[0], pair = message?.fields[fieldIndex];
74
+ if (pair === undefined || message === undefined)
75
+ return make('selection-missing');
76
+ if (expectedFieldBase64 !== null && pair.field.base64 !== expectedFieldBase64)
77
+ return make('selection-changed');
78
+ return make('value', pair.value, message);
79
+ }
80
+ finally {
81
+ reader.dispose();
82
+ }
83
+ }
84
+ }
@@ -0,0 +1,12 @@
1
+ import { type ScanSetRequest, type ScanSetResult } from '../domain.js';
2
+ import type { RedisConnections } from './connection-service.js';
3
+ /** One SSCAN per action. A full member, not a display prefix, is its identity. */
4
+ export declare class RedisSets {
5
+ private readonly connections;
6
+ private readonly retryCancelled;
7
+ private readonly scans;
8
+ constructor(connections: RedisConnections, retryCancelled?: boolean);
9
+ disposeSession(sessionId: string): void;
10
+ dispose(): void;
11
+ scan(sessionId: string, request: ScanSetRequest, signal: AbortSignal): Promise<ScanSetResult>;
12
+ }