@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.
- package/LICENSE +21 -0
- package/README.md +184 -2
- package/README.zh.md +185 -0
- package/cordis.patch.yml +4 -0
- package/icon.svg +1 -0
- package/lib/client/index.d.ts +4 -0
- package/lib/client.js +7684 -0
- package/lib/connection-errors.d.ts +66 -0
- package/lib/connection-errors.js +21 -0
- package/lib/domain.d.ts +451 -0
- package/lib/domain.js +20 -0
- package/lib/host/ai-answer.d.ts +7 -0
- package/lib/host/ai-answer.js +132 -0
- package/lib/host/ai-budget.d.ts +43 -0
- package/lib/host/ai-budget.js +78 -0
- package/lib/host/ai-connection-tools.d.ts +8 -0
- package/lib/host/ai-connection-tools.js +49 -0
- package/lib/host/ai-hash-filter.d.ts +13 -0
- package/lib/host/ai-hash-filter.js +97 -0
- package/lib/host/ai-hash-pages.d.ts +15 -0
- package/lib/host/ai-hash-pages.js +42 -0
- package/lib/host/ai-key-pages.d.ts +14 -0
- package/lib/host/ai-key-pages.js +27 -0
- package/lib/host/ai-locate-tool.d.ts +6 -0
- package/lib/host/ai-locate-tool.js +234 -0
- package/lib/host/ai-match-tools.d.ts +7 -0
- package/lib/host/ai-match-tools.js +112 -0
- package/lib/host/ai-page-coordinator.d.ts +21 -0
- package/lib/host/ai-page-coordinator.js +81 -0
- package/lib/host/ai-page-store.d.ts +40 -0
- package/lib/host/ai-page-store.js +104 -0
- package/lib/host/ai-profile-tools.d.ts +7 -0
- package/lib/host/ai-profile-tools.js +44 -0
- package/lib/host/ai-query-scope.d.ts +42 -0
- package/lib/host/ai-query-scope.js +104 -0
- package/lib/host/ai-reader.d.ts +219 -0
- package/lib/host/ai-reader.js +1221 -0
- package/lib/host/ai-report-samples.d.ts +26 -0
- package/lib/host/ai-report-samples.js +77 -0
- package/lib/host/ai-report-tools.d.ts +11 -0
- package/lib/host/ai-report-tools.js +70 -0
- package/lib/host/ai-set-pages.d.ts +15 -0
- package/lib/host/ai-set-pages.js +40 -0
- package/lib/host/ai-stream-pages.d.ts +15 -0
- package/lib/host/ai-stream-pages.js +42 -0
- package/lib/host/ai-tools.d.ts +4 -0
- package/lib/host/ai-tools.js +106 -0
- package/lib/host/ai-ui-tools.d.ts +10 -0
- package/lib/host/ai-ui-tools.js +72 -0
- package/lib/host/ai-value.d.ts +12 -0
- package/lib/host/ai-value.js +15 -0
- package/lib/host/ai-write-tools.d.ts +5 -0
- package/lib/host/ai-write-tools.js +101 -0
- package/lib/host/ai-writer.d.ts +25 -0
- package/lib/host/ai-writer.js +77 -0
- package/lib/host/ai-zset-pages.d.ts +15 -0
- package/lib/host/ai-zset-pages.js +40 -0
- package/lib/host/byte-identity.d.ts +3 -0
- package/lib/host/byte-identity.js +12 -0
- package/lib/host/client-list.d.ts +13 -0
- package/lib/host/client-list.js +35 -0
- package/lib/host/connection-service.d.ts +71 -0
- package/lib/host/connection-service.js +468 -0
- package/lib/host/database-reader.d.ts +10 -0
- package/lib/host/database-reader.js +62 -0
- package/lib/host/hash-reader.d.ts +12 -0
- package/lib/host/hash-reader.js +91 -0
- package/lib/host/key-reader.d.ts +20 -0
- package/lib/host/key-reader.js +65 -0
- package/lib/host/list-reader.d.ts +8 -0
- package/lib/host/list-reader.js +61 -0
- package/lib/host/match-preset-store.d.ts +36 -0
- package/lib/host/match-preset-store.js +201 -0
- package/lib/host/profile-snapshots.d.ts +32 -0
- package/lib/host/profile-snapshots.js +187 -0
- package/lib/host/profile-store.d.ts +15 -0
- package/lib/host/profile-store.js +120 -0
- package/lib/host/read-context.d.ts +23 -0
- package/lib/host/read-context.js +41 -0
- package/lib/host/redis-transport.d.ts +34 -0
- package/lib/host/redis-transport.js +262 -0
- package/lib/host/redis-write-transaction.d.ts +28 -0
- package/lib/host/redis-write-transaction.js +180 -0
- package/lib/host/resp.d.ts +38 -0
- package/lib/host/resp.js +174 -0
- package/lib/host/scan-cursors.d.ts +25 -0
- package/lib/host/scan-cursors.js +59 -0
- package/lib/host/selected-reader.d.ts +22 -0
- package/lib/host/selected-reader.js +84 -0
- package/lib/host/set-reader.d.ts +12 -0
- package/lib/host/set-reader.js +85 -0
- package/lib/host/stream-groups.d.ts +17 -0
- package/lib/host/stream-groups.js +42 -0
- package/lib/host/stream-reader.d.ts +12 -0
- package/lib/host/stream-reader.js +105 -0
- package/lib/host/string-reader.d.ts +9 -0
- package/lib/host/string-reader.js +81 -0
- package/lib/host/ui-action-channel.d.ts +4 -0
- package/lib/host/ui-action-channel.js +182 -0
- package/lib/host/ui-action-coordinator.d.ts +28 -0
- package/lib/host/ui-action-coordinator.js +188 -0
- package/lib/host/value-prefix.d.ts +5 -0
- package/lib/host/value-prefix.js +11 -0
- package/lib/host/write-bytes.d.ts +3 -0
- package/lib/host/write-bytes.js +9 -0
- package/lib/host/write-history.d.ts +18 -0
- package/lib/host/write-history.js +79 -0
- package/lib/host/write-proposals.d.ts +46 -0
- package/lib/host/write-proposals.js +132 -0
- package/lib/host/zset-reader.d.ts +12 -0
- package/lib/host/zset-reader.js +103 -0
- package/lib/host/zset-values.d.ts +6 -0
- package/lib/host/zset-values.js +26 -0
- package/lib/index.d.ts +6 -0
- package/lib/index.js +5 -0
- package/lib/redis-answer.d.ts +32 -0
- package/lib/redis-answer.js +215 -0
- package/lib/redis-databases.d.ts +3 -0
- package/lib/redis-databases.js +21 -0
- package/lib/redis-read-tools.d.ts +2 -0
- package/lib/redis-read-tools.js +7 -0
- package/lib/redis-result.d.ts +4 -0
- package/lib/redis-result.js +18 -0
- package/lib/redis-score.d.ts +2 -0
- package/lib/redis-score.js +6 -0
- package/lib/remote-service.d.ts +69 -0
- package/lib/remote-service.js +187 -0
- package/lib/runtime.d.ts +3 -0
- package/lib/runtime.js +29 -0
- package/lib/stream-id.d.ts +7 -0
- package/lib/stream-id.js +19 -0
- package/lib/typert.host.d.ts +13 -0
- package/lib/typert.host.js +7 -0
- package/lib/typert.remote-client.d.ts +98 -0
- package/lib/typert.remote-client.js +3 -0
- package/lib/typert.shared.d.ts +62 -0
- package/lib/typert.shared.js +735 -0
- package/lib/ui-action-selection.d.ts +3 -0
- package/lib/ui-action-selection.js +12 -0
- package/licenses/THIRD_PARTY_NOTICES.txt +9 -0
- package/licenses/deepseek-harness-MIT.txt +21 -0
- package/licenses/dsh-database-MIT.txt +21 -0
- package/licenses/dsh-git-graph-MIT.txt +21 -0
- package/licenses/lucide-react-LICENSE.txt +43 -0
- package/licenses/phosphor-icons-MIT.txt +21 -0
- package/package.json +132 -3
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { MAX_KEY_BYTES, MAX_SCAN_KEYS, MAX_SCAN_JSON_BYTES } from "../domain.js";
|
|
2
|
+
import { RedisFrameError } from "./resp.js";
|
|
3
|
+
import { RedisReadContext } from "./read-context.js";
|
|
4
|
+
import { RedisScanCursors, scanReply } from "./scan-cursors.js";
|
|
5
|
+
import { byteIdentity } from "./byte-identity.js";
|
|
6
|
+
/** One SSCAN per action. A full member, not a display prefix, is its identity. */
|
|
7
|
+
export class RedisSets {
|
|
8
|
+
connections;
|
|
9
|
+
retryCancelled;
|
|
10
|
+
scans = new RedisScanCursors();
|
|
11
|
+
constructor(connections, retryCancelled = false) {
|
|
12
|
+
this.connections = connections;
|
|
13
|
+
this.retryCancelled = retryCancelled;
|
|
14
|
+
}
|
|
15
|
+
disposeSession(sessionId) { this.scans.disposeSession(sessionId); }
|
|
16
|
+
dispose() { this.scans.dispose(); }
|
|
17
|
+
async scan(sessionId, request, signal) {
|
|
18
|
+
let scan;
|
|
19
|
+
const context = new RedisReadContext(this.connections, sessionId, request.target, signal, () => { if (scan !== undefined)
|
|
20
|
+
this.scans.validate(sessionId, scan); });
|
|
21
|
+
const result = (state, error = null, metadata = null) => ({ state, error, metadata, members: [], cursor: null, sampledAt: new Date().toISOString() });
|
|
22
|
+
try {
|
|
23
|
+
signal.throwIfAborted();
|
|
24
|
+
this.connections.assertTarget(sessionId, request.target);
|
|
25
|
+
scan = this.scans.begin(sessionId, JSON.stringify([request.target.id, request.target.generation, request.target.db, request.keyBase64, request.pattern]), request.cursor);
|
|
26
|
+
const key = Buffer.from(request.keyBase64, 'base64'), firstType = await context.type(key);
|
|
27
|
+
if (firstType === 'none')
|
|
28
|
+
return result('missing');
|
|
29
|
+
const firstTtl = await context.ttl(key);
|
|
30
|
+
if (firstTtl === -2n)
|
|
31
|
+
return result('missing');
|
|
32
|
+
if (firstType !== 'set')
|
|
33
|
+
return result('unsupported', null, { type: firstType, ttlMs: String(firstTtl), length: null });
|
|
34
|
+
const length = await context.integer('SCARD', [key]);
|
|
35
|
+
const { cursor, values } = scanReply(await context.command('SSCAN', [key, scan.cursor, 'MATCH', request.pattern, 'COUNT', '100']));
|
|
36
|
+
if (values.length > MAX_SCAN_KEYS)
|
|
37
|
+
throw new RedisFrameError('oversize');
|
|
38
|
+
const members = new Map();
|
|
39
|
+
for (const raw of values) {
|
|
40
|
+
if (!Buffer.isBuffer(raw))
|
|
41
|
+
throw new RedisFrameError('protocol');
|
|
42
|
+
if (raw.length > MAX_KEY_BYTES)
|
|
43
|
+
throw new RedisFrameError('oversize');
|
|
44
|
+
const member = byteIdentity(raw);
|
|
45
|
+
members.set(member.base64, member);
|
|
46
|
+
}
|
|
47
|
+
const secondType = await context.type(key);
|
|
48
|
+
if (secondType === 'none')
|
|
49
|
+
return result('missing');
|
|
50
|
+
if (secondType !== 'set')
|
|
51
|
+
return result('changed');
|
|
52
|
+
const secondLength = await context.integer('SCARD', [key]), ttl = await context.ttl(key);
|
|
53
|
+
if (ttl === -2n)
|
|
54
|
+
return result('missing');
|
|
55
|
+
if (length !== secondLength || BigInt(members.size) > secondLength)
|
|
56
|
+
return result('changed');
|
|
57
|
+
context.signal.throwIfAborted();
|
|
58
|
+
const page = { ...result('page', null, { type: 'set', ttlMs: String(ttl), length: String(secondLength) }), members: [...members.values()] };
|
|
59
|
+
if (Buffer.byteLength(JSON.stringify(page)) + 36 > MAX_SCAN_JSON_BYTES)
|
|
60
|
+
throw new RedisFrameError('oversize');
|
|
61
|
+
const token = this.scans.advance(sessionId, scan, cursor);
|
|
62
|
+
scan = undefined;
|
|
63
|
+
return { ...page, cursor: token };
|
|
64
|
+
}
|
|
65
|
+
catch (error) {
|
|
66
|
+
const code = context.error(error);
|
|
67
|
+
// Only the AI reader retries a cancelled stateless cursor, and only
|
|
68
|
+
// while the same target and reader state remain current.
|
|
69
|
+
if (this.retryCancelled && signal.aborted && scan !== undefined) {
|
|
70
|
+
try {
|
|
71
|
+
this.connections.assertTarget(sessionId, request.target);
|
|
72
|
+
if (this.scans.restore(sessionId, scan, request.cursor))
|
|
73
|
+
scan = undefined;
|
|
74
|
+
}
|
|
75
|
+
catch { /* target changed */ }
|
|
76
|
+
}
|
|
77
|
+
return code === 'type-changed' ? result('changed') : result('failed', code);
|
|
78
|
+
}
|
|
79
|
+
finally {
|
|
80
|
+
if (scan !== undefined)
|
|
81
|
+
this.scans.discard(sessionId, scan);
|
|
82
|
+
context.dispose();
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { byteIdentity } from './byte-identity.js';
|
|
2
|
+
import { type RedisReply } from './resp.js';
|
|
3
|
+
/** XINFO GROUPS has no server-side pagination. Bound the projected result as well as the RESP frame. */
|
|
4
|
+
export declare function projectStreamGroups(reply: RedisReply): {
|
|
5
|
+
groups: {
|
|
6
|
+
name: ReturnType<typeof byteIdentity>;
|
|
7
|
+
consumers: string;
|
|
8
|
+
pending: string;
|
|
9
|
+
lastDeliveredId: string;
|
|
10
|
+
entriesRead: string | null;
|
|
11
|
+
entriesReadReported: boolean;
|
|
12
|
+
lag: string | null;
|
|
13
|
+
lagStatus: "available" | "unknown" | "not-reported";
|
|
14
|
+
}[];
|
|
15
|
+
totalCount: number;
|
|
16
|
+
complete: boolean;
|
|
17
|
+
};
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { isStreamId } from "../stream-id.js";
|
|
2
|
+
import { byteIdentity } from "./byte-identity.js";
|
|
3
|
+
import { RedisFrameError } from "./resp.js";
|
|
4
|
+
/** XINFO GROUPS has no server-side pagination. Bound the projected result as well as the RESP frame. */
|
|
5
|
+
export function projectStreamGroups(reply) {
|
|
6
|
+
if (!Array.isArray(reply))
|
|
7
|
+
throw new RedisFrameError('protocol');
|
|
8
|
+
const groups = [];
|
|
9
|
+
let size = 0;
|
|
10
|
+
for (const row of reply) {
|
|
11
|
+
if (groups.length === 20)
|
|
12
|
+
break;
|
|
13
|
+
if (!Array.isArray(row) || row.length % 2 !== 0)
|
|
14
|
+
throw new RedisFrameError('protocol');
|
|
15
|
+
const fields = new Map();
|
|
16
|
+
for (let index = 0; index < row.length; index += 2) {
|
|
17
|
+
const name = row[index], value = row[index + 1];
|
|
18
|
+
if (!Buffer.isBuffer(name) || value === undefined)
|
|
19
|
+
throw new RedisFrameError('protocol');
|
|
20
|
+
const label = name.toString('utf8');
|
|
21
|
+
if (fields.has(label))
|
|
22
|
+
throw new RedisFrameError('protocol');
|
|
23
|
+
fields.set(label, value);
|
|
24
|
+
}
|
|
25
|
+
const name = fields.get('name'), consumers = fields.get('consumers'), pending = fields.get('pending'), delivered = fields.get('last-delivered-id');
|
|
26
|
+
if (!Buffer.isBuffer(name) || typeof consumers !== 'bigint' || consumers < 0n || typeof pending !== 'bigint' || pending < 0n || !Buffer.isBuffer(delivered) || !isStreamId(delivered.toString('utf8')))
|
|
27
|
+
throw new RedisFrameError('protocol');
|
|
28
|
+
const read = fields.get('entries-read'), lag = fields.get('lag');
|
|
29
|
+
if ((read !== undefined && read !== null && (typeof read !== 'bigint' || read < 0n)) || (lag !== undefined && lag !== null && (typeof lag !== 'bigint' || lag < 0n)))
|
|
30
|
+
throw new RedisFrameError('protocol');
|
|
31
|
+
const group = { name: byteIdentity(name), consumers: consumers.toString(), pending: pending.toString(), lastDeliveredId: delivered.toString('utf8'), entriesRead: typeof read === 'bigint' ? read.toString() : null, entriesReadReported: read !== undefined, lag: typeof lag === 'bigint' ? lag.toString() : null, lagStatus: lag === undefined ? 'not-reported' : lag === null ? 'unknown' : 'available' };
|
|
32
|
+
const bytes = Buffer.byteLength(JSON.stringify(group));
|
|
33
|
+
if (size + bytes > 48 * 1024) {
|
|
34
|
+
if (groups.length === 0)
|
|
35
|
+
throw new RedisFrameError('oversize');
|
|
36
|
+
break;
|
|
37
|
+
}
|
|
38
|
+
size += bytes;
|
|
39
|
+
groups.push(group);
|
|
40
|
+
}
|
|
41
|
+
return { groups, totalCount: reply.length, complete: groups.length === reply.length };
|
|
42
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { type StreamReadRequest, type StreamReadResult } from '../domain.js';
|
|
2
|
+
import type { RedisConnections } from './connection-service.js';
|
|
3
|
+
/** XRANGE/XREVRANGE do not advance consumer groups, add Pending entries or ACK. */
|
|
4
|
+
export declare class RedisStreams {
|
|
5
|
+
private readonly connections;
|
|
6
|
+
private readonly retryCancelled;
|
|
7
|
+
private readonly pages;
|
|
8
|
+
constructor(connections: RedisConnections, retryCancelled?: boolean);
|
|
9
|
+
disposeSession(sessionId: string): void;
|
|
10
|
+
dispose(): void;
|
|
11
|
+
read(sessionId: string, request: StreamReadRequest, signal: AbortSignal, validate?: () => void): Promise<StreamReadResult>;
|
|
12
|
+
}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { MAX_KEY_BYTES, MAX_SCAN_KEYS, MAX_SCAN_JSON_BYTES } from "../domain.js";
|
|
2
|
+
import { compareStreamIds, isStreamId, MAX_STREAM_ID, withinStreamRange } from "../stream-id.js";
|
|
3
|
+
import { RedisFrameError } from "./resp.js";
|
|
4
|
+
import { RedisReadContext } from "./read-context.js";
|
|
5
|
+
import { RedisScanCursors } from "./scan-cursors.js";
|
|
6
|
+
import { byteIdentity } from "./byte-identity.js";
|
|
7
|
+
import { valuePrefix } from "./value-prefix.js";
|
|
8
|
+
/** XRANGE/XREVRANGE do not advance consumer groups, add Pending entries or ACK. */
|
|
9
|
+
export class RedisStreams {
|
|
10
|
+
connections;
|
|
11
|
+
retryCancelled;
|
|
12
|
+
pages = new RedisScanCursors();
|
|
13
|
+
constructor(connections, retryCancelled = false) {
|
|
14
|
+
this.connections = connections;
|
|
15
|
+
this.retryCancelled = retryCancelled;
|
|
16
|
+
}
|
|
17
|
+
disposeSession(sessionId) { this.pages.disposeSession(sessionId); }
|
|
18
|
+
dispose() { this.pages.dispose(); }
|
|
19
|
+
async read(sessionId, request, signal, validate = () => undefined) {
|
|
20
|
+
let pageState;
|
|
21
|
+
const context = new RedisReadContext(this.connections, sessionId, request.target, signal, () => { validate(); if (pageState !== undefined)
|
|
22
|
+
this.pages.validate(sessionId, pageState); });
|
|
23
|
+
const result = (state, error = null, metadata = null) => ({ state, error, metadata, direction: request.direction, start: request.start, end: request.end, messages: [], cursor: null, sampledAt: new Date().toISOString() });
|
|
24
|
+
try {
|
|
25
|
+
signal.throwIfAborted();
|
|
26
|
+
this.connections.assertTarget(sessionId, request.target);
|
|
27
|
+
pageState = this.pages.begin(sessionId, JSON.stringify([request.target.id, request.target.generation, request.target.db, request.keyBase64, request.direction, request.start, request.end]), request.cursor);
|
|
28
|
+
const key = Buffer.from(request.keyBase64, 'base64'), firstType = await context.type(key);
|
|
29
|
+
if (firstType === 'none')
|
|
30
|
+
return result('missing');
|
|
31
|
+
const firstTtl = await context.ttl(key);
|
|
32
|
+
if (firstTtl === -2n)
|
|
33
|
+
return result('missing');
|
|
34
|
+
if (firstType !== 'stream')
|
|
35
|
+
return result('unsupported', null, { type: firstType, ttlMs: String(firstTtl), length: null });
|
|
36
|
+
const length = await context.integer('XLEN', [key]), forward = request.direction === 'forward';
|
|
37
|
+
// '0' is the cursor store's fresh-page sentinel, never a Stream message ID.
|
|
38
|
+
const boundary = pageState.cursor === '0' ? (forward ? request.start : request.end) : '(' + pageState.cursor;
|
|
39
|
+
const reply = await context.command(forward ? 'XRANGE' : 'XREVRANGE', [key, boundary, forward ? request.end : request.start, 'COUNT', String(request.count)]);
|
|
40
|
+
if (!Array.isArray(reply) || reply.length > request.count)
|
|
41
|
+
throw new RedisFrameError('protocol');
|
|
42
|
+
let previous = pageState.cursor === '0' ? null : pageState.cursor, fields = 0;
|
|
43
|
+
const messages = reply.map(raw => {
|
|
44
|
+
if (!Array.isArray(raw) || raw.length !== 2 || !Buffer.isBuffer(raw[0]) || !Array.isArray(raw[1]) || raw[1].length === 0 || raw[1].length % 2 !== 0)
|
|
45
|
+
throw new RedisFrameError('protocol');
|
|
46
|
+
const id = raw[0].toString('utf8');
|
|
47
|
+
if (!isStreamId(id) || id === '0-0' || !withinStreamRange(id, request.start, request.end) || (previous !== null && (forward ? compareStreamIds(id, previous) <= 0 : compareStreamIds(id, previous) >= 0)))
|
|
48
|
+
throw new RedisFrameError('protocol');
|
|
49
|
+
previous = id;
|
|
50
|
+
fields += raw[1].length / 2;
|
|
51
|
+
if (fields > MAX_SCAN_KEYS)
|
|
52
|
+
throw new RedisFrameError('oversize');
|
|
53
|
+
const pairs = [];
|
|
54
|
+
for (let index = 0; index < raw[1].length; index += 2) {
|
|
55
|
+
const field = raw[1][index], value = raw[1][index + 1];
|
|
56
|
+
if (!Buffer.isBuffer(field) || !Buffer.isBuffer(value))
|
|
57
|
+
throw new RedisFrameError('protocol');
|
|
58
|
+
if (field.length > MAX_KEY_BYTES)
|
|
59
|
+
throw new RedisFrameError('oversize');
|
|
60
|
+
pairs.push({ field: byteIdentity(field), value: valuePrefix(value) });
|
|
61
|
+
}
|
|
62
|
+
return { id, fields: pairs };
|
|
63
|
+
});
|
|
64
|
+
const secondType = await context.type(key);
|
|
65
|
+
if (secondType === 'none')
|
|
66
|
+
return result('missing');
|
|
67
|
+
if (secondType !== 'stream')
|
|
68
|
+
return result('changed');
|
|
69
|
+
const secondLength = await context.integer('XLEN', [key]), ttl = await context.ttl(key);
|
|
70
|
+
if (ttl === -2n)
|
|
71
|
+
return result('missing');
|
|
72
|
+
// Appends need not invalidate an ID-based page; trimming/deletion may do so.
|
|
73
|
+
// An equal-length replacement still cannot be detected as an atomic snapshot.
|
|
74
|
+
if (secondLength < length || BigInt(messages.length) > secondLength)
|
|
75
|
+
return result('changed');
|
|
76
|
+
context.signal.throwIfAborted();
|
|
77
|
+
const page = { ...result('page', null, { type: 'stream', ttlMs: String(ttl), length: String(secondLength) }), messages };
|
|
78
|
+
if (Buffer.byteLength(JSON.stringify(page)) + 36 > MAX_SCAN_JSON_BYTES)
|
|
79
|
+
throw new RedisFrameError('oversize');
|
|
80
|
+
const last = messages.at(-1)?.id;
|
|
81
|
+
const done = messages.length < request.count || last === (forward ? request.end : request.start) || (forward ? last === MAX_STREAM_ID : last === '0-1');
|
|
82
|
+
const token = this.pages.advance(sessionId, pageState, done || last === undefined ? '0' : last);
|
|
83
|
+
pageState = undefined;
|
|
84
|
+
return { ...page, cursor: token };
|
|
85
|
+
}
|
|
86
|
+
catch (error) {
|
|
87
|
+
const code = context.error(error);
|
|
88
|
+
// AI continuation may retry a cancelled range while the target is current.
|
|
89
|
+
if (this.retryCancelled && signal.aborted && pageState !== undefined) {
|
|
90
|
+
try {
|
|
91
|
+
this.connections.assertTarget(sessionId, request.target);
|
|
92
|
+
if (this.pages.restore(sessionId, pageState, request.cursor))
|
|
93
|
+
pageState = undefined;
|
|
94
|
+
}
|
|
95
|
+
catch { /* target changed */ }
|
|
96
|
+
}
|
|
97
|
+
return code === 'type-changed' ? result('changed') : result('failed', code);
|
|
98
|
+
}
|
|
99
|
+
finally {
|
|
100
|
+
if (pageState !== undefined)
|
|
101
|
+
this.pages.discard(sessionId, pageState);
|
|
102
|
+
context.dispose();
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { type StringReadRequest, type StringReadResult } from '../domain.js';
|
|
2
|
+
import type { RedisConnections } from './connection-service.js';
|
|
3
|
+
/** Only fixed metadata and GETRANGE operations; never fetch a full value then truncate. */
|
|
4
|
+
export declare class RedisStrings {
|
|
5
|
+
private readonly connections;
|
|
6
|
+
private readonly includeTextContext;
|
|
7
|
+
constructor(connections: RedisConnections, includeTextContext?: boolean);
|
|
8
|
+
read(sessionId: string, request: StringReadRequest, signal: AbortSignal, validateType?: (type: string) => string | null): Promise<StringReadResult>;
|
|
9
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { MAX_VALUE_BYTES } from "../domain.js";
|
|
2
|
+
import { RedisFrameError } from "./resp.js";
|
|
3
|
+
import { RedisReadContext } from "./read-context.js";
|
|
4
|
+
const MAX_INTEGER = (1n << 63n) - 1n;
|
|
5
|
+
class InvalidTypeArguments extends Error {
|
|
6
|
+
}
|
|
7
|
+
/** Only fixed metadata and GETRANGE operations; never fetch a full value then truncate. */
|
|
8
|
+
export class RedisStrings {
|
|
9
|
+
connections;
|
|
10
|
+
includeTextContext;
|
|
11
|
+
constructor(connections, includeTextContext = true) {
|
|
12
|
+
this.connections = connections;
|
|
13
|
+
this.includeTextContext = includeTextContext;
|
|
14
|
+
}
|
|
15
|
+
async read(sessionId, request, signal, validateType) {
|
|
16
|
+
const context = new RedisReadContext(this.connections, sessionId, request.target, signal);
|
|
17
|
+
const result = (state, error = null, metadata = null) => ({
|
|
18
|
+
state, error, metadata, offset: request.offset, base64: '', byteLength: 0, prefix: '', suffix: '', complete: false, nextOffset: null, sampledAt: new Date().toISOString(),
|
|
19
|
+
});
|
|
20
|
+
try {
|
|
21
|
+
const key = Buffer.from(request.keyBase64, 'base64');
|
|
22
|
+
const firstType = await context.type(key);
|
|
23
|
+
if (firstType === 'none')
|
|
24
|
+
return result('missing');
|
|
25
|
+
// AI callers can reject incompatible ranges before any value is fetched.
|
|
26
|
+
const argumentError = validateType?.(firstType) ?? null;
|
|
27
|
+
if (argumentError !== null)
|
|
28
|
+
throw new InvalidTypeArguments(argumentError);
|
|
29
|
+
const firstTtl = await context.ttl(key);
|
|
30
|
+
if (firstTtl === -2n)
|
|
31
|
+
return result('missing');
|
|
32
|
+
if (firstType !== 'string')
|
|
33
|
+
return result('unsupported', null, { type: firstType, ttlMs: String(firstTtl), length: null });
|
|
34
|
+
const firstLength = await context.integer('STRLEN', [key]), offset = BigInt(request.offset);
|
|
35
|
+
// AI reads use no context, so Redis receives precisely the requested range.
|
|
36
|
+
const contextBytes = this.includeTextContext ? 3n : 0n;
|
|
37
|
+
const start = offset > contextBytes ? offset - contextBytes : 0n;
|
|
38
|
+
const wantedEnd = offset + BigInt(request.count) + contextBytes - 1n;
|
|
39
|
+
const end = wantedEnd > MAX_INTEGER ? MAX_INTEGER : wantedEnd;
|
|
40
|
+
const reply = await context.command('GETRANGE', [key, String(start), String(end)]);
|
|
41
|
+
if (!Buffer.isBuffer(reply))
|
|
42
|
+
throw new RedisFrameError('protocol');
|
|
43
|
+
if (reply.length > MAX_VALUE_BYTES + Number(contextBytes * 2n) || reply.length > request.count + Number(offset - start + contextBytes))
|
|
44
|
+
throw new RedisFrameError('oversize');
|
|
45
|
+
const secondType = await context.type(key);
|
|
46
|
+
if (secondType === 'none')
|
|
47
|
+
return result('missing');
|
|
48
|
+
if (secondType !== firstType)
|
|
49
|
+
return result('changed');
|
|
50
|
+
const secondLength = await context.integer('STRLEN', [key]), secondTtl = await context.ttl(key);
|
|
51
|
+
if (secondTtl === -2n)
|
|
52
|
+
return result('missing');
|
|
53
|
+
if (firstLength !== secondLength)
|
|
54
|
+
return result('changed');
|
|
55
|
+
const available = firstLength > start ? firstLength - start : 0n;
|
|
56
|
+
const expected = available < end - start + 1n ? available : end - start + 1n;
|
|
57
|
+
if (BigInt(reply.length) !== expected)
|
|
58
|
+
return result('changed');
|
|
59
|
+
const skip = Math.min(Number(offset - start), reply.length);
|
|
60
|
+
const bytes = reply.subarray(skip, skip + request.count);
|
|
61
|
+
// UI context can complete a crossing UTF-8 scalar; AI requests omit it.
|
|
62
|
+
const prefix = reply.subarray(0, skip), suffix = reply.subarray(skip + request.count);
|
|
63
|
+
const next = offset + BigInt(bytes.length);
|
|
64
|
+
return {
|
|
65
|
+
...result('value', null, { type: firstType, ttlMs: String(secondTtl), length: String(secondLength) }),
|
|
66
|
+
base64: bytes.toString('base64'), byteLength: bytes.length, prefix: prefix.toString('base64'), suffix: suffix.toString('base64'),
|
|
67
|
+
complete: offset === 0n && BigInt(bytes.length) === secondLength,
|
|
68
|
+
nextOffset: bytes.length > 0 && next < secondLength ? String(next) : null,
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
catch (error) {
|
|
72
|
+
if (error instanceof InvalidTypeArguments)
|
|
73
|
+
throw error;
|
|
74
|
+
const code = context.error(error);
|
|
75
|
+
return code === 'type-changed' ? result('changed') : result('failed', code);
|
|
76
|
+
}
|
|
77
|
+
finally {
|
|
78
|
+
context.dispose();
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { UiActionCoordinator } from './ui-action-coordinator.js';
|
|
2
|
+
import type { SelectionAck, SetSelectionRequest, UiAction, UiChannelInput, UiChannelMessage } from '../domain.js';
|
|
3
|
+
/** One bounded downlink per mounted client; the uplink belongs to that same client. */
|
|
4
|
+
export declare function openUiActionChannel(coordinator: UiActionCoordinator<UiAction>, sessionId: string, signal: AbortSignal, uplink: AsyncIterable<UiChannelInput>, publish: (request: SetSelectionRequest, source: 'manual' | 'action') => SelectionAck): AsyncGenerator<UiChannelMessage>;
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
import { selectionForAction } from "../ui-action-selection.js";
|
|
2
|
+
import { UiActionCoordinator } from "./ui-action-coordinator.js";
|
|
3
|
+
import { uiChannelInputSchema } from "../typert.shared.js";
|
|
4
|
+
/** One bounded downlink per mounted client; the uplink belongs to that same client. */
|
|
5
|
+
export async function* openUiActionChannel(coordinator, sessionId, signal, uplink, publish) {
|
|
6
|
+
const queue = [];
|
|
7
|
+
let wake = null, closed = false;
|
|
8
|
+
let selection = null;
|
|
9
|
+
let notifyClosed;
|
|
10
|
+
const closedSignal = new Promise(resolve => { notifyClosed = () => resolve(null); });
|
|
11
|
+
const state = { pending: null };
|
|
12
|
+
const iterator = uplink[Symbol.asyncIterator]();
|
|
13
|
+
const notify = () => { const waiting = wake; wake = null; waiting?.(); };
|
|
14
|
+
const close = () => {
|
|
15
|
+
if (closed)
|
|
16
|
+
return;
|
|
17
|
+
closed = true;
|
|
18
|
+
queue.length = 0;
|
|
19
|
+
unregister();
|
|
20
|
+
signal.removeEventListener('abort', close);
|
|
21
|
+
const current = state.pending;
|
|
22
|
+
state.pending = null;
|
|
23
|
+
current?.cleanup();
|
|
24
|
+
current?.reject();
|
|
25
|
+
notify();
|
|
26
|
+
notifyClosed();
|
|
27
|
+
if (iterator.return !== undefined)
|
|
28
|
+
void Promise.resolve().then(() => iterator.return?.()).catch(() => undefined);
|
|
29
|
+
};
|
|
30
|
+
const enqueue = (message) => {
|
|
31
|
+
if (closed)
|
|
32
|
+
return;
|
|
33
|
+
// A slow or abandoned client must not accumulate actions indefinitely.
|
|
34
|
+
if (queue.length >= 2) {
|
|
35
|
+
close();
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
queue.push(message);
|
|
39
|
+
notify();
|
|
40
|
+
};
|
|
41
|
+
const receive = (request, actionSignal) => new Promise((resolve, reject) => {
|
|
42
|
+
if (closed || state.pending !== null || actionSignal.aborted) {
|
|
43
|
+
reject(new Error('界面通道不可用。'));
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
if (request.target !== null && (selection === null || !selection.synchronized || selection.revision !== request.selectionRevision)) {
|
|
47
|
+
resolve({ requestId: request.requestId, target: request.target, selectionRevision: request.selectionRevision, outcome: 'stale' });
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
const cancelled = () => {
|
|
51
|
+
const current = state.pending;
|
|
52
|
+
if (current === null || current.request.requestId !== request.requestId)
|
|
53
|
+
return;
|
|
54
|
+
state.pending = null;
|
|
55
|
+
current.cleanup();
|
|
56
|
+
const index = queue.findIndex(item => item.kind === 'action' && item.request.requestId === request.requestId);
|
|
57
|
+
if (index >= 0)
|
|
58
|
+
queue.splice(index, 1);
|
|
59
|
+
else
|
|
60
|
+
enqueue({ kind: 'cancel', requestId: request.requestId });
|
|
61
|
+
reject(new Error('界面动作已取消。'));
|
|
62
|
+
};
|
|
63
|
+
state.pending = { request, signal: actionSignal, resolve, reject: () => reject(new Error('界面通道已关闭。')), cleanup: () => actionSignal.removeEventListener('abort', cancelled), prepared: null, publishedRevision: null };
|
|
64
|
+
actionSignal.addEventListener('abort', cancelled, { once: true });
|
|
65
|
+
if (actionSignal.aborted) {
|
|
66
|
+
cancelled();
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
69
|
+
enqueue({ kind: 'action', request });
|
|
70
|
+
});
|
|
71
|
+
const unregister = coordinator.register(sessionId, receive);
|
|
72
|
+
signal.addEventListener('abort', close, { once: true });
|
|
73
|
+
if (signal.aborted)
|
|
74
|
+
close();
|
|
75
|
+
void (async () => {
|
|
76
|
+
try {
|
|
77
|
+
while (!closed) {
|
|
78
|
+
const result = await Promise.race([iterator.next(), closedSignal]);
|
|
79
|
+
if (result === null || result.done)
|
|
80
|
+
break;
|
|
81
|
+
const input = uiChannelInputSchema.parse(result.value);
|
|
82
|
+
if ('kind' in input) {
|
|
83
|
+
if (input.kind === 'commitSelection') {
|
|
84
|
+
const current = state.pending, request = current?.request;
|
|
85
|
+
const latestSelection = selection;
|
|
86
|
+
const selected = request === undefined ? null : selectionForAction(request.action);
|
|
87
|
+
const valid = current !== null && request !== undefined && selected !== null && request.target !== null && request.requestId === input.requestId && request.selectionRevision === input.revision && latestSelection !== null && latestSelection.revision === input.revision && latestSelection.synchronized && input.nextRevision === input.revision + 1 && !current.signal.aborted && coordinator.canCommit(sessionId, receive, request) && (request.action.kind === 'selectKey' || coordinator.pointSucceeded(sessionId, request));
|
|
88
|
+
// Prepare only. The visible client publishes the matching identity after rendering.
|
|
89
|
+
const accepted = valid;
|
|
90
|
+
if (accepted) {
|
|
91
|
+
selection = { revision: input.nextRevision, synchronized: false };
|
|
92
|
+
coordinator.setSelectionState(sessionId, receive, input.nextRevision, false);
|
|
93
|
+
current.prepared = { target: request.target, selection: selected };
|
|
94
|
+
coordinator.markPrepared(sessionId, receive, request);
|
|
95
|
+
}
|
|
96
|
+
else if (current !== null && request !== undefined && selected !== null && request.requestId === input.requestId) {
|
|
97
|
+
// A matching refusal is terminal even if no further client frame arrives.
|
|
98
|
+
if (latestSelection !== null && latestSelection.revision === request.selectionRevision && request.selectionRevision < Number.MAX_SAFE_INTEGER) {
|
|
99
|
+
selection = { revision: request.selectionRevision + 1, synchronized: false };
|
|
100
|
+
coordinator.setSelectionState(sessionId, receive, selection.revision, false);
|
|
101
|
+
}
|
|
102
|
+
state.pending = null;
|
|
103
|
+
current.cleanup();
|
|
104
|
+
current.resolve({ requestId: request.requestId, target: request.target, selectionRevision: request.selectionRevision, outcome: 'stale' });
|
|
105
|
+
}
|
|
106
|
+
enqueue({ kind: 'selectionResult', requestId: input.requestId, accepted });
|
|
107
|
+
continue;
|
|
108
|
+
}
|
|
109
|
+
if (input.kind === 'publishSelection') {
|
|
110
|
+
const current = state.pending;
|
|
111
|
+
const prepared = current?.prepared;
|
|
112
|
+
const validPublication = selection !== null && selection.revision === input.revision && coordinator.isUniqueReceiver(sessionId, receive);
|
|
113
|
+
const matchingAction = current !== null && prepared !== null && prepared !== undefined && current.publishedRevision === null && validPublication && input.actionRequestId === current.request.requestId && JSON.stringify(prepared) === JSON.stringify(input.request) && !current.signal.aborted && coordinator.canCommit(sessionId, receive, current.request);
|
|
114
|
+
// An expired or forged action token can never become a manual selection.
|
|
115
|
+
if (input.actionRequestId !== undefined && !matchingAction) {
|
|
116
|
+
enqueue({ kind: 'selectionResult', requestId: input.requestId, accepted: false });
|
|
117
|
+
continue;
|
|
118
|
+
}
|
|
119
|
+
if (prepared !== null && prepared !== undefined && !matchingAction)
|
|
120
|
+
coordinator.invalidateSession(sessionId);
|
|
121
|
+
const accepted = validPublication && publish(input.request, matchingAction ? 'action' : 'manual').accepted;
|
|
122
|
+
if (matchingAction && current !== null && accepted)
|
|
123
|
+
current.publishedRevision = input.revision;
|
|
124
|
+
enqueue({ kind: 'selectionResult', requestId: input.requestId, accepted });
|
|
125
|
+
if (matchingAction && current !== null && !accepted) {
|
|
126
|
+
state.pending = null;
|
|
127
|
+
current.cleanup();
|
|
128
|
+
current.resolve({ requestId: current.request.requestId, target: current.request.target, selectionRevision: current.request.selectionRevision, outcome: 'stale' });
|
|
129
|
+
}
|
|
130
|
+
continue;
|
|
131
|
+
}
|
|
132
|
+
if (selection !== null && (input.revision < selection.revision || (input.revision === selection.revision && selection.synchronized && !input.synchronized)))
|
|
133
|
+
throw new Error('选择版本回退。');
|
|
134
|
+
const current = state.pending;
|
|
135
|
+
if (current?.prepared !== null && current?.prepared !== undefined) {
|
|
136
|
+
if (current.publishedRevision !== null && current.publishedRevision !== input.revision) {
|
|
137
|
+
coordinator.invalidateSession(sessionId);
|
|
138
|
+
if (input.synchronized)
|
|
139
|
+
throw new Error('新的界面选择尚未发布。');
|
|
140
|
+
}
|
|
141
|
+
else if (input.synchronized && current.publishedRevision === null)
|
|
142
|
+
throw new Error('界面动作尚未确认。');
|
|
143
|
+
}
|
|
144
|
+
else if (selection !== null && (input.revision !== selection.revision || !input.synchronized))
|
|
145
|
+
coordinator.invalidateSession(sessionId);
|
|
146
|
+
selection = input;
|
|
147
|
+
coordinator.setSelectionState(sessionId, receive, input.revision, input.synchronized);
|
|
148
|
+
if (current?.prepared !== null && current?.prepared !== undefined && current.publishedRevision === input.revision && input.synchronized && !current.signal.aborted && coordinator.canCommit(sessionId, receive, current.request)) {
|
|
149
|
+
state.pending = null;
|
|
150
|
+
current.cleanup();
|
|
151
|
+
current.resolve({ requestId: current.request.requestId, target: current.request.target, selectionRevision: current.request.selectionRevision, outcome: 'applied' });
|
|
152
|
+
}
|
|
153
|
+
continue;
|
|
154
|
+
}
|
|
155
|
+
const current = state.pending;
|
|
156
|
+
if (current !== null && input.requestId === current.request.requestId) {
|
|
157
|
+
state.pending = null;
|
|
158
|
+
current.cleanup();
|
|
159
|
+
current.resolve(selectionForAction(current.request.action) !== null && input.outcome === 'applied' ? { ...input, outcome: 'failed' } : input);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
catch { /* A broken uplink closes the receiver below. */ }
|
|
164
|
+
finally {
|
|
165
|
+
close();
|
|
166
|
+
}
|
|
167
|
+
})();
|
|
168
|
+
try {
|
|
169
|
+
while (!closed) {
|
|
170
|
+
const message = queue.shift();
|
|
171
|
+
if (message !== undefined) {
|
|
172
|
+
yield message;
|
|
173
|
+
continue;
|
|
174
|
+
}
|
|
175
|
+
await new Promise(resolve => { wake = resolve; if (closed || queue.length > 0)
|
|
176
|
+
notify(); });
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
finally {
|
|
180
|
+
close();
|
|
181
|
+
}
|
|
182
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { DatabaseTarget, UiActionAck, UiActionOutcome, UiActionRequest } from '../domain.js';
|
|
2
|
+
type Receiver<Action> = (request: UiActionRequest<Action>, signal: AbortSignal) => Promise<UiActionAck>;
|
|
3
|
+
/** Coordinates one bounded action per trusted session; actual UI work belongs to the receiver. */
|
|
4
|
+
export declare class UiActionCoordinator<Action> {
|
|
5
|
+
private readonly sessions;
|
|
6
|
+
register(sessionId: string, receive: Receiver<Action>): () => void;
|
|
7
|
+
/** State belongs to a particular registered stream, never to a model argument. */
|
|
8
|
+
setSelectionState(sessionId: string, receive: Receiver<Action>, revision: number, synchronized: boolean): void;
|
|
9
|
+
selectionRevision(sessionId: string): number | null;
|
|
10
|
+
isUniqueReceiver(sessionId: string, receive: Receiver<Action>): boolean;
|
|
11
|
+
/** A commit is valid only for the still-pending request on its unique stream. */
|
|
12
|
+
canCommit(sessionId: string, receive: Receiver<Action>, request: UiActionRequest<Action>): boolean;
|
|
13
|
+
/** Resolve an unprepared action only while its original selection remains current. */
|
|
14
|
+
activeRequest(sessionId: string, requestId: string): UiActionRequest<Action> | null;
|
|
15
|
+
/** A UI action may sample its point once, even if that sample is cancelled. */
|
|
16
|
+
claimPoint(sessionId: string, request: UiActionRequest<Action>): boolean;
|
|
17
|
+
/** The Host marks the bound point sample only after a successful, current read. */
|
|
18
|
+
markPointSucceeded(sessionId: string, request: UiActionRequest<Action>): boolean;
|
|
19
|
+
pointSucceeded(sessionId: string, request: UiActionRequest<Action>): boolean;
|
|
20
|
+
/** Once Host has prepared an action, interruptions cannot prove UI application either way. */
|
|
21
|
+
markPrepared(sessionId: string, receive: Receiver<Action>, request: UiActionRequest<Action>): void;
|
|
22
|
+
dispatch(sessionId: string, action: Action, target: DatabaseTarget | null, selectionRevision: number, isCurrent: () => boolean, signal: AbortSignal, timeoutMs?: number): Promise<UiActionOutcome>;
|
|
23
|
+
/** Selection or target changes cannot invalidate an action without a target, such as showing the pane. */
|
|
24
|
+
invalidateSession(sessionId: string): void;
|
|
25
|
+
disposeSession(sessionId: string): void;
|
|
26
|
+
dispose(): void;
|
|
27
|
+
}
|
|
28
|
+
export {};
|