Personal Telegram developer console for GitHub
feat: add durable workspace store
davoodmehraban89 committed
Oct 3, 2026 at 12:33 UTC
e1d07ed92157f5063ebaf410ea768b69f6b96dd2
1 file changed
+352
src/durable/workspace-store.js
new
+352
@@ -0,0 +1,352 @@
1
+const json = (payload, status = 200) => Response.json(payload, { status });
2
+const HANDLE_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-';
3
+const WORKSPACE_TTL_MS = 30 * 60_000;
4
+const REF_TTL_MS = 15 * 60_000;
5
+const COMMITTED_RETENTION_MS = 24 * 60 * 60_000;
6
+
7
+function randomHandle(length) {
8
+ const bytes = new Uint8Array(length);
9
+ crypto.getRandomValues(bytes);
10
+ let out = '';
11
+ for (const byte of bytes) out += HANDLE_ALPHABET[byte & 63];
12
+ return out;
13
+}
14
+
15
+function finiteNow(value) {
16
+ const parsed = Number(value);
17
+ return Number.isFinite(parsed) ? parsed : Date.now();
18
+}
19
+
20
+function positiveTtl(value, fallback) {
21
+ const parsed = Number(value);
22
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
23
+}
24
+
25
+function expired(record, now) {
26
+ return Boolean(record && Number.isFinite(Number(record.expiresAt)) && Number(record.expiresAt) < now);
27
+}
28
+
29
+export class WorkspaceStore {
30
+ constructor(state) {
31
+ this.state = state;
32
+ }
33
+
34
+ async fetch(request) {
35
+ const url = new URL(request.url);
36
+ if (request.method !== 'POST') return new Response('Not Found', { status: 404 });
37
+
38
+ let payload;
39
+ try { payload = await request.json(); } catch { return json({ error: 'Invalid workspace payload' }, 400); }
40
+ const now = finiteNow(payload?.now);
41
+
42
+ try {
43
+ switch (url.pathname) {
44
+ case '/refs/create': return json({ result: await this.#createRefs(payload, now) });
45
+ case '/refs/get': return json({ result: await this.#getExpiring(`ref:${String(payload.refId || '')}`, now) });
46
+ case '/workspace/create': return json({ result: await this.#createWorkspace(payload, now) });
47
+ case '/workspace/get': return json({ result: await this.#getExpiring(`ws:${String(payload.workspaceId || '')}`, now) });
48
+ case '/workspace/draft': return json({ result: await this.#updateDraft(payload, now) });
49
+ case '/workspace/message': return json({ result: await this.#setCommitMessage(payload, now) });
50
+ case '/workspace/cancel': return json({ result: await this.#cancelWorkspace(payload) });
51
+ case '/pending/set': return json({ result: await this.#setPending(payload, now) });
52
+ case '/pending/get': return json({ result: await this.#getPending(now) });
53
+ case '/pending/consume': return json({ result: await this.#consumePending(payload, now) });
54
+ case '/intent/seal': return json({ result: await this.#sealIntent(payload, now) });
55
+ case '/intent/get': return json({ result: await this.#getExpiring(`intent:${String(payload.intentId || '')}`, now) });
56
+ case '/intent/begin': return json({ result: await this.#beginCommit(payload, now) });
57
+ case '/intent/candidate': return json({ result: await this.#setCandidate(payload, now) });
58
+ case '/intent/complete': return json({ result: await this.#completeCommit(payload, now) });
59
+ case '/intent/stale': return json({ result: await this.#markStale(payload, now) });
60
+ default: return new Response('Not Found', { status: 404 });
61
+ }
62
+ } catch (error) {
63
+ return json({ error: String(error?.message || 'Workspace store operation failed') }, 400);
64
+ }
65
+ }
66
+
67
+ async #schedule(expiresAt) {
68
+ const expiry = Number(expiresAt);
69
+ if (!Number.isFinite(expiry)) return;
70
+ const current = Number(await this.state.storage.get('__next_alarm'));
71
+ if (!Number.isFinite(current) || expiry < current) {
72
+ await this.state.storage.put('__next_alarm', expiry);
73
+ await this.state.storage.setAlarm(expiry);
74
+ }
75
+ }
76
+
77
+ async #getExpiring(key, now) {
78
+ if (!key || key.endsWith(':')) return null;
79
+ const record = await this.state.storage.get(key);
80
+ if (!record) return null;
81
+ if (expired(record, now)) {
82
+ await this.state.storage.delete(key);
83
+ return null;
84
+ }
85
+ return record;
86
+ }
87
+
88
+ async #createRefs(payload, now) {
89
+ if (!Array.isArray(payload.refs)) throw new Error('Navigation refs are required');
90
+ const ttlMs = positiveTtl(payload.ttlMs, REF_TTL_MS);
91
+ const expiresAt = now + ttlMs;
92
+ const output = [];
93
+ for (const source of payload.refs) {
94
+ const refId = randomHandle(10);
95
+ const record = {
96
+ repoId: source?.repoId,
97
+ path: String(source?.path || ''),
98
+ type: source?.type === 'dir' ? 'dir' : 'file',
99
+ sha: String(source?.sha || ''),
100
+ expiresAt
101
+ };
102
+ await this.state.storage.put(`ref:${refId}`, record);
103
+ output.push({ refId });
104
+ }
105
+ await this.#schedule(expiresAt);
106
+ return output;
107
+ }
108
+
109
+ async #createWorkspace(payload, now) {
110
+ const id = randomHandle(10);
111
+ const expiresAt = Number.isFinite(Number(payload.expiresAt)) ? Number(payload.expiresAt) : now + WORKSPACE_TTL_MS;
112
+ if (expiresAt <= now) throw new Error('Workspace expiry must be in the future');
113
+ const workspace = {
114
+ id,
115
+ repoId: payload.repoId,
116
+ repoFullName: String(payload.repoFullName || ''),
117
+ baseBranch: String(payload.baseBranch || ''),
118
+ baseHeadSha: String(payload.baseHeadSha || ''),
119
+ baseTreeSha: String(payload.baseTreeSha || ''),
120
+ path: String(payload.path || ''),
121
+ blobSha: String(payload.blobSha || ''),
122
+ originalText: String(payload.originalText ?? ''),
123
+ originalDigest: String(payload.originalDigest || ''),
124
+ draftText: String(payload.originalText ?? ''),
125
+ draftDigest: String(payload.originalDigest || ''),
126
+ commitMessage: '',
127
+ commitMessageDigest: '',
128
+ currentIntentId: null,
129
+ state: 'DRAFT',
130
+ createdAt: now,
131
+ updatedAt: now,
132
+ expiresAt
133
+ };
134
+ await this.state.storage.put(`ws:${id}`, workspace);
135
+ await this.#schedule(expiresAt);
136
+ return workspace;
137
+ }
138
+
139
+ async #requireWorkspace(workspaceId, now) {
140
+ const workspace = await this.#getExpiring(`ws:${String(workspaceId || '')}`, now);
141
+ if (!workspace) throw new Error('Workspace not found or expired');
142
+ return workspace;
143
+ }
144
+
145
+ async #updateDraft(payload, now) {
146
+ const workspace = await this.#requireWorkspace(payload.workspaceId, now);
147
+ const digest = String(payload.digest || '');
148
+ if (!digest) throw new Error('Draft digest is required');
149
+ const changed = digest !== workspace.draftDigest;
150
+ const updated = {
151
+ ...workspace,
152
+ draftText: String(payload.text ?? ''),
153
+ draftDigest: digest,
154
+ updatedAt: now,
155
+ ...(changed ? { currentIntentId: null, state: 'DRAFT' } : {})
156
+ };
157
+ await this.state.storage.put(`ws:${workspace.id}`, updated);
158
+ return updated;
159
+ }
160
+
161
+ async #setCommitMessage(payload, now) {
162
+ const workspace = await this.#requireWorkspace(payload.workspaceId, now);
163
+ const digest = String(payload.digest || '');
164
+ if (!digest) throw new Error('Commit message digest is required');
165
+ const changed = digest !== workspace.commitMessageDigest;
166
+ const updated = {
167
+ ...workspace,
168
+ commitMessage: String(payload.message || ''),
169
+ commitMessageDigest: digest,
170
+ updatedAt: now,
171
+ ...(changed ? { currentIntentId: null, state: 'DRAFT' } : {})
172
+ };
173
+ await this.state.storage.put(`ws:${workspace.id}`, updated);
174
+ return updated;
175
+ }
176
+
177
+ async #setPending(payload, now) {
178
+ const workspace = await this.#requireWorkspace(payload.workspaceId, now);
179
+ const mode = String(payload.mode || '');
180
+ if (!['draft', 'commit_message'].includes(mode)) throw new Error('Pending input mode is invalid');
181
+ const pending = { workspaceId: workspace.id, mode, expiresAt: workspace.expiresAt };
182
+ await this.state.storage.put('pending', pending);
183
+ await this.#schedule(pending.expiresAt);
184
+ return pending;
185
+ }
186
+
187
+ async #getPending(now) {
188
+ const pending = await this.state.storage.get('pending');
189
+ if (!pending) return null;
190
+ if (expired(pending, now)) {
191
+ await this.state.storage.delete('pending');
192
+ return null;
193
+ }
194
+ const workspace = await this.#getExpiring(`ws:${pending.workspaceId}`, now);
195
+ if (!workspace) {
196
+ await this.state.storage.delete('pending');
197
+ return null;
198
+ }
199
+ return { workspaceId: pending.workspaceId, mode: pending.mode };
200
+ }
201
+
202
+ async #consumePending(payload, now) {
203
+ return this.state.storage.transaction(async txn => {
204
+ const pending = await txn.get('pending');
205
+ if (!pending || expired(pending, now)) {
206
+ if (pending) await txn.delete('pending');
207
+ return false;
208
+ }
209
+ if (pending.workspaceId !== String(payload.workspaceId || '') || pending.mode !== String(payload.mode || '')) return false;
210
+ await txn.delete('pending');
211
+ return true;
212
+ });
213
+ }
214
+
215
+ async #sealIntent(payload, now) {
216
+ const workspace = await this.#requireWorkspace(payload.workspaceId, now);
217
+ const proposed = payload.intent && typeof payload.intent === 'object' ? payload.intent : null;
218
+ if (!proposed?.intentDigest) throw new Error('Commit intent digest is required');
219
+
220
+ if (workspace.currentIntentId) {
221
+ const existing = await this.#getExpiring(`intent:${workspace.currentIntentId}`, now);
222
+ if (existing?.intentDigest === proposed.intentDigest) return existing;
223
+ }
224
+
225
+ const id = randomHandle(8);
226
+ const intent = {
227
+ ...proposed,
228
+ id,
229
+ workspaceId: workspace.id,
230
+ state: 'READY',
231
+ candidateCommitSha: null,
232
+ commitSha: null,
233
+ branch: null,
234
+ createdAt: now,
235
+ updatedAt: now,
236
+ expiresAt: workspace.expiresAt
237
+ };
238
+ await this.state.storage.put(`intent:${id}`, intent);
239
+ await this.state.storage.put(`ws:${workspace.id}`, {
240
+ ...workspace,
241
+ currentIntentId: id,
242
+ state: 'READY',
243
+ updatedAt: now
244
+ });
245
+ await this.#schedule(intent.expiresAt);
246
+ return intent;
247
+ }
248
+
249
+ async #beginCommit(payload, now) {
250
+ const key = `intent:${String(payload.intentId || '')}`;
251
+ return this.state.storage.transaction(async txn => {
252
+ const intent = await txn.get(key);
253
+ if (!intent || expired(intent, now)) throw new Error('Commit intent not found or expired');
254
+ if (intent.state === 'COMMITTED') return { disposition: 'committed', intent };
255
+ if (intent.state === 'COMMITTING') return { disposition: 'resume', intent };
256
+ if (intent.state !== 'READY') throw new Error(`Commit intent is ${intent.state || 'invalid'}`);
257
+ const updated = { ...intent, state: 'COMMITTING', updatedAt: now };
258
+ await txn.put(key, updated);
259
+ return { disposition: 'start', intent: updated };
260
+ });
261
+ }
262
+
263
+ async #setCandidate(payload, now) {
264
+ const key = `intent:${String(payload.intentId || '')}`;
265
+ return this.state.storage.transaction(async txn => {
266
+ const intent = await txn.get(key);
267
+ if (!intent || expired(intent, now)) throw new Error('Commit intent not found or expired');
268
+ if (intent.state === 'COMMITTED') return intent;
269
+ if (intent.state !== 'COMMITTING') throw new Error('Commit intent is not committing');
270
+ const updated = { ...intent, candidateCommitSha: String(payload.commitSha || ''), updatedAt: now };
271
+ await txn.put(key, updated);
272
+ return updated;
273
+ });
274
+ }
275
+
276
+ async #completeCommit(payload, now) {
277
+ const key = `intent:${String(payload.intentId || '')}`;
278
+ const retainedUntil = now + COMMITTED_RETENTION_MS;
279
+ const completed = await this.state.storage.transaction(async txn => {
280
+ const intent = await txn.get(key);
281
+ if (!intent) throw new Error('Commit intent not found');
282
+ if (intent.state === 'COMMITTED') return intent;
283
+ if (intent.state !== 'COMMITTING') throw new Error('Commit intent is not committing');
284
+ const updated = {
285
+ ...intent,
286
+ state: 'COMMITTED',
287
+ commitSha: String(payload.commitSha || ''),
288
+ branch: String(payload.branch || ''),
289
+ updatedAt: now,
290
+ expiresAt: retainedUntil
291
+ };
292
+ await txn.put(key, updated);
293
+ const workspaceKey = `ws:${intent.workspaceId}`;
294
+ const workspace = await txn.get(workspaceKey);
295
+ if (workspace) {
296
+ await txn.put(workspaceKey, {
297
+ ...workspace,
298
+ state: 'COMMITTED',
299
+ currentIntentId: intent.id,
300
+ commitSha: updated.commitSha,
301
+ branch: updated.branch,
302
+ updatedAt: now,
303
+ expiresAt: retainedUntil
304
+ });
305
+ }
306
+ return updated;
307
+ });
308
+ await this.#schedule(retainedUntil);
309
+ return completed;
310
+ }
311
+
312
+ async #markStale(payload, now) {
313
+ const key = `intent:${String(payload.intentId || '')}`;
314
+ return this.state.storage.transaction(async txn => {
315
+ const intent = await txn.get(key);
316
+ if (!intent) throw new Error('Commit intent not found');
317
+ if (intent.state === 'COMMITTED') return intent;
318
+ const updated = { ...intent, state: 'STALE', staleReason: String(payload.reason || 'stale'), updatedAt: now };
319
+ await txn.put(key, updated);
320
+ return updated;
321
+ });
322
+ }
323
+
324
+ async #cancelWorkspace(payload) {
325
+ const workspaceId = String(payload.workspaceId || '');
326
+ if (!workspaceId) throw new Error('Workspace ID is required');
327
+ await this.state.storage.transaction(async txn => {
328
+ await txn.delete(`ws:${workspaceId}`);
329
+ const pending = await txn.get('pending');
330
+ if (pending?.workspaceId === workspaceId) await txn.delete('pending');
331
+ });
332
+ return { cancelled: true };
333
+ }
334
+
335
+ async alarm() {
336
+ const now = Date.now();
337
+ const entries = await this.state.storage.list();
338
+ let next = Infinity;
339
+ for (const [key, value] of entries) {
340
+ if (key === '__next_alarm') continue;
341
+ const expiry = Number(value?.expiresAt);
342
+ if (!Number.isFinite(expiry)) continue;
343
+ if (expiry <= now) await this.state.storage.delete(key);
344
+ else next = Math.min(next, expiry);
345
+ }
346
+ await this.state.storage.delete('__next_alarm');
347
+ if (Number.isFinite(next)) {
348
+ await this.state.storage.put('__next_alarm', next);
349
+ await this.state.storage.setAlarm(next);
350
+ }
351
+ }
352
+}