@comforge/github 0.1.0 → 0.3.0
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/README.md +55 -4
- package/dist/errors.d.ts +1 -1
- package/dist/errors.js +4 -0
- package/dist/evidence.d.ts +56 -2
- package/dist/evidence.js +109 -9
- package/dist/index.d.ts +3 -1
- package/dist/index.js +2 -0
- package/dist/operations.d.ts +147 -0
- package/dist/operations.js +328 -0
- package/dist/request.d.ts +49 -0
- package/dist/request.js +88 -0
- package/dist/transport.js +7 -1
- package/dist/writer.d.ts +183 -0
- package/dist/writer.js +877 -0
- package/llms.txt +5 -3
- package/package.json +2 -2
package/dist/writer.js
ADDED
|
@@ -0,0 +1,877 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { GitHubAdapterError } from "./errors.js";
|
|
3
|
+
import { bodyDigest, carriesMarker, correlationMarker, describe, markedBody, WRITE_CAPABILITIES, } from "./operations.js";
|
|
4
|
+
import { sendWrite } from "./request.js";
|
|
5
|
+
import { createFetchTransport, DEFAULTS } from "./transport.js";
|
|
6
|
+
export const DEFAULT_WRITER_LIMITS = {
|
|
7
|
+
reconcileMaxPages: 5,
|
|
8
|
+
leaseMs: 120_000,
|
|
9
|
+
maxAuthorizationTtlMs: 15 * 60_000,
|
|
10
|
+
searchSkewMs: 10 * 60_000,
|
|
11
|
+
};
|
|
12
|
+
const NAME = /^[A-Za-z0-9_.-]{1,100}$/;
|
|
13
|
+
const NAMESPACE = /^[a-z0-9][a-z0-9-]{0,39}$/;
|
|
14
|
+
const LOGIN = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})(?:\[bot\])?$/;
|
|
15
|
+
// biome-ignore lint/suspicious/noControlCharactersInRegex: refusing control characters
|
|
16
|
+
const CONTROL = /[\u0000-\u001f\u007f]/;
|
|
17
|
+
const CREATES = new Set([
|
|
18
|
+
"issue.create",
|
|
19
|
+
"issue.comment",
|
|
20
|
+
"pull.review",
|
|
21
|
+
"pull.create",
|
|
22
|
+
]);
|
|
23
|
+
const User = z.object({ login: z.string() }).nullable().optional();
|
|
24
|
+
const IssueRead = z.object({
|
|
25
|
+
number: z.number().int().positive(),
|
|
26
|
+
title: z.string(),
|
|
27
|
+
body: z.string().nullable().optional(),
|
|
28
|
+
state: z.string(),
|
|
29
|
+
state_reason: z.string().nullable().optional(),
|
|
30
|
+
locked: z.boolean().optional(),
|
|
31
|
+
labels: z.array(z.union([z.string(), z.object({ name: z.string() })])).optional(),
|
|
32
|
+
assignees: z
|
|
33
|
+
.array(z.object({ login: z.string() }))
|
|
34
|
+
.nullable()
|
|
35
|
+
.optional(),
|
|
36
|
+
pull_request: z.unknown().optional(),
|
|
37
|
+
html_url: z.string(),
|
|
38
|
+
updated_at: z.string(),
|
|
39
|
+
user: User,
|
|
40
|
+
});
|
|
41
|
+
const CommentRead = z.object({
|
|
42
|
+
id: z.number().int().positive(),
|
|
43
|
+
body: z.string().nullable().optional(),
|
|
44
|
+
html_url: z.string(),
|
|
45
|
+
issue_url: z.string(),
|
|
46
|
+
updated_at: z.string(),
|
|
47
|
+
user: User,
|
|
48
|
+
});
|
|
49
|
+
const Ref = z.object({
|
|
50
|
+
ref: z.string(),
|
|
51
|
+
sha: z.string(),
|
|
52
|
+
repo: z.object({ full_name: z.string() }).nullable().optional(),
|
|
53
|
+
});
|
|
54
|
+
const PullRead = z.object({
|
|
55
|
+
number: z.number().int().positive(),
|
|
56
|
+
title: z.string(),
|
|
57
|
+
body: z.string().nullable().optional(),
|
|
58
|
+
state: z.string(),
|
|
59
|
+
draft: z.boolean().optional(),
|
|
60
|
+
merged_at: z.string().nullable().optional(),
|
|
61
|
+
html_url: z.string(),
|
|
62
|
+
head: Ref,
|
|
63
|
+
base: Ref,
|
|
64
|
+
user: User,
|
|
65
|
+
});
|
|
66
|
+
const ReviewRead = z.object({
|
|
67
|
+
id: z.number().int().positive(),
|
|
68
|
+
commit_id: z.string().nullable().optional(),
|
|
69
|
+
state: z.string(),
|
|
70
|
+
body: z.string().nullable().optional(),
|
|
71
|
+
user: User,
|
|
72
|
+
});
|
|
73
|
+
/** The fields a reconciliation search needs from any listed issue, comment, review or pull request. */
|
|
74
|
+
const Listed = z.object({
|
|
75
|
+
id: z.number().optional(),
|
|
76
|
+
number: z.number().optional(),
|
|
77
|
+
body: z.string().nullable().optional(),
|
|
78
|
+
user: User,
|
|
79
|
+
});
|
|
80
|
+
const GitRefRead = z.object({
|
|
81
|
+
ref: z.string(),
|
|
82
|
+
object: z.object({ sha: z.string(), type: z.string() }),
|
|
83
|
+
});
|
|
84
|
+
const REVIEW_STATE = {
|
|
85
|
+
COMMENT: "COMMENTED",
|
|
86
|
+
APPROVE: "APPROVED",
|
|
87
|
+
REQUEST_CHANGES: "CHANGES_REQUESTED",
|
|
88
|
+
};
|
|
89
|
+
function fail(code, message, detail = {}) {
|
|
90
|
+
throw new GitHubAdapterError(code, message, detail);
|
|
91
|
+
}
|
|
92
|
+
function parse(schema, body, what) {
|
|
93
|
+
const parsed = schema.safeParse(body);
|
|
94
|
+
if (!parsed.success)
|
|
95
|
+
fail("malformed-response", `Unexpected GitHub response for ${what}`);
|
|
96
|
+
return parsed.data;
|
|
97
|
+
}
|
|
98
|
+
const labelNames = (labels) => (labels ?? []).map((l) => (typeof l === "string" ? l : l.name));
|
|
99
|
+
const sameSet = (a, b) => a.length === b.length && [...a].sort().join("\n") === [...b].sort().join("\n");
|
|
100
|
+
export function createGitHubWriter(options) {
|
|
101
|
+
const { owner, name } = options.repository ?? {};
|
|
102
|
+
if (!NAME.test(owner ?? "") || !NAME.test(name ?? ""))
|
|
103
|
+
fail("invalid-input", "Invalid repository owner or name");
|
|
104
|
+
const repository = `${owner}/${name}`;
|
|
105
|
+
const root = `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}`;
|
|
106
|
+
if (!Array.isArray(options.capabilities) || options.capabilities.length === 0)
|
|
107
|
+
fail("invalid-input", "A writer needs at least one explicit capability");
|
|
108
|
+
for (const capability of options.capabilities)
|
|
109
|
+
if (!WRITE_CAPABILITIES.includes(capability))
|
|
110
|
+
fail("invalid-input", `Unknown capability: ${String(capability)}`);
|
|
111
|
+
const capabilities = Object.freeze([...new Set(options.capabilities)]);
|
|
112
|
+
if (typeof options.authorize !== "function")
|
|
113
|
+
fail("invalid-input", "authorize is required");
|
|
114
|
+
if (typeof options.clock !== "function")
|
|
115
|
+
fail("invalid-input", "clock is required");
|
|
116
|
+
const ledger = options.ledger;
|
|
117
|
+
if (!ledger ||
|
|
118
|
+
typeof ledger.get !== "function" ||
|
|
119
|
+
typeof ledger.create !== "function" ||
|
|
120
|
+
typeof ledger.replace !== "function")
|
|
121
|
+
fail("invalid-input", "A durable operation ledger is required");
|
|
122
|
+
if (options.expectedAuthor !== undefined && !LOGIN.test(options.expectedAuthor))
|
|
123
|
+
fail("invalid-input", "Invalid expectedAuthor");
|
|
124
|
+
const namespace = options.markers === false ? null : (options.markers?.namespace ?? "comforge");
|
|
125
|
+
if (namespace !== null && !NAMESPACE.test(namespace))
|
|
126
|
+
fail("invalid-input", "Invalid marker namespace");
|
|
127
|
+
const limits = { ...DEFAULT_WRITER_LIMITS, ...options.limits };
|
|
128
|
+
if (!(Number.isSafeInteger(limits.reconcileMaxPages) &&
|
|
129
|
+
limits.reconcileMaxPages >= 1 &&
|
|
130
|
+
limits.reconcileMaxPages <= 50) ||
|
|
131
|
+
!(limits.leaseMs > 0 && limits.maxAuthorizationTtlMs > 0 && limits.searchSkewMs >= 0))
|
|
132
|
+
fail("invalid-input", "Invalid writer limits");
|
|
133
|
+
const apiOrigin = options.apiOrigin ?? DEFAULTS.apiOrigin;
|
|
134
|
+
const fetchImpl = (...args) => (options.fetchImpl ?? globalThis.fetch)(...args);
|
|
135
|
+
const token = async () => (typeof options.token === "function" ? options.token() : options.token);
|
|
136
|
+
const transport = createFetchTransport({
|
|
137
|
+
token,
|
|
138
|
+
fetchImpl: fetchImpl,
|
|
139
|
+
apiOrigin,
|
|
140
|
+
...(options.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),
|
|
141
|
+
...(options.maxBodyBytes !== undefined ? { maxBodyBytes: options.maxBodyBytes } : {}),
|
|
142
|
+
...(options.userAgent !== undefined ? { userAgent: options.userAgent } : {}),
|
|
143
|
+
});
|
|
144
|
+
const sendOptions = {
|
|
145
|
+
origin: new URL(apiOrigin).origin,
|
|
146
|
+
base: apiOrigin.replace(/\/+$/, ""),
|
|
147
|
+
token,
|
|
148
|
+
fetchImpl: fetchImpl,
|
|
149
|
+
timeoutMs: options.timeoutMs ?? DEFAULTS.timeoutMs,
|
|
150
|
+
maxBodyBytes: options.maxBodyBytes ?? DEFAULTS.maxBodyBytes,
|
|
151
|
+
...(options.userAgent !== undefined ? { userAgent: options.userAgent } : {}),
|
|
152
|
+
};
|
|
153
|
+
const now = () => {
|
|
154
|
+
const t = options.clock();
|
|
155
|
+
if (!Number.isFinite(t))
|
|
156
|
+
fail("invalid-input", "The clock returned no time");
|
|
157
|
+
return t;
|
|
158
|
+
};
|
|
159
|
+
const read = (segments, query) => transport.get(`${root}/${segments.map((s) => encodeURIComponent(String(s))).join("/")}`, query);
|
|
160
|
+
const readRef = (branch) => transport.get(`${root}/git/ref/heads/${branch.split("/").map(encodeURIComponent).join("/")}`);
|
|
161
|
+
// --- ledger -------------------------------------------------------------------------------
|
|
162
|
+
async function store(call) {
|
|
163
|
+
try {
|
|
164
|
+
return await call();
|
|
165
|
+
}
|
|
166
|
+
catch (error) {
|
|
167
|
+
if (error instanceof GitHubAdapterError)
|
|
168
|
+
throw error;
|
|
169
|
+
fail("ledger-failure", "The operation ledger failed");
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
/** Compare-and-swap; `false` means another caller changed the record first. */
|
|
173
|
+
async function advance(record, changes) {
|
|
174
|
+
const next = {
|
|
175
|
+
...record,
|
|
176
|
+
...changes,
|
|
177
|
+
version: record.version + 1,
|
|
178
|
+
changedAt: now(),
|
|
179
|
+
};
|
|
180
|
+
return (await store(() => ledger.replace(record.operationId, record.version, next)))
|
|
181
|
+
? next
|
|
182
|
+
: null;
|
|
183
|
+
}
|
|
184
|
+
/** As `advance`, after a send: a ledger failure must not hide what happened on GitHub. */
|
|
185
|
+
async function settle(record, changes) {
|
|
186
|
+
try {
|
|
187
|
+
return (await advance(record, changes)) !== null;
|
|
188
|
+
}
|
|
189
|
+
catch {
|
|
190
|
+
return false;
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
function storedOutcome(record, replayed) {
|
|
194
|
+
if (!record.outcome)
|
|
195
|
+
fail("conflict", "The operation has no recorded outcome", { reason: record.state });
|
|
196
|
+
return { ...record.outcome, replayed, recorded: true };
|
|
197
|
+
}
|
|
198
|
+
async function refuse(record, error, retryable) {
|
|
199
|
+
const retryAfter = error.detail.retryAfterSeconds;
|
|
200
|
+
await settle(record, {
|
|
201
|
+
state: "failed",
|
|
202
|
+
leaseUntil: null,
|
|
203
|
+
failure: {
|
|
204
|
+
code: error.code,
|
|
205
|
+
message: error.message,
|
|
206
|
+
...(error.detail.status !== undefined ? { status: error.detail.status } : {}),
|
|
207
|
+
retryable,
|
|
208
|
+
notBefore: typeof retryAfter === "number" ? now() + retryAfter * 1000 : null,
|
|
209
|
+
},
|
|
210
|
+
});
|
|
211
|
+
throw error;
|
|
212
|
+
}
|
|
213
|
+
// --- authorization ------------------------------------------------------------------------
|
|
214
|
+
async function authorize(descriptor) {
|
|
215
|
+
let decision;
|
|
216
|
+
try {
|
|
217
|
+
decision = await options.authorize(descriptor);
|
|
218
|
+
}
|
|
219
|
+
catch {
|
|
220
|
+
fail("authorization-denied", "The authorization callback failed; nothing was sent");
|
|
221
|
+
}
|
|
222
|
+
const d = decision;
|
|
223
|
+
if (!d || typeof d !== "object" || d.allow !== true) {
|
|
224
|
+
const reason = d && typeof d.reason === "string" ? d.reason.slice(0, 200) : undefined;
|
|
225
|
+
fail("authorization-denied", "The consumer's policy did not allow this operation", reason ? { reason } : {});
|
|
226
|
+
}
|
|
227
|
+
if (d.descriptorDigest !== descriptor.digest)
|
|
228
|
+
fail("authorization-denied", "The authorization is for a different descriptor");
|
|
229
|
+
const t = now();
|
|
230
|
+
if (typeof d.expiresAt !== "number" || !Number.isFinite(d.expiresAt) || d.expiresAt <= t)
|
|
231
|
+
fail("authorization-denied", "The authorization has expired or has no expiry");
|
|
232
|
+
if (d.expiresAt > t + limits.maxAuthorizationTtlMs)
|
|
233
|
+
fail("authorization-denied", "The authorization lives longer than the writer accepts");
|
|
234
|
+
if (d.reference !== undefined &&
|
|
235
|
+
(typeof d.reference !== "string" || d.reference.length > 200 || CONTROL.test(d.reference)))
|
|
236
|
+
fail("authorization-denied", "The authorization reference is malformed");
|
|
237
|
+
return { expiresAt: d.expiresAt, reference: d.reference ?? null };
|
|
238
|
+
}
|
|
239
|
+
// --- per-kind GitHub mechanics --------------------------------------------------------------
|
|
240
|
+
function writePath(d) {
|
|
241
|
+
const t = d.target;
|
|
242
|
+
switch (d.kind) {
|
|
243
|
+
case "issue.create":
|
|
244
|
+
return `${root}/issues`;
|
|
245
|
+
case "issue.comment":
|
|
246
|
+
return `${root}/issues/${t.number}/comments`;
|
|
247
|
+
case "pull.review":
|
|
248
|
+
return `${root}/pulls/${t.number}/reviews`;
|
|
249
|
+
case "pull.create":
|
|
250
|
+
return `${root}/pulls`;
|
|
251
|
+
case "issue.update":
|
|
252
|
+
return `${root}/issues/${t.number}`;
|
|
253
|
+
case "comment.update":
|
|
254
|
+
return `${root}/issues/comments/${t.id}`;
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
function payloadOf(d, marker) {
|
|
258
|
+
const payload = { ...d.payload };
|
|
259
|
+
if (CREATES.has(d.kind))
|
|
260
|
+
payload.body = markedBody(String(payload.body ?? ""), marker);
|
|
261
|
+
return payload;
|
|
262
|
+
}
|
|
263
|
+
/** Reads what must hold before the write. Throws a refusal; nothing has been sent. */
|
|
264
|
+
async function preflight(d) {
|
|
265
|
+
const pre = d.precondition;
|
|
266
|
+
switch (d.kind) {
|
|
267
|
+
case "issue.create":
|
|
268
|
+
return {};
|
|
269
|
+
case "issue.comment": {
|
|
270
|
+
const number = d.target.number;
|
|
271
|
+
const issue = parse(IssueRead, await read(["issues", number]), "an issue");
|
|
272
|
+
const isPull = issue.pull_request !== undefined && issue.pull_request !== null;
|
|
273
|
+
if (isPull !== (pre.thread === "pull-request"))
|
|
274
|
+
fail("wrong-target", `#${number} is ${isPull ? "a pull request" : "an issue"}, not the expected thread`);
|
|
275
|
+
if (issue.state !== "open" && pre.allowClosed !== true)
|
|
276
|
+
fail("conflict", `#${number} is ${issue.state}`, { reason: "closed" });
|
|
277
|
+
if (issue.locked === true && pre.allowLocked !== true)
|
|
278
|
+
fail("conflict", `#${number} is locked`, { reason: "locked" });
|
|
279
|
+
return {};
|
|
280
|
+
}
|
|
281
|
+
case "pull.review": {
|
|
282
|
+
const pull = parse(PullRead, await read(["pulls", d.target.number]), "a pull request");
|
|
283
|
+
if (pull.state !== "open" || pull.merged_at)
|
|
284
|
+
fail("conflict", "The pull request is not open", { reason: "closed" });
|
|
285
|
+
if (pull.head.sha !== pre.headSha)
|
|
286
|
+
fail("stale", "The pull request head is not the reviewed commit", {
|
|
287
|
+
expected: pre.headSha,
|
|
288
|
+
actual: pull.head.sha,
|
|
289
|
+
});
|
|
290
|
+
return { headSha: pull.head.sha };
|
|
291
|
+
}
|
|
292
|
+
case "pull.create": {
|
|
293
|
+
const t = d.target;
|
|
294
|
+
const head = parse(GitRefRead, await readRef(t.head), "a branch");
|
|
295
|
+
if (head.object.sha !== pre.headSha)
|
|
296
|
+
fail("stale", "The head branch is not at the expected commit", {
|
|
297
|
+
expected: pre.headSha,
|
|
298
|
+
actual: head.object.sha,
|
|
299
|
+
});
|
|
300
|
+
if (pre.baseSha !== undefined) {
|
|
301
|
+
const base = parse(GitRefRead, await readRef(t.base), "a branch");
|
|
302
|
+
if (base.object.sha !== pre.baseSha)
|
|
303
|
+
fail("stale", "The base branch is not at the expected commit", {
|
|
304
|
+
expected: pre.baseSha,
|
|
305
|
+
actual: base.object.sha,
|
|
306
|
+
});
|
|
307
|
+
}
|
|
308
|
+
const open = parse(z.array(PullRead), await read(["pulls"], {
|
|
309
|
+
state: "open",
|
|
310
|
+
head: `${owner}:${t.head}`,
|
|
311
|
+
base: t.base,
|
|
312
|
+
per_page: "100",
|
|
313
|
+
}), "pull requests");
|
|
314
|
+
if (open.length > 0)
|
|
315
|
+
fail("conflict", "An open pull request already exists for this head and base", {
|
|
316
|
+
reason: "exists",
|
|
317
|
+
number: open[0]?.number,
|
|
318
|
+
});
|
|
319
|
+
return {};
|
|
320
|
+
}
|
|
321
|
+
case "issue.update": {
|
|
322
|
+
const number = d.target.number;
|
|
323
|
+
const issue = parse(IssueRead, await read(["issues", number]), "an issue");
|
|
324
|
+
if (issue.pull_request !== undefined && issue.pull_request !== null)
|
|
325
|
+
fail("wrong-target", `#${number} is a pull request`);
|
|
326
|
+
await expectState(issue.updated_at, issue.body, pre, { state: issue.state });
|
|
327
|
+
return {};
|
|
328
|
+
}
|
|
329
|
+
case "comment.update": {
|
|
330
|
+
const comment = parse(CommentRead, await read(["issues", "comments", d.target.id]), "a comment");
|
|
331
|
+
if (!comment.issue_url.endsWith(`${root}/issues/${pre.issueNumber}`))
|
|
332
|
+
fail("wrong-target", "The comment is not on the expected issue in this repository");
|
|
333
|
+
if (pre.author !== undefined && comment.user?.login !== pre.author)
|
|
334
|
+
fail("conflict", "The comment is by another author", { reason: "author" });
|
|
335
|
+
await expectState(comment.updated_at, comment.body, pre, {});
|
|
336
|
+
return {};
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
async function expectState(updatedAt, body, pre, actual) {
|
|
341
|
+
if (updatedAt !== pre.updatedAt)
|
|
342
|
+
fail("stale", "The target changed since it was read", {
|
|
343
|
+
expected: pre.updatedAt,
|
|
344
|
+
actual: updatedAt,
|
|
345
|
+
});
|
|
346
|
+
if (pre.bodyDigest !== undefined && (await bodyDigest(body)) !== pre.bodyDigest)
|
|
347
|
+
fail("stale", "The target's body changed since it was read");
|
|
348
|
+
if (pre.state !== undefined && actual.state !== pre.state)
|
|
349
|
+
fail("stale", "The target's state changed since it was read");
|
|
350
|
+
}
|
|
351
|
+
function resourceOf(d, body) {
|
|
352
|
+
const target = d.target;
|
|
353
|
+
switch (d.kind) {
|
|
354
|
+
case "issue.create":
|
|
355
|
+
case "issue.update": {
|
|
356
|
+
const r = IssueRead.safeParse(body);
|
|
357
|
+
return r.success ? { type: "issue", number: r.data.number, url: r.data.html_url } : null;
|
|
358
|
+
}
|
|
359
|
+
case "issue.comment":
|
|
360
|
+
case "comment.update": {
|
|
361
|
+
const r = CommentRead.safeParse(body);
|
|
362
|
+
const issueNumber = d.kind === "issue.comment"
|
|
363
|
+
? target.number
|
|
364
|
+
: d.precondition.issueNumber;
|
|
365
|
+
return r.success
|
|
366
|
+
? { type: "comment", id: r.data.id, issueNumber, url: r.data.html_url }
|
|
367
|
+
: null;
|
|
368
|
+
}
|
|
369
|
+
case "pull.review": {
|
|
370
|
+
const r = ReviewRead.safeParse(body);
|
|
371
|
+
return r.success
|
|
372
|
+
? {
|
|
373
|
+
type: "review",
|
|
374
|
+
id: r.data.id,
|
|
375
|
+
pullNumber: target.number,
|
|
376
|
+
commitSha: r.data.commit_id ?? null,
|
|
377
|
+
state: r.data.state,
|
|
378
|
+
}
|
|
379
|
+
: null;
|
|
380
|
+
}
|
|
381
|
+
case "pull.create": {
|
|
382
|
+
const r = PullRead.safeParse(body);
|
|
383
|
+
return r.success
|
|
384
|
+
? { type: "pull", number: r.data.number, url: r.data.html_url, headSha: r.data.head.sha }
|
|
385
|
+
: null;
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
/** A fresh read of the written resource, compared field by field with what was authorized. */
|
|
390
|
+
async function verify(d, resource, sent) {
|
|
391
|
+
const mismatches = [];
|
|
392
|
+
let headMoved;
|
|
393
|
+
try {
|
|
394
|
+
switch (resource.type) {
|
|
395
|
+
case "issue": {
|
|
396
|
+
const issue = parse(IssueRead, await read(["issues", resource.number]), "an issue");
|
|
397
|
+
if (sent.title !== undefined && issue.title !== sent.title)
|
|
398
|
+
mismatches.push("title");
|
|
399
|
+
if (sent.body !== undefined && (issue.body ?? "") !== sent.body)
|
|
400
|
+
mismatches.push("body");
|
|
401
|
+
if (sent.state !== undefined && issue.state !== sent.state)
|
|
402
|
+
mismatches.push("state");
|
|
403
|
+
if (sent.labels !== undefined &&
|
|
404
|
+
!sameSet(labelNames(issue.labels), sent.labels))
|
|
405
|
+
mismatches.push("labels");
|
|
406
|
+
if (sent.assignees !== undefined &&
|
|
407
|
+
!sameSet((issue.assignees ?? []).map((a) => a.login), sent.assignees))
|
|
408
|
+
mismatches.push("assignees");
|
|
409
|
+
break;
|
|
410
|
+
}
|
|
411
|
+
case "comment": {
|
|
412
|
+
const comment = parse(CommentRead, await read(["issues", "comments", resource.id]), "a comment");
|
|
413
|
+
if ((comment.body ?? "") !== sent.body)
|
|
414
|
+
mismatches.push("body");
|
|
415
|
+
if (!comment.issue_url.endsWith(`${root}/issues/${resource.issueNumber}`))
|
|
416
|
+
mismatches.push("issue");
|
|
417
|
+
break;
|
|
418
|
+
}
|
|
419
|
+
case "review": {
|
|
420
|
+
const review = parse(ReviewRead, await read(["pulls", resource.pullNumber, "reviews", resource.id]), "a review");
|
|
421
|
+
if (review.commit_id !== sent.commit_id)
|
|
422
|
+
mismatches.push("commit");
|
|
423
|
+
if (review.state !== REVIEW_STATE[sent.event])
|
|
424
|
+
mismatches.push("state");
|
|
425
|
+
if ((review.body ?? "") !== sent.body)
|
|
426
|
+
mismatches.push("body");
|
|
427
|
+
const pull = parse(PullRead, await read(["pulls", resource.pullNumber]), "a pull request");
|
|
428
|
+
headMoved = pull.head.sha !== d.precondition.headSha;
|
|
429
|
+
break;
|
|
430
|
+
}
|
|
431
|
+
case "pull": {
|
|
432
|
+
const pull = parse(PullRead, await read(["pulls", resource.number]), "a pull request");
|
|
433
|
+
const pre = d.precondition;
|
|
434
|
+
if (pull.head.sha !== pre.headSha)
|
|
435
|
+
mismatches.push("head.sha");
|
|
436
|
+
if (pull.head.ref !== sent.head)
|
|
437
|
+
mismatches.push("head.ref");
|
|
438
|
+
if (pull.head.repo?.full_name !== repository)
|
|
439
|
+
mismatches.push("head.repository");
|
|
440
|
+
if (pull.base.ref !== sent.base)
|
|
441
|
+
mismatches.push("base.ref");
|
|
442
|
+
if (pull.title !== sent.title)
|
|
443
|
+
mismatches.push("title");
|
|
444
|
+
if ((pull.body ?? "") !== sent.body)
|
|
445
|
+
mismatches.push("body");
|
|
446
|
+
break;
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
catch {
|
|
451
|
+
return { verification: "unavailable", mismatches, headMoved };
|
|
452
|
+
}
|
|
453
|
+
return {
|
|
454
|
+
verification: mismatches.length === 0 ? "matched" : "mismatch",
|
|
455
|
+
mismatches,
|
|
456
|
+
headMoved,
|
|
457
|
+
};
|
|
458
|
+
}
|
|
459
|
+
/** Bounded search for an uncertain create, by its marker. Reads only. */
|
|
460
|
+
async function search(record) {
|
|
461
|
+
const d = record.descriptor;
|
|
462
|
+
const marker = record.marker;
|
|
463
|
+
const empty = { complete: false, matches: 0, foreignMarkers: 0, duplicates: [] };
|
|
464
|
+
if (marker === null || !CREATES.has(d.kind))
|
|
465
|
+
return { found: null, body: null, report: empty };
|
|
466
|
+
const since = record.firstSentAt === null
|
|
467
|
+
? undefined
|
|
468
|
+
: new Date(Math.max(0, record.firstSentAt - limits.searchSkewMs)).toISOString();
|
|
469
|
+
const t = d.target;
|
|
470
|
+
let segments;
|
|
471
|
+
let query = {};
|
|
472
|
+
switch (d.kind) {
|
|
473
|
+
case "issue.create":
|
|
474
|
+
segments = ["issues"];
|
|
475
|
+
query = { state: "all", sort: "created", direction: "desc", ...(since ? { since } : {}) };
|
|
476
|
+
break;
|
|
477
|
+
case "issue.comment":
|
|
478
|
+
segments = ["issues", t.number, "comments"];
|
|
479
|
+
query = since ? { since } : {};
|
|
480
|
+
break;
|
|
481
|
+
case "pull.review":
|
|
482
|
+
segments = ["pulls", t.number, "reviews"];
|
|
483
|
+
break;
|
|
484
|
+
default:
|
|
485
|
+
segments = ["pulls"];
|
|
486
|
+
query = { state: "all", head: `${owner}:${t.head}`, base: t.base };
|
|
487
|
+
}
|
|
488
|
+
const matches = [];
|
|
489
|
+
let foreign = 0;
|
|
490
|
+
let complete = false;
|
|
491
|
+
for (let page = 1; page <= limits.reconcileMaxPages; page++) {
|
|
492
|
+
const batch = parse(z.array(z.unknown()), await read(segments, { ...query, per_page: "100", page: String(page) }), "a listing");
|
|
493
|
+
for (const raw of batch) {
|
|
494
|
+
const item = parse(Listed, raw, "a listed item");
|
|
495
|
+
if (d.kind === "issue.create" && raw.pull_request)
|
|
496
|
+
continue;
|
|
497
|
+
if (!carriesMarker(item.body, marker))
|
|
498
|
+
continue;
|
|
499
|
+
if (options.expectedAuthor !== undefined && item.user?.login !== options.expectedAuthor)
|
|
500
|
+
foreign += 1;
|
|
501
|
+
else
|
|
502
|
+
matches.push({ item, raw });
|
|
503
|
+
}
|
|
504
|
+
if (batch.length < 100) {
|
|
505
|
+
complete = true;
|
|
506
|
+
break;
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
const first = matches[0];
|
|
510
|
+
const report = {
|
|
511
|
+
complete,
|
|
512
|
+
matches: matches.length,
|
|
513
|
+
foreignMarkers: foreign,
|
|
514
|
+
duplicates: matches.slice(1).map((m) => m.item.id ?? m.item.number ?? 0),
|
|
515
|
+
};
|
|
516
|
+
if (!first)
|
|
517
|
+
return { found: null, body: null, report };
|
|
518
|
+
// Listings are newest-first for issues, oldest-first elsewhere; report the oldest as the write.
|
|
519
|
+
const chosen = d.kind === "issue.create" ? (matches.at(-1) ?? first) : first;
|
|
520
|
+
if (d.kind === "issue.create")
|
|
521
|
+
report.duplicates = matches.slice(0, -1).map((m) => m.item.number ?? 0);
|
|
522
|
+
return { found: resourceOf(d, chosen.raw), body: chosen.item.body ?? null, report };
|
|
523
|
+
}
|
|
524
|
+
function outcome(record, status, fields) {
|
|
525
|
+
return {
|
|
526
|
+
status,
|
|
527
|
+
operationId: record.operationId,
|
|
528
|
+
kind: record.kind,
|
|
529
|
+
repository: record.repository,
|
|
530
|
+
descriptorDigest: record.fingerprint,
|
|
531
|
+
recovered: false,
|
|
532
|
+
resource: null,
|
|
533
|
+
verification: "not-attempted",
|
|
534
|
+
mismatches: [],
|
|
535
|
+
...fields,
|
|
536
|
+
};
|
|
537
|
+
}
|
|
538
|
+
/** The write was found by reconciliation: record it as succeeded and say how it was found. */
|
|
539
|
+
async function adopt(record, found, report) {
|
|
540
|
+
const sent = payloadOf(record.descriptor, record.marker);
|
|
541
|
+
const checked = await verify(record.descriptor, found, sent);
|
|
542
|
+
const result = outcome(record, checked.verification === "matched" ? "verified" : "accepted", {
|
|
543
|
+
recovered: true,
|
|
544
|
+
resource: found,
|
|
545
|
+
verification: checked.verification,
|
|
546
|
+
mismatches: checked.mismatches,
|
|
547
|
+
reconciliation: report,
|
|
548
|
+
...(checked.headMoved !== undefined ? { headMovedDuringPublication: checked.headMoved } : {}),
|
|
549
|
+
});
|
|
550
|
+
const recorded = await settle(record, {
|
|
551
|
+
state: "succeeded",
|
|
552
|
+
leaseUntil: null,
|
|
553
|
+
outcome: result,
|
|
554
|
+
failure: null,
|
|
555
|
+
});
|
|
556
|
+
return { ...result, replayed: false, recorded };
|
|
557
|
+
}
|
|
558
|
+
async function markIndeterminate(record, reason, report) {
|
|
559
|
+
const result = outcome(record, "indeterminate", {
|
|
560
|
+
reason,
|
|
561
|
+
...(report ? { reconciliation: report } : {}),
|
|
562
|
+
});
|
|
563
|
+
const recorded = await settle(record, {
|
|
564
|
+
state: "indeterminate",
|
|
565
|
+
leaseUntil: null,
|
|
566
|
+
outcome: result,
|
|
567
|
+
});
|
|
568
|
+
return { ...result, replayed: false, recorded };
|
|
569
|
+
}
|
|
570
|
+
/** For an update that may already have been sent: is it applied, still applicable, or neither? */
|
|
571
|
+
async function updateStatus(d) {
|
|
572
|
+
const sent = payloadOf(d, null);
|
|
573
|
+
const pre = d.precondition;
|
|
574
|
+
if (d.kind === "issue.update") {
|
|
575
|
+
const issue = parse(IssueRead, await read(["issues", d.target.number]), "an issue");
|
|
576
|
+
const applied = (sent.title === undefined || issue.title === sent.title) &&
|
|
577
|
+
(sent.body === undefined || (issue.body ?? "") === sent.body) &&
|
|
578
|
+
(sent.state === undefined || issue.state === sent.state) &&
|
|
579
|
+
(sent.labels === undefined || sameSet(labelNames(issue.labels), sent.labels));
|
|
580
|
+
if (applied)
|
|
581
|
+
return "applied";
|
|
582
|
+
return issue.updated_at === pre.updatedAt ? "applicable" : "diverged";
|
|
583
|
+
}
|
|
584
|
+
const comment = parse(CommentRead, await read(["issues", "comments", d.target.id]), "a comment");
|
|
585
|
+
if ((comment.body ?? "") === sent.body)
|
|
586
|
+
return "applied";
|
|
587
|
+
return comment.updated_at === pre.updatedAt ? "applicable" : "diverged";
|
|
588
|
+
}
|
|
589
|
+
// --- execution ------------------------------------------------------------------------------
|
|
590
|
+
/** Takes ownership of the operation's record, or answers from it without sending. */
|
|
591
|
+
async function claim(d, marker, reference) {
|
|
592
|
+
for (let round = 0; round < 3; round++) {
|
|
593
|
+
const existing = await store(() => ledger.get(d.operationId));
|
|
594
|
+
const t = now();
|
|
595
|
+
if (!existing) {
|
|
596
|
+
const fresh = {
|
|
597
|
+
schema: "comforge-github-operation/v1",
|
|
598
|
+
operationId: d.operationId,
|
|
599
|
+
repository,
|
|
600
|
+
kind: d.kind,
|
|
601
|
+
capability: d.capability,
|
|
602
|
+
fingerprint: d.digest,
|
|
603
|
+
descriptor: d,
|
|
604
|
+
version: 1,
|
|
605
|
+
state: "reserved",
|
|
606
|
+
leaseUntil: t + limits.leaseMs,
|
|
607
|
+
attempts: 0,
|
|
608
|
+
firstSentAt: null,
|
|
609
|
+
changedAt: t,
|
|
610
|
+
authorizationReference: reference,
|
|
611
|
+
marker,
|
|
612
|
+
outcome: null,
|
|
613
|
+
failure: null,
|
|
614
|
+
note: null,
|
|
615
|
+
};
|
|
616
|
+
if (await store(() => ledger.create(fresh)))
|
|
617
|
+
return { record: fresh };
|
|
618
|
+
continue;
|
|
619
|
+
}
|
|
620
|
+
if (existing.repository !== repository || existing.fingerprint !== d.digest)
|
|
621
|
+
fail("conflict", "This operationId was already used for a different operation", {
|
|
622
|
+
reason: "fingerprint-mismatch",
|
|
623
|
+
});
|
|
624
|
+
switch (existing.state) {
|
|
625
|
+
case "succeeded":
|
|
626
|
+
return { answer: storedOutcome(existing, true) };
|
|
627
|
+
case "indeterminate":
|
|
628
|
+
return { answer: storedOutcome(existing, true) };
|
|
629
|
+
case "abandoned":
|
|
630
|
+
fail("conflict", "This operation was abandoned; use a new operationId", {
|
|
631
|
+
reason: "abandoned",
|
|
632
|
+
});
|
|
633
|
+
break;
|
|
634
|
+
case "reserved":
|
|
635
|
+
case "sending": {
|
|
636
|
+
if (existing.leaseUntil !== null && existing.leaseUntil > t)
|
|
637
|
+
fail("conflict", "This operation is in progress elsewhere", { reason: "in-progress" });
|
|
638
|
+
if (existing.state === "sending") {
|
|
639
|
+
// The sender stopped without recording an answer: the write may have happened.
|
|
640
|
+
const taken = await advance(existing, { leaseUntil: t + limits.leaseMs });
|
|
641
|
+
if (!taken)
|
|
642
|
+
continue;
|
|
643
|
+
return {
|
|
644
|
+
answer: await markIndeterminate(taken, "a previous attempt stopped after sending"),
|
|
645
|
+
};
|
|
646
|
+
}
|
|
647
|
+
const taken = await advance(existing, {
|
|
648
|
+
leaseUntil: t + limits.leaseMs,
|
|
649
|
+
authorizationReference: reference,
|
|
650
|
+
});
|
|
651
|
+
if (taken)
|
|
652
|
+
return { record: taken };
|
|
653
|
+
continue;
|
|
654
|
+
}
|
|
655
|
+
case "failed": {
|
|
656
|
+
const f = existing.failure;
|
|
657
|
+
if (!f?.retryable)
|
|
658
|
+
fail(f?.code ?? "conflict", f?.message ?? "This operation failed", {
|
|
659
|
+
...(f?.status !== undefined ? { status: f.status } : {}),
|
|
660
|
+
reason: "failed",
|
|
661
|
+
});
|
|
662
|
+
if (f.notBefore !== null && f.notBefore > t)
|
|
663
|
+
fail("rate-limited", "Retry after GitHub's requested delay", {
|
|
664
|
+
retryAfterSeconds: Math.ceil((f.notBefore - t) / 1000),
|
|
665
|
+
});
|
|
666
|
+
const taken = await advance(existing, {
|
|
667
|
+
state: "reserved",
|
|
668
|
+
leaseUntil: t + limits.leaseMs,
|
|
669
|
+
authorizationReference: reference,
|
|
670
|
+
});
|
|
671
|
+
if (taken)
|
|
672
|
+
return { record: taken };
|
|
673
|
+
continue;
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
fail("conflict", "The operation record kept changing; retry later", { reason: "in-progress" });
|
|
678
|
+
}
|
|
679
|
+
async function execute(operation) {
|
|
680
|
+
const d = await describe(repository, operation);
|
|
681
|
+
if (!capabilities.includes(d.capability))
|
|
682
|
+
fail("capability-denied", `This writer was not constructed with ${d.capability}`);
|
|
683
|
+
const marker = namespace !== null && CREATES.has(d.kind) ? await correlationMarker(namespace, d) : null;
|
|
684
|
+
payloadOf(d, marker); // refuses an over-long body before anything is recorded
|
|
685
|
+
const grant = await authorize(d);
|
|
686
|
+
const claimed = await claim(d, marker, grant.reference);
|
|
687
|
+
if ("answer" in claimed)
|
|
688
|
+
return claimed.answer;
|
|
689
|
+
let record = claimed.record;
|
|
690
|
+
// A create that may already have reached GitHub is looked for before it is sent again.
|
|
691
|
+
if (record.firstSentAt !== null) {
|
|
692
|
+
if (CREATES.has(d.kind)) {
|
|
693
|
+
let found;
|
|
694
|
+
try {
|
|
695
|
+
found = await search(record);
|
|
696
|
+
}
|
|
697
|
+
catch {
|
|
698
|
+
return markIndeterminate(record, "could not search for an earlier attempt");
|
|
699
|
+
}
|
|
700
|
+
if (found.found)
|
|
701
|
+
return adopt(record, found.found, found.report);
|
|
702
|
+
if (!found.report.complete)
|
|
703
|
+
return markIndeterminate(record, "an earlier attempt could not be ruled out", found.report);
|
|
704
|
+
}
|
|
705
|
+
else {
|
|
706
|
+
const status = await updateStatus(d).catch(() => "diverged");
|
|
707
|
+
if (status === "applied")
|
|
708
|
+
return adopt(record, resourceOf(d, await readTarget(d)), {
|
|
709
|
+
complete: true,
|
|
710
|
+
matches: 1,
|
|
711
|
+
foreignMarkers: 0,
|
|
712
|
+
duplicates: [],
|
|
713
|
+
});
|
|
714
|
+
if (status === "diverged")
|
|
715
|
+
return markIndeterminate(record, "the target changed after an earlier attempt");
|
|
716
|
+
}
|
|
717
|
+
}
|
|
718
|
+
try {
|
|
719
|
+
await preflight(d);
|
|
720
|
+
}
|
|
721
|
+
catch (error) {
|
|
722
|
+
const e = error instanceof GitHubAdapterError
|
|
723
|
+
? error
|
|
724
|
+
: new GitHubAdapterError("malformed-response", "Precondition read failed");
|
|
725
|
+
// Stale or wrong targets are permanent for this exact descriptor; transient reads are not.
|
|
726
|
+
return refuse(record, e, ["timeout", "network", "rate-limited", "http-error"].includes(e.code));
|
|
727
|
+
}
|
|
728
|
+
if (grant.expiresAt <= now())
|
|
729
|
+
return refuse(record, new GitHubAdapterError("authorization-denied", "The authorization expired before the write"), true);
|
|
730
|
+
const sending = await advance(record, {
|
|
731
|
+
state: "sending",
|
|
732
|
+
attempts: record.attempts + 1,
|
|
733
|
+
firstSentAt: record.firstSentAt ?? now(),
|
|
734
|
+
leaseUntil: now() + limits.leaseMs,
|
|
735
|
+
});
|
|
736
|
+
if (!sending)
|
|
737
|
+
fail("conflict", "Another caller took this operation", { reason: "in-progress" });
|
|
738
|
+
record = sending;
|
|
739
|
+
const sent = payloadOf(d, marker);
|
|
740
|
+
let result;
|
|
741
|
+
try {
|
|
742
|
+
result = await sendWrite(sendOptions, d.kind, writePath(d), sent);
|
|
743
|
+
}
|
|
744
|
+
catch (error) {
|
|
745
|
+
// Refused before sending (token provider, path): nothing reached GitHub.
|
|
746
|
+
const e = error instanceof GitHubAdapterError
|
|
747
|
+
? error
|
|
748
|
+
: new GitHubAdapterError("network", "The request could not be built");
|
|
749
|
+
return refuse(record, e, true);
|
|
750
|
+
}
|
|
751
|
+
if (result.kind === "refused")
|
|
752
|
+
return refuse(record, result.error, result.error.code === "rate-limited");
|
|
753
|
+
if (result.kind === "sent-unknown") {
|
|
754
|
+
// Look once; never resend.
|
|
755
|
+
const found = CREATES.has(d.kind) ? await search(record).catch(() => null) : null;
|
|
756
|
+
if (found?.found)
|
|
757
|
+
return adopt(record, found.found, found.report);
|
|
758
|
+
if (!CREATES.has(d.kind)) {
|
|
759
|
+
const status = await updateStatus(d).catch(() => "diverged");
|
|
760
|
+
if (status === "applied")
|
|
761
|
+
return adopt(record, resourceOf(d, await readTarget(d)), {
|
|
762
|
+
complete: true,
|
|
763
|
+
matches: 1,
|
|
764
|
+
foreignMarkers: 0,
|
|
765
|
+
duplicates: [],
|
|
766
|
+
});
|
|
767
|
+
}
|
|
768
|
+
return markIndeterminate(record, `GitHub's answer is unknown (${result.reason})`, found?.report);
|
|
769
|
+
}
|
|
770
|
+
const resource = resourceOf(d, result.body);
|
|
771
|
+
if (!resource)
|
|
772
|
+
return markIndeterminate(record, "GitHub accepted the request but its response was unreadable");
|
|
773
|
+
const checked = await verify(d, resource, sent);
|
|
774
|
+
const final = outcome(record, checked.verification === "matched" ? "verified" : "accepted", {
|
|
775
|
+
resource,
|
|
776
|
+
verification: checked.verification,
|
|
777
|
+
mismatches: checked.mismatches,
|
|
778
|
+
...(checked.headMoved !== undefined ? { headMovedDuringPublication: checked.headMoved } : {}),
|
|
779
|
+
});
|
|
780
|
+
const recorded = await settle(record, {
|
|
781
|
+
state: "succeeded",
|
|
782
|
+
leaseUntil: null,
|
|
783
|
+
outcome: final,
|
|
784
|
+
failure: null,
|
|
785
|
+
});
|
|
786
|
+
return { ...final, replayed: false, recorded };
|
|
787
|
+
}
|
|
788
|
+
async function readTarget(d) {
|
|
789
|
+
return d.kind === "issue.update"
|
|
790
|
+
? read(["issues", d.target.number])
|
|
791
|
+
: read(["issues", "comments", d.target.id]);
|
|
792
|
+
}
|
|
793
|
+
async function reconcile(operationId) {
|
|
794
|
+
const record = await store(() => ledger.get(operationId));
|
|
795
|
+
if (!record || record.repository !== repository)
|
|
796
|
+
fail("not-found", "No such operation in the ledger");
|
|
797
|
+
if (record.state === "succeeded")
|
|
798
|
+
return storedOutcome(record, true);
|
|
799
|
+
const t = now();
|
|
800
|
+
if (record.state === "sending" && record.leaseUntil !== null && record.leaseUntil > t)
|
|
801
|
+
fail("conflict", "This operation is in progress elsewhere", { reason: "in-progress" });
|
|
802
|
+
if (record.state !== "indeterminate" && record.state !== "sending")
|
|
803
|
+
fail("conflict", `A ${record.state} operation has nothing to reconcile`, {
|
|
804
|
+
reason: record.state,
|
|
805
|
+
});
|
|
806
|
+
const owned = await advance(record, { leaseUntil: t + limits.leaseMs });
|
|
807
|
+
if (!owned)
|
|
808
|
+
fail("conflict", "Another caller changed this operation", { reason: "in-progress" });
|
|
809
|
+
const d = owned.descriptor;
|
|
810
|
+
if (CREATES.has(d.kind)) {
|
|
811
|
+
const found = await search(owned);
|
|
812
|
+
if (found.found)
|
|
813
|
+
return adopt(owned, found.found, found.report);
|
|
814
|
+
return markIndeterminate(owned, owned.marker === null
|
|
815
|
+
? "no correlation marker: resolve by inspection, then abandon"
|
|
816
|
+
: found.report.complete
|
|
817
|
+
? "not found; it may still appear, or it was never created — abandon to give up"
|
|
818
|
+
: "the search was incomplete", found.report);
|
|
819
|
+
}
|
|
820
|
+
const status = await updateStatus(d);
|
|
821
|
+
if (status === "applied")
|
|
822
|
+
return adopt(owned, resourceOf(d, await readTarget(d)), {
|
|
823
|
+
complete: true,
|
|
824
|
+
matches: 1,
|
|
825
|
+
foreignMarkers: 0,
|
|
826
|
+
duplicates: [],
|
|
827
|
+
});
|
|
828
|
+
if (status === "applicable") {
|
|
829
|
+
// Not applied, and the target is as authorized: a later execute may send it again.
|
|
830
|
+
await settle(owned, {
|
|
831
|
+
state: "failed",
|
|
832
|
+
leaseUntil: null,
|
|
833
|
+
outcome: null,
|
|
834
|
+
failure: {
|
|
835
|
+
code: "incomplete",
|
|
836
|
+
message: "The update was not applied",
|
|
837
|
+
retryable: true,
|
|
838
|
+
notBefore: null,
|
|
839
|
+
},
|
|
840
|
+
});
|
|
841
|
+
return {
|
|
842
|
+
...outcome(owned, "indeterminate", { reason: "not applied; execute again to resend" }),
|
|
843
|
+
replayed: false,
|
|
844
|
+
recorded: true,
|
|
845
|
+
};
|
|
846
|
+
}
|
|
847
|
+
return markIndeterminate(owned, "the target changed after the attempt; inspect it, then abandon");
|
|
848
|
+
}
|
|
849
|
+
async function abandon(operationId, reason) {
|
|
850
|
+
if (typeof reason !== "string" ||
|
|
851
|
+
reason.trim().length === 0 ||
|
|
852
|
+
reason.length > 500 ||
|
|
853
|
+
CONTROL.test(reason.replace(/\n/g, " ")))
|
|
854
|
+
fail("invalid-input", "An abandonment needs a one-line reason");
|
|
855
|
+
const record = await store(() => ledger.get(operationId));
|
|
856
|
+
if (!record || record.repository !== repository)
|
|
857
|
+
fail("not-found", "No such operation in the ledger");
|
|
858
|
+
if (record.state === "succeeded")
|
|
859
|
+
fail("conflict", "A succeeded operation cannot be abandoned", { reason: "succeeded" });
|
|
860
|
+
if (record.state === "abandoned")
|
|
861
|
+
return;
|
|
862
|
+
if ((record.state === "sending" || record.state === "reserved") &&
|
|
863
|
+
record.leaseUntil !== null &&
|
|
864
|
+
record.leaseUntil > now())
|
|
865
|
+
fail("conflict", "This operation is in progress elsewhere", { reason: "in-progress" });
|
|
866
|
+
if (!(await advance(record, { state: "abandoned", leaseUntil: null, note: reason.trim() })))
|
|
867
|
+
fail("conflict", "Another caller changed this operation", { reason: "in-progress" });
|
|
868
|
+
}
|
|
869
|
+
return Object.freeze({
|
|
870
|
+
repository,
|
|
871
|
+
capabilities,
|
|
872
|
+
prepare: (operation) => describe(repository, operation),
|
|
873
|
+
execute,
|
|
874
|
+
reconcile,
|
|
875
|
+
abandon,
|
|
876
|
+
});
|
|
877
|
+
}
|