返回 CodeWhale
draft-claim-lock.ts
根目录 / web / lib / draft-claim-lock.ts
1 /**
2 * The exclusive hold on one community-agent draft while it is saved,
3 * posted or discarded.
4 *
5 * The `DraftClaimLock` Durable Object (exported from `worker.ts`, one instance
6 * per draft identity via `idFromName`) runs `applyDraftLock` against its own
7 * storage. A Durable Object handles one event at a time and its input gate
8 * holds other events while a storage call is pending, so the read and write
9 * below cannot interleave with another request's: exactly one claim wins.
10 *
11 * This module has no `cloudflare:workers` import so it runs under vitest and
12 * the Next.js build; `worker.ts` holds the thin class around it.
13 */
14
15 export type DraftLockAction = "post" | "discard" | "generate";
16
17 export interface PostAttempt { at: string; identity: string }
18
19 export type DraftLockRequest =
20 | { op: "post-status" }
21 | { op: "remember-draft"; token: string; revision: string }
22 | { op: "remember-post"; token: string; attempt: PostAttempt }
23 | { op: "forget-post"; token: string }
24 | { op: "claim"; token: string; action: DraftLockAction; leaseMs: number }
25 /**
26 * `holdMs` > 0 keeps refusing other claims for that long after an action
27 * whose decision was recorded, covering the time the KV decision marker
28 * takes to reach other locations. 0 frees the draft at once.
29 */
30 | { op: "release"; token: string; holdMs: number };
31
32 export type DraftLockResponse =
33 | { ok: true; attempt?: PostAttempt; revision?: string }
34 | { ok: false; holder: DraftLockAction };
35
36 /** The subset of `DurableObjectStorage` the lock uses. */
37 export interface DraftLockStorage {
38 get<T>(key: string): Promise<T | undefined>;
39 put<T>(key: string, value: T): Promise<void>;
40 delete(key: string): Promise<boolean>;
41 }
42
43 interface Lease {
44 token: string;
45 action: DraftLockAction;
46 /** Epoch ms. A lease past this no longer holds, so a crashed action cannot wedge the draft. */
47 expiresAt: number;
48 }
49
50 const LEASE_KEY = "lease";
51
52 export async function applyDraftLock(
53 storage: DraftLockStorage,
54 now: number,
55 req: DraftLockRequest
56 ): Promise<DraftLockResponse> {
57 if (req.op === "post-status") {
58 return { ok: true, attempt: await storage.get<PostAttempt>("post-attempt") };
59 }
60 const lease = await storage.get<Lease>(LEASE_KEY);
61 const live = lease && lease.expiresAt > now ? lease : undefined;
62
63 if (req.op === "remember-draft") {
64 if (live?.action !== "generate" || live.token !== req.token) throw new Error("draft generation claim expired");
65 if (!/^[0-9a-f]{64}$/.test(req.revision)) throw new Error("invalid draft revision");
66 await storage.put("draft-revision", req.revision);
67 return { ok: true };
68 }
69 if (req.op === "remember-post" || req.op === "forget-post") {
70 if (!live || live.token !== req.token) throw new Error("post claim expired");
71 if (req.op === "remember-post") {
72 if (!/^[0-9a-f]{64}$/.test(req.attempt.identity) || !Number.isFinite(Date.parse(req.attempt.at))) throw new Error("invalid post receipt");
73 const previous = await storage.get<PostAttempt>("post-attempt");
74 if (previous && previous.identity !== req.attempt.identity) throw new Error("unresolved post has different text or target");
75 await storage.put("post-attempt", previous ?? req.attempt);
76 } else {
77 await storage.delete("post-attempt");
78 }
79 return { ok: true };
80 }
81 if (req.op === "claim") {
82 if (live && live.token !== req.token) return { ok: false, holder: live.action };
83 const revision = req.action === "generate" ? undefined : await storage.get<string>("draft-revision");
84 await storage.put<Lease>(LEASE_KEY, {
85 token: req.token,
86 action: req.action,
87 expiresAt: now + Math.max(0, req.leaseMs),
88 });
89 return revision ? { ok: true, revision } : { ok: true };
90 }
91
92 // Release: only the holder's own token can release, so a request whose
93 // lease expired and was retaken cannot free the new holder's claim.
94 if (!live || live.token !== req.token) return { ok: true };
95 if (req.holdMs > 0) {
96 await storage.put<Lease>(LEASE_KEY, { ...live, expiresAt: now + req.holdMs });
97 } else {
98 await storage.delete(LEASE_KEY);
99 }
100 return { ok: true };
101 }
102
103 /** The RPC surface of a `DraftClaimLock` stub. */
104 export interface DraftClaimLockStub {
105 act(req: DraftLockRequest): Promise<DraftLockResponse>;
106 }
107
108 /** The `DRAFT_CLAIM_LOCK` Durable Object namespace binding, as the app uses it. */
109 export interface DraftClaimLockNamespace {
110 idFromName(name: string): DraftClaimLockId;
111 get(id: DraftClaimLockId): DraftClaimLockStub;
112 }
113
114 /** Opaque `DurableObjectId`. */
115 export interface DraftClaimLockId {
116 toString(): string;
117 }
118
119 export async function withGenerationLease<T extends { ok?: unknown }>(
120 namespace: DraftClaimLockNamespace,
121 task: string,
122 generate: () => Promise<T>,
123 ): Promise<T | "busy" | "unavailable"> {
124 let lock: DraftClaimLockStub;
125 const token = `generate:${crypto.randomUUID()}`;
126 try {
127 lock = namespace.get(namespace.idFromName(`draft-generation:${task}`));
128 const held = await lock.act({ op: "claim", token, action: "generate", leaseMs: 45 * 60 * 1000 });
129 if (!held.ok) return "busy";
130 } catch {
131 return "unavailable";
132 }
133 let completed = false;
134 try {
135 const result = await generate();
136 completed = result.ok === true;
137 return result;
138 } finally {
139 // A release failure leaves the durable lease in place until its expiry.
140 await lock.act({ op: "release", token, holdMs: completed ? 120_000 : 0 }).catch(() => undefined);
141 }
142 }
143
143 lines TYPESCRIPT