@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,65 @@
1
+ import { MAX_KEY_BYTES, MAX_SCAN_JSON_BYTES, MAX_SCAN_KEYS } from "../domain.js";
2
+ import { connectionErrorCode } from "./connection-service.js";
3
+ import { RedisFrameError } from "./resp.js";
4
+ import { RedisScanCursors, scanReply } from "./scan-cursors.js";
5
+ import { byteIdentity } from "./byte-identity.js";
6
+ /** MATCH filters returned names; COUNT is a Redis work hint, not a hard limit. */
7
+ export const KEY_SCAN_SCOPE = Object.freeze({ command: 'SCAN', traversal: 'current_db_keyspace', match: 'key_names', countHint: 100, countIsLimit: false, fullIterationMayTraverseEntireKeyspace: true });
8
+ /** Exactly one SCAN per explicit action; cursor tokens cannot be replayed or moved. */
9
+ export class RedisKeys {
10
+ connections;
11
+ scans = new RedisScanCursors();
12
+ constructor(connections) {
13
+ this.connections = connections;
14
+ }
15
+ disposeSession(sessionId) { this.scans.disposeSession(sessionId); }
16
+ dispose() { this.scans.dispose(); }
17
+ async scan(sessionId, request, signal) {
18
+ let scan;
19
+ try {
20
+ signal.throwIfAborted();
21
+ this.connections.assertTarget(sessionId, request.target);
22
+ scan = this.scans.begin(sessionId, JSON.stringify([request.target.id, request.target.generation, request.target.db, request.pattern]), request.cursor);
23
+ const current = scan;
24
+ const guard = () => { this.scans.validate(sessionId, current); };
25
+ const reply = await this.connections.read(sessionId, request.target, 'SCAN', [current.cursor, 'MATCH', request.pattern, 'COUNT', String(KEY_SCAN_SCOPE.countHint)], signal, guard);
26
+ const { cursor, values } = scanReply(reply);
27
+ if (values.length > MAX_SCAN_KEYS)
28
+ throw new RedisFrameError('oversize');
29
+ const unique = new Map();
30
+ for (const raw of values) {
31
+ if (!Buffer.isBuffer(raw))
32
+ throw new RedisFrameError('protocol');
33
+ if (raw.length > MAX_KEY_BYTES)
34
+ throw new RedisFrameError('oversize');
35
+ const base64 = raw.toString('base64');
36
+ unique.set(base64, byteIdentity(raw));
37
+ }
38
+ guard();
39
+ signal.throwIfAborted();
40
+ const token = this.scans.advance(sessionId, current, cursor);
41
+ const result = { state: 'page', error: null, keys: [...unique.values()], cursor: token, sampledAt: new Date().toISOString() };
42
+ // Base64/JSON amplification is budgeted as well; never advance after dropping keys.
43
+ if (Buffer.byteLength(JSON.stringify(result)) > MAX_SCAN_JSON_BYTES)
44
+ throw new RedisFrameError('oversize');
45
+ return result;
46
+ }
47
+ catch (error) {
48
+ if (scan !== undefined) {
49
+ // SCAN has no server-side cursor state; only restore if this remains
50
+ // the same connection and no newer scan has replaced this state.
51
+ let restored = false;
52
+ if (signal.aborted) {
53
+ try {
54
+ this.connections.assertTarget(sessionId, request.target);
55
+ restored = this.scans.restore(sessionId, scan, request.cursor);
56
+ }
57
+ catch { /* target changed */ }
58
+ }
59
+ if (!restored)
60
+ this.scans.discard(sessionId, scan);
61
+ }
62
+ return { state: 'failed', error: signal.aborted ? 'cancelled' : connectionErrorCode(error), keys: [], cursor: null, sampledAt: new Date().toISOString() };
63
+ }
64
+ }
65
+ }
@@ -0,0 +1,8 @@
1
+ import { type ListReadRequest, type ListReadResult } from '../domain.js';
2
+ import type { RedisConnections } from './connection-service.js';
3
+ /** Fixed nonnegative LRANGE interval, preserving repeated values and positions. */
4
+ export declare class RedisLists {
5
+ private readonly connections;
6
+ constructor(connections: RedisConnections);
7
+ read(sessionId: string, request: ListReadRequest, signal: AbortSignal, validate?: () => void): Promise<ListReadResult>;
8
+ }
@@ -0,0 +1,61 @@
1
+ import { MAX_SCAN_JSON_BYTES } from "../domain.js";
2
+ import { RedisReadContext } from "./read-context.js";
3
+ import { RedisFrameError } from "./resp.js";
4
+ import { valuePrefix } from "./value-prefix.js";
5
+ const MAX_INTEGER = (1n << 63n) - 1n;
6
+ /** Fixed nonnegative LRANGE interval, preserving repeated values and positions. */
7
+ export class RedisLists {
8
+ connections;
9
+ constructor(connections) {
10
+ this.connections = connections;
11
+ }
12
+ async read(sessionId, request, signal, validate = () => undefined) {
13
+ const context = new RedisReadContext(this.connections, sessionId, request.target, signal, validate);
14
+ const result = (state, error = null, metadata = null) => ({ state, error, metadata, entries: [], offset: request.offset, nextOffset: null, sampledAt: new Date().toISOString() });
15
+ try {
16
+ const key = Buffer.from(request.keyBase64, 'base64'), firstType = await context.type(key);
17
+ if (firstType === 'none')
18
+ return result('missing');
19
+ const firstTtl = await context.ttl(key);
20
+ if (firstTtl === -2n)
21
+ return result('missing');
22
+ if (firstType !== 'list')
23
+ return result('unsupported', null, { type: firstType, ttlMs: String(firstTtl), length: null });
24
+ const length = await context.integer('LLEN', [key]), offset = BigInt(request.offset);
25
+ const wantedEnd = offset + BigInt(request.count) - 1n, end = wantedEnd > MAX_INTEGER ? MAX_INTEGER : wantedEnd;
26
+ const reply = await context.command('LRANGE', [key, String(offset), String(end)]);
27
+ // Later length, type and TTL checks do not change when this page was read.
28
+ const sampledAt = new Date().toISOString();
29
+ if (!Array.isArray(reply) || reply.length > request.count)
30
+ throw new RedisFrameError('protocol');
31
+ const entries = reply.map((raw, index) => {
32
+ if (!Buffer.isBuffer(raw))
33
+ throw new RedisFrameError('protocol');
34
+ return { index: String(offset + BigInt(index)), value: valuePrefix(raw) };
35
+ });
36
+ const secondType = await context.type(key);
37
+ if (secondType === 'none')
38
+ return result('missing');
39
+ if (secondType !== 'list')
40
+ return result('changed');
41
+ const secondLength = await context.integer('LLEN', [key]), ttl = await context.ttl(key);
42
+ if (ttl === -2n)
43
+ return result('missing');
44
+ const available = length > offset ? length - offset : 0n, expected = available < BigInt(request.count) ? available : BigInt(request.count);
45
+ if (length !== secondLength || BigInt(entries.length) !== expected)
46
+ return result('changed');
47
+ const next = offset + BigInt(entries.length);
48
+ const page = { ...result('page', null, { type: 'list', ttlMs: String(ttl), length: String(secondLength) }), entries, nextOffset: entries.length > 0 && next < secondLength ? String(next) : null, sampledAt };
49
+ if (Buffer.byteLength(JSON.stringify(page)) > MAX_SCAN_JSON_BYTES)
50
+ throw new RedisFrameError('oversize');
51
+ return page;
52
+ }
53
+ catch (error) {
54
+ const code = context.error(error);
55
+ return code === 'type-changed' ? result('changed') : result('failed', code);
56
+ }
57
+ finally {
58
+ context.dispose();
59
+ }
60
+ }
61
+ }
@@ -0,0 +1,36 @@
1
+ export interface MatchPreset {
2
+ readonly id: string;
3
+ readonly name: string;
4
+ readonly pattern: string;
5
+ }
6
+ export interface MatchPresetPage {
7
+ readonly presets: readonly MatchPreset[];
8
+ readonly nextCursor: string | null;
9
+ readonly snapshot: false;
10
+ }
11
+ export type MatchPresetErrorCode = 'invalid' | 'conflict' | 'full' | 'cancelled' | 'storage';
12
+ export declare class MatchPresetError extends Error {
13
+ readonly code: MatchPresetErrorCode;
14
+ constructor(code: MatchPresetErrorCode);
15
+ }
16
+ /** Immutable fixed slots; creation uses a non-replacing filesystem link.
17
+ * The profile directory must be trusted: lstat/open cannot stop a hostile local replacement.
18
+ */
19
+ export declare class RedisMatchPresets {
20
+ private readonly directory;
21
+ constructor(profileDirectory: string);
22
+ private path;
23
+ save(input: {
24
+ readonly name: string;
25
+ readonly pattern: string;
26
+ }, signal: AbortSignal): Promise<MatchPreset>;
27
+ get(id: string, signal: AbortSignal): Promise<MatchPreset | null>;
28
+ /** Validate all identities before returning any result, including across page boundaries. */
29
+ private readAll;
30
+ /** A fixed slot is read at most once per traversal; close precedes the final cancellation check. */
31
+ private readSlot;
32
+ /** Each page checks at most 256 fixed slots; concurrent changes are not a snapshot.
33
+ * Cancellation is checked between I/O calls, not during a blocked filesystem operation.
34
+ */
35
+ list(cursor: string | null, signal: AbortSignal): Promise<MatchPresetPage>;
36
+ }
@@ -0,0 +1,201 @@
1
+ /** Profile-scoped immutable MATCH presets. No Redis data, credentials or caller paths are stored. */
2
+ import { createHash, randomUUID } from 'node:crypto';
3
+ import { link, lstat, mkdir, open, unlink } from 'node:fs/promises';
4
+ import { resolve } from 'node:path';
5
+ export class MatchPresetError extends Error {
6
+ code;
7
+ constructor(code) {
8
+ super(`Redis MATCH preset: ${code}`);
9
+ this.code = code;
10
+ }
11
+ }
12
+ const PAGE_SIZE = 10;
13
+ const MAX_FILE_BYTES = 8192;
14
+ const SLOT_COUNT = 256;
15
+ const ID = /^[a-f0-9]{64}$/u;
16
+ function checkId(value) {
17
+ if (typeof value !== 'string' || !ID.test(value))
18
+ throw new MatchPresetError('invalid');
19
+ return value;
20
+ }
21
+ function text(value, max) {
22
+ if (typeof value !== 'string' || value.length > max || Buffer.from(value, 'utf8').toString('utf8') !== value)
23
+ throw new MatchPresetError('invalid');
24
+ return value;
25
+ }
26
+ function nameAt(value) {
27
+ const name = text(value, 80).normalize('NFC');
28
+ if (name.length === 0 || name.length > 80 || name.trim() !== name || /[\u0000-\u001f\u007f/\\]/u.test(name))
29
+ throw new MatchPresetError('invalid');
30
+ return name;
31
+ }
32
+ function parseInput(value) {
33
+ if (typeof value !== 'object' || value === null || Array.isArray(value))
34
+ throw new MatchPresetError('invalid');
35
+ const record = value;
36
+ if (Object.keys(record).some(key => key !== 'name' && key !== 'pattern'))
37
+ throw new MatchPresetError('invalid');
38
+ return { name: nameAt(record.name), pattern: text(record.pattern, 256) };
39
+ }
40
+ function presetId(name) { return createHash('sha256').update(name, 'utf8').digest('hex'); }
41
+ function parseStored(value) {
42
+ if (typeof value !== 'object' || value === null || Array.isArray(value))
43
+ throw new MatchPresetError('storage');
44
+ const record = value;
45
+ if (Object.keys(record).length !== 3 || Object.keys(record).some(key => key !== 'id' && key !== 'name' && key !== 'pattern'))
46
+ throw new MatchPresetError('storage');
47
+ try {
48
+ const id = checkId(record.id), name = nameAt(record.name), pattern = text(record.pattern, 256);
49
+ if (id !== presetId(name) || record.name !== name)
50
+ throw new Error('Invalid preset identity');
51
+ return { id, name, pattern };
52
+ }
53
+ catch {
54
+ throw new MatchPresetError('storage');
55
+ }
56
+ }
57
+ function cancelled(signal) { if (signal.aborted)
58
+ throw new MatchPresetError('cancelled'); }
59
+ function errorCode(error) { return error instanceof Error && 'code' in error && typeof error.code === 'string' ? error.code : undefined; }
60
+ /** Immutable fixed slots; creation uses a non-replacing filesystem link.
61
+ * The profile directory must be trusted: lstat/open cannot stop a hostile local replacement.
62
+ */
63
+ export class RedisMatchPresets {
64
+ directory;
65
+ constructor(profileDirectory) { this.directory = resolve(profileDirectory, 'data', 'dsh-redis', 'match-preset-slots'); }
66
+ path(slot) { return resolve(this.directory, `${String(slot).padStart(3, '0')}.json`); }
67
+ async save(input, signal) {
68
+ const value = parseInput(input), preset = { id: presetId(value.name), ...value };
69
+ const content = JSON.stringify(preset) + '\n', temporary = resolve(this.directory, `.staging-${randomUUID()}.tmp`);
70
+ let created = false;
71
+ cancelled(signal);
72
+ try {
73
+ await mkdir(this.directory, { recursive: true, mode: 0o700 });
74
+ // A complete scan detects existing identities even if a slot was removed externally.
75
+ if (await this.get(preset.id, signal) !== null)
76
+ throw new MatchPresetError('conflict');
77
+ const file = await open(temporary, 'wx', 0o600);
78
+ created = true;
79
+ try {
80
+ await file.writeFile(content, 'utf8');
81
+ }
82
+ finally {
83
+ await file.close();
84
+ }
85
+ cancelled(signal);
86
+ const start = Number.parseInt(preset.id.slice(0, 2), 16);
87
+ for (let offset = 0; offset < SLOT_COUNT; offset++) {
88
+ cancelled(signal);
89
+ const slot = (start + offset) % SLOT_COUNT;
90
+ try {
91
+ await link(temporary, this.path(slot));
92
+ // After link succeeds the preset exists even if cancellation arrives before return.
93
+ return preset;
94
+ }
95
+ catch (error) {
96
+ if (errorCode(error) !== 'EEXIST')
97
+ throw error;
98
+ const existing = await this.readSlot(slot, signal);
99
+ if (existing === null)
100
+ throw new MatchPresetError('storage');
101
+ if (existing.id === preset.id)
102
+ throw new MatchPresetError('conflict');
103
+ }
104
+ }
105
+ throw new MatchPresetError('full');
106
+ }
107
+ catch (error) {
108
+ if (error instanceof MatchPresetError)
109
+ throw error;
110
+ console.warn('[dsh-redis] MATCH preset save failed');
111
+ throw new MatchPresetError('storage');
112
+ }
113
+ finally {
114
+ if (created)
115
+ try {
116
+ await unlink(temporary);
117
+ }
118
+ catch {
119
+ console.warn('[dsh-redis] MATCH preset temporary cleanup failed');
120
+ }
121
+ }
122
+ }
123
+ async get(id, signal) {
124
+ checkId(id);
125
+ const presets = await this.readAll(signal);
126
+ return presets.find(entry => entry.preset.id === id)?.preset ?? null;
127
+ }
128
+ /** Validate all identities before returning any result, including across page boundaries. */
129
+ async readAll(signal) {
130
+ const entries = [], ids = new Set();
131
+ for (let slot = 0; slot < SLOT_COUNT; slot++) {
132
+ const preset = await this.readSlot(slot, signal);
133
+ if (preset === null)
134
+ continue;
135
+ if (ids.has(preset.id))
136
+ throw new MatchPresetError('storage');
137
+ ids.add(preset.id);
138
+ entries.push({ slot, preset });
139
+ }
140
+ cancelled(signal);
141
+ return entries;
142
+ }
143
+ /** A fixed slot is read at most once per traversal; close precedes the final cancellation check. */
144
+ async readSlot(slot, signal) {
145
+ const path = this.path(slot);
146
+ cancelled(signal);
147
+ try {
148
+ if (!(await lstat(path)).isFile())
149
+ throw new MatchPresetError('storage');
150
+ const file = await open(path, 'r');
151
+ let preset;
152
+ try {
153
+ if (!(await file.stat()).isFile())
154
+ throw new MatchPresetError('storage');
155
+ const buffer = Buffer.alloc(MAX_FILE_BYTES + 1);
156
+ let size = 0;
157
+ while (size < buffer.length) {
158
+ cancelled(signal);
159
+ const read = await file.read(buffer, size, buffer.length - size, size);
160
+ if (read.bytesRead === 0)
161
+ break;
162
+ size += read.bytesRead;
163
+ }
164
+ if (size > MAX_FILE_BYTES)
165
+ throw new MatchPresetError('storage');
166
+ cancelled(signal);
167
+ const content = new TextDecoder('utf-8', { fatal: true }).decode(buffer.subarray(0, size));
168
+ preset = parseStored(JSON.parse(content));
169
+ }
170
+ finally {
171
+ await file.close();
172
+ }
173
+ cancelled(signal);
174
+ return preset;
175
+ }
176
+ catch (error) {
177
+ cancelled(signal);
178
+ if (errorCode(error) === 'ENOENT')
179
+ return null;
180
+ if (error instanceof MatchPresetError)
181
+ throw error;
182
+ console.warn('[dsh-redis] MATCH preset read failed');
183
+ throw new MatchPresetError('storage');
184
+ }
185
+ }
186
+ /** Each page checks at most 256 fixed slots; concurrent changes are not a snapshot.
187
+ * Cancellation is checked between I/O calls, not during a blocked filesystem operation.
188
+ */
189
+ async list(cursor, signal) {
190
+ if (cursor !== null && !/^(?:0|[1-9]\d{0,2})$/u.test(cursor))
191
+ throw new MatchPresetError('invalid');
192
+ const slot = cursor === null ? 0 : Number(cursor);
193
+ if (slot >= SLOT_COUNT)
194
+ throw new MatchPresetError('invalid');
195
+ cancelled(signal);
196
+ const entries = (await this.readAll(signal)).filter(entry => entry.slot >= slot).slice(0, PAGE_SIZE);
197
+ const next = entries.length === PAGE_SIZE ? entries[entries.length - 1].slot + 1 : SLOT_COUNT;
198
+ cancelled(signal);
199
+ return { presets: entries.map(entry => entry.preset), nextCursor: next < SLOT_COUNT ? String(next) : null, snapshot: false };
200
+ }
201
+ }
@@ -0,0 +1,32 @@
1
+ import { type SavedConnection } from '../domain.js';
2
+ interface PreparedSnapshots {
3
+ readonly tokens: readonly (string | null)[];
4
+ commit(): void;
5
+ rollback(): void;
6
+ }
7
+ /** Host-only references. A returned token contains no saved connection settings. */
8
+ export declare class RedisProfileSnapshots {
9
+ private readonly snapshots;
10
+ private readonly sessions;
11
+ private readonly pendingByOwner;
12
+ private readonly reservedByOwner;
13
+ private readonly reservations;
14
+ private readonly stagedTokens;
15
+ private reserved;
16
+ private timer;
17
+ private disposed;
18
+ private clone;
19
+ private remove;
20
+ private prune;
21
+ private retire;
22
+ private schedule;
23
+ /** Stage references until the tool result and its budget are committed. */
24
+ prepare(sessionId: string, profiles: readonly SavedConnection[]): PreparedSnapshots;
25
+ /** Reissuing for the same session/profile invalidates its earlier token. */
26
+ issue(sessionId: string, profile: SavedConnection): string | null;
27
+ /** Only trusted Host callers receive a detached copy of the bound profile. */
28
+ resolve(sessionId: string, profileId: string, token: string): SavedConnection | undefined;
29
+ disposeSession(sessionId: string): void;
30
+ dispose(): void;
31
+ }
32
+ export {};
@@ -0,0 +1,187 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { MAX_PROFILES } from "../domain.js";
3
+ import { profileCollectionSchema } from "../typert.shared.js";
4
+ const MAX_SNAPSHOTS = 250;
5
+ const MAX_STAGES = 250;
6
+ const SNAPSHOT_LIFETIME_MS = 5 * 60 * 1000;
7
+ /** Host-only references. A returned token contains no saved connection settings. */
8
+ export class RedisProfileSnapshots {
9
+ snapshots = new Map();
10
+ sessions = new Map();
11
+ pendingByOwner = new WeakMap();
12
+ reservedByOwner = new WeakMap();
13
+ reservations = new Set();
14
+ stagedTokens = new Set();
15
+ reserved = 0;
16
+ timer;
17
+ disposed = false;
18
+ clone(profile) {
19
+ return profileCollectionSchema.parse({ profiles: [profile], selectedId: null }).profiles[0];
20
+ }
21
+ remove(token) {
22
+ const snapshot = this.snapshots.get(token);
23
+ if (snapshot === undefined)
24
+ return;
25
+ this.snapshots.delete(token);
26
+ const session = this.sessions.get(snapshot.sessionId);
27
+ if (session?.get(snapshot.profile.id) === token)
28
+ session.delete(snapshot.profile.id);
29
+ if (session?.size === 0 && (this.pendingByOwner.get(session) ?? 0) === 0)
30
+ this.sessions.delete(snapshot.sessionId);
31
+ }
32
+ prune() {
33
+ const now = performance.now();
34
+ for (const [token, snapshot] of this.snapshots)
35
+ if (snapshot.expiresAt <= now)
36
+ this.remove(token);
37
+ for (const reservation of this.reservations)
38
+ if (reservation.expiresAt <= now)
39
+ this.retire(reservation);
40
+ }
41
+ retire(reservation) {
42
+ if (!reservation.active)
43
+ return;
44
+ reservation.active = false;
45
+ this.reservations.delete(reservation);
46
+ this.reserved -= reservation.count;
47
+ for (const token of reservation.tokens)
48
+ this.stagedTokens.delete(token);
49
+ const owner = reservation.owner;
50
+ const reserved = (this.reservedByOwner.get(owner) ?? 0) - reservation.count;
51
+ if (reserved === 0)
52
+ this.reservedByOwner.delete(owner);
53
+ else
54
+ this.reservedByOwner.set(owner, reserved);
55
+ const remaining = (this.pendingByOwner.get(owner) ?? 1) - 1;
56
+ if (remaining === 0)
57
+ this.pendingByOwner.delete(owner);
58
+ else
59
+ this.pendingByOwner.set(owner, remaining);
60
+ if (remaining === 0 && owner.size === 0 && this.sessions.get(reservation.sessionId) === owner)
61
+ this.sessions.delete(reservation.sessionId);
62
+ }
63
+ schedule() {
64
+ if (this.timer !== undefined)
65
+ clearTimeout(this.timer);
66
+ this.timer = undefined;
67
+ let earliest = Infinity;
68
+ for (const snapshot of this.snapshots.values())
69
+ earliest = Math.min(earliest, snapshot.expiresAt);
70
+ for (const reservation of this.reservations)
71
+ earliest = Math.min(earliest, reservation.expiresAt);
72
+ if (earliest === Infinity)
73
+ return;
74
+ this.timer = setTimeout(() => { this.timer = undefined; this.prune(); this.schedule(); }, Math.max(0, earliest - performance.now()));
75
+ this.timer.unref();
76
+ }
77
+ /** Stage references until the tool result and its budget are committed. */
78
+ prepare(sessionId, profiles) {
79
+ if (this.disposed)
80
+ throw new Error('Redis profile snapshots are disposed.');
81
+ if (sessionId.length === 0 || sessionId.length > 256)
82
+ throw new Error('Invalid Redis session identity.');
83
+ const saved = profileCollectionSchema.parse({ profiles, selectedId: null }).profiles;
84
+ this.prune();
85
+ if (this.reservations.size >= MAX_STAGES) {
86
+ this.schedule();
87
+ return { tokens: saved.map(() => null), commit: () => undefined, rollback: () => undefined };
88
+ }
89
+ let session = this.sessions.get(sessionId);
90
+ if (session === undefined) {
91
+ session = new Map();
92
+ this.sessions.set(sessionId, session);
93
+ }
94
+ const owner = session, issued = new Set();
95
+ let additions = 0;
96
+ const pending = saved.map(profile => {
97
+ const previous = owner.get(profile.id);
98
+ if (previous === undefined && (this.snapshots.size + this.reserved + additions >= MAX_SNAPSHOTS || owner.size + (this.reservedByOwner.get(owner) ?? 0) + additions >= MAX_PROFILES))
99
+ return { profile, previous, token: null };
100
+ if (previous === undefined)
101
+ additions++;
102
+ let token;
103
+ do {
104
+ token = randomUUID();
105
+ } while (this.snapshots.has(token) || this.stagedTokens.has(token) || issued.has(token));
106
+ issued.add(token);
107
+ return { profile, previous, token };
108
+ });
109
+ this.pendingByOwner.set(owner, (this.pendingByOwner.get(owner) ?? 0) + 1);
110
+ this.reservedByOwner.set(owner, (this.reservedByOwner.get(owner) ?? 0) + additions);
111
+ this.reserved += additions;
112
+ for (const token of issued)
113
+ this.stagedTokens.add(token);
114
+ const reservation = { sessionId, owner, count: additions, tokens: [...issued], expiresAt: performance.now() + SNAPSHOT_LIFETIME_MS, active: true };
115
+ this.reservations.add(reservation);
116
+ this.schedule();
117
+ let finished = false;
118
+ return {
119
+ tokens: pending.map(value => value.token),
120
+ commit: () => {
121
+ if (finished || !reservation.active || this.disposed || this.sessions.get(sessionId) !== owner)
122
+ throw new Error('Redis profile snapshot is stale.');
123
+ this.prune();
124
+ if (!reservation.active || this.sessions.get(sessionId) !== owner || pending.some(value => value.token !== null && owner.get(value.profile.id) !== value.previous))
125
+ throw new Error('Redis profile snapshot is stale.');
126
+ for (const { profile, previous, token } of pending) {
127
+ if (token === null)
128
+ continue;
129
+ if (previous !== undefined)
130
+ this.snapshots.delete(previous);
131
+ this.snapshots.set(token, { sessionId, profile, expiresAt: performance.now() + SNAPSHOT_LIFETIME_MS });
132
+ owner.set(profile.id, token);
133
+ }
134
+ finished = true;
135
+ this.retire(reservation);
136
+ this.schedule();
137
+ },
138
+ rollback: () => {
139
+ if (finished)
140
+ return;
141
+ finished = true;
142
+ this.retire(reservation);
143
+ this.schedule();
144
+ },
145
+ };
146
+ }
147
+ /** Reissuing for the same session/profile invalidates its earlier token. */
148
+ issue(sessionId, profile) {
149
+ const prepared = this.prepare(sessionId, [profile]);
150
+ try {
151
+ prepared.commit();
152
+ return prepared.tokens[0] ?? null;
153
+ }
154
+ catch (error) {
155
+ prepared.rollback();
156
+ throw error;
157
+ }
158
+ }
159
+ /** Only trusted Host callers receive a detached copy of the bound profile. */
160
+ resolve(sessionId, profileId, token) {
161
+ this.prune();
162
+ this.schedule();
163
+ const snapshot = this.snapshots.get(token);
164
+ if (snapshot === undefined || snapshot.sessionId !== sessionId || snapshot.profile.id !== profileId)
165
+ return undefined;
166
+ return this.clone(snapshot.profile);
167
+ }
168
+ disposeSession(sessionId) {
169
+ for (const reservation of this.reservations)
170
+ if (reservation.sessionId === sessionId)
171
+ this.retire(reservation);
172
+ for (const token of this.sessions.get(sessionId)?.values() ?? [])
173
+ this.remove(token);
174
+ this.sessions.delete(sessionId);
175
+ this.schedule();
176
+ }
177
+ dispose() {
178
+ this.disposed = true;
179
+ for (const reservation of this.reservations)
180
+ this.retire(reservation);
181
+ this.snapshots.clear();
182
+ this.sessions.clear();
183
+ if (this.timer !== undefined)
184
+ clearTimeout(this.timer);
185
+ this.timer = undefined;
186
+ }
187
+ }
@@ -0,0 +1,15 @@
1
+ import { type ProfileCollection, type ProfileId, type SavedConnection, type SaveProfileRequest } from '../domain.js';
2
+ export declare class RedisProfiles {
3
+ private readonly file;
4
+ private readonly queueKey;
5
+ constructor(profileDirectory: string);
6
+ /** Serialize cooperating instances using the same normalized file path. */
7
+ private queue;
8
+ private read;
9
+ private write;
10
+ list(signal: AbortSignal): Promise<ProfileCollection>;
11
+ /** Caller prepares its candidate first. No asynchronous work is allowed in commit. */
12
+ withVerifiedProfile(expected: SavedConnection, signal: AbortSignal, commit: () => undefined): Promise<boolean>;
13
+ save(request: SaveProfileRequest, signal: AbortSignal): Promise<ProfileCollection>;
14
+ remove(request: ProfileId, signal: AbortSignal): Promise<ProfileCollection>;
15
+ }