@futurelastic/colab-handbook 1.12.0 โ 1.13.0-rc.10
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 +248 -213
- package/README.vi.md +252 -186
- package/audit/audit.mjs +193 -10
- package/package.json +7 -1
- package/templates/README.md +30 -2
- package/templates/ci-laravel.yml +102 -21
- package/templates/ci-node.yml +61 -3
- package/templates/ci-python.yml +52 -3
- package/templates/deploy-adapter-portainer.mjs +206 -0
- package/templates/deploy-container-run.mjs +368 -0
- package/templates/deploy-container.yml +219 -0
- package/templates/dist-refs.yml +6 -0
- package/templates/docs-lint.mjs +1 -1
- package/templates/npx-launcher.mjs +118 -20
- package/templates/npx-service.mjs +828 -0
- package/templates/release-auto.yml +341 -32
- package/tools/colab +1902 -278
- package/tools/lib/adopt.js +373 -14
- package/tools/lib/branch-name.js +29 -1
- package/tools/lib/ci-cure.js +522 -31
- package/tools/lib/ci-grant.js +289 -22
- package/tools/lib/ci-wait.js +223 -0
- package/tools/lib/claim-comments.js +13 -64
- package/tools/lib/claim-identity.js +42 -7
- package/tools/lib/codec/claim.d.ts +41 -0
- package/tools/lib/codec/claim.js +153 -0
- package/tools/lib/codec/decision.d.ts +29 -0
- package/tools/lib/codec/decision.js +81 -0
- package/tools/lib/codec/grants.d.ts +82 -0
- package/tools/lib/codec/grants.js +268 -0
- package/tools/lib/codec/hold.d.ts +26 -0
- package/tools/lib/codec/hold.js +152 -0
- package/tools/lib/codec/index.d.ts +21 -0
- package/tools/lib/codec/index.js +32 -0
- package/tools/lib/codec/labels.d.ts +65 -0
- package/tools/lib/codec/labels.js +723 -0
- package/tools/lib/codec/markers.d.ts +35 -0
- package/tools/lib/codec/markers.js +138 -0
- package/tools/lib/codec/release.d.ts +17 -0
- package/tools/lib/codec/release.js +69 -0
- package/tools/lib/codec/samples.json +778 -0
- package/tools/lib/codeowners.js +68 -4
- package/tools/lib/container-close.js +38 -0
- package/tools/lib/cure-diff.js +198 -9
- package/tools/lib/decision-record.js +15 -39
- package/tools/lib/docs-only.js +15 -1
- package/tools/lib/exposure-shape.js +42 -8
- package/tools/lib/git.js +324 -42
- package/tools/lib/group-labels.js +65 -0
- package/tools/lib/install-check.js +14 -8
- package/tools/lib/install-route.js +139 -0
- package/tools/lib/instruction-file.js +1 -0
- package/tools/lib/labels.js +22 -647
- package/tools/lib/local-adopt.js +8 -4
- package/tools/lib/migration-grant.js +206 -104
- package/tools/lib/place.js +2 -2
- package/tools/lib/release-cut.js +199 -25
- package/tools/lib/release-finalize.js +111 -23
- package/tools/lib/release-policy.js +130 -22
- package/tools/lib/release-runner.js +125 -0
- package/tools/lib/release-tag.js +3 -1
- package/tools/lib/scratch-dirs.js +118 -0
- package/tools/lib/ship-batch.js +36 -1
- package/tools/lib/ship-human-door.js +76 -0
- package/tools/lib/stamp.js +7 -0
- package/tools/lib/tracker-fake.js +195 -0
- package/tools/lib/tracker-github.js +106 -0
- package/tools/lib/tracker-scenarios.json +206 -0
- package/tools/lib/tracker.js +64 -0
- package/tools/lib/tree-green.js +88 -0
- package/tools/lib/util.js +17 -1
- package/tools/lib/verify-runs.js +104 -0
- package/tools/lib/wake.js +8 -90
- package/tools/lib/workflow-triggers.js +48 -0
package/tools/lib/ci-grant.js
CHANGED
|
@@ -68,32 +68,28 @@
|
|
|
68
68
|
* `COLAB_HUMAN=1`, the same bar `cmdPromote` and `cmdMigrationGrant` already hold.
|
|
69
69
|
*/
|
|
70
70
|
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
const
|
|
76
|
-
const
|
|
71
|
+
// The wire format โ both marks (a leading emoji distinct from migration-grant's ๐ข/๐ซ AND from
|
|
72
|
+
// each other; ci-grant.test.js's four-way collision test pins it), both regexes, and the
|
|
73
|
+
// encode/decode pairs โ lives in codec/grants.js (#498, epic #496). Re-exported below under the
|
|
74
|
+
// names this module always had.
|
|
75
|
+
const codec = require('./codec/grants');
|
|
76
|
+
const GRANT_MARK = codec.CI_GRANT_MARK;
|
|
77
|
+
const REVOKE_MARK = codec.CI_REVOKE_MARK;
|
|
78
|
+
const GRANT_RE = codec.CI_GRANT_RE;
|
|
79
|
+
const REVOKE_RE = codec.CI_REVOKE_RE;
|
|
77
80
|
|
|
78
|
-
|
|
79
|
-
const REVOKE_RE = /^๐งฏ Red-trunk CI grant revoked โ branch `([^`]*)` ยท host `([^`]*)` ยท (\S+)/;
|
|
80
|
-
|
|
81
|
-
/** The exact grant-comment body. Keep in lockstep with GRANT_RE. Carries strictly more than
|
|
81
|
+
/** The exact grant-comment body (codec `encodeCiGrant`, canonical tail). Carries strictly more than
|
|
82
82
|
* migration-grant's equivalent: the TRUNK NAME + RED SHA it was reviewed against, and the
|
|
83
83
|
* EVIDENCE RUN sha that proved the branch's own head green โ both are read back and re-checked
|
|
84
84
|
* by evaluateIssue, not merely stored for audit. */
|
|
85
85
|
function grantCommentBody(branch, trunk, redSha, evidenceSha, host, iso) {
|
|
86
|
-
return
|
|
87
|
-
+ ` โ this exempts THIS BRANCH from the trunk-CI-green precondition ONLY, only while \`${trunk}\``
|
|
88
|
-
+ ` is still at \`${redSha}\`, and expires when this issue closes.`;
|
|
86
|
+
return codec.encodeCiGrant({ branch, trunk, redSha, evidenceSha, host, at: iso });
|
|
89
87
|
}
|
|
90
88
|
|
|
91
|
-
/** The exact revoke-comment body
|
|
92
|
-
*
|
|
93
|
-
* in migration-grant.js; identical reasoning applies here). */
|
|
89
|
+
/** The exact revoke-comment body (codec `encodeCiRevoke`). `branch` is for the audit trail โ
|
|
90
|
+
* revocation itself is NOT branch-scoped (see evaluateIssue doc in migration-grant.js). */
|
|
94
91
|
function revokeCommentBody(branch, host, iso) {
|
|
95
|
-
return
|
|
96
|
-
+ ' โ every grant on this issue up to this point is cancelled.';
|
|
92
|
+
return codec.encodeCiRevoke({ branch, host, at: iso });
|
|
97
93
|
}
|
|
98
94
|
|
|
99
95
|
/**
|
|
@@ -234,6 +230,11 @@ function evaluateIssue(record, branch, trunk, redTrunkSha, evidence, issueNum, l
|
|
|
234
230
|
*
|
|
235
231
|
* `records` maps issue number โ the `ghIssueView` result for that issue, or `null` on a failed
|
|
236
232
|
* read (the caller's job, not this function's).
|
|
233
|
+
*
|
|
234
|
+
* `opts` (#504) additionally carries `{ policy, now, redJobs }` for the reviewer role: per issue a
|
|
235
|
+
* live human grant wins, unchanged; otherwise an issue carrying a live reviewer grant is judged by
|
|
236
|
+
* evaluateReviewerIssue (records must then include `title`). `redJobs` is a thunk, called at most
|
|
237
|
+
* once per set. A granted reviewer entry carries `role: 'ci-reviewer'`, `reviewer`, `head`, `cures`.
|
|
237
238
|
*/
|
|
238
239
|
function evaluateShipSet(issues, records, branch, trunk, redTrunkSha, evidence, labelName, opts) {
|
|
239
240
|
const list = Array.isArray(issues) ? issues : [];
|
|
@@ -243,10 +244,35 @@ function evaluateShipSet(issues, records, branch, trunk, redTrunkSha, evidence,
|
|
|
243
244
|
}
|
|
244
245
|
const granted = [];
|
|
245
246
|
const missing = [];
|
|
247
|
+
// #504: the red-job set is read at most once per set, and only by an issue whose reviewer grant
|
|
248
|
+
// has cleared every cheaper check.
|
|
249
|
+
let redJobsMemo;
|
|
250
|
+
const redJobs = () => {
|
|
251
|
+
if (redJobsMemo === undefined) {
|
|
252
|
+
try { redJobsMemo = opts && typeof opts.redJobs === 'function' ? opts.redJobs() : null; } catch (_) { redJobsMemo = null; }
|
|
253
|
+
}
|
|
254
|
+
return redJobsMemo;
|
|
255
|
+
};
|
|
246
256
|
for (const n of list) {
|
|
247
|
-
const
|
|
248
|
-
|
|
249
|
-
|
|
257
|
+
const rec = records ? records[n] : null;
|
|
258
|
+
const v = evaluateIssue(rec, branch, trunk, redTrunkSha, evidence, n, labelName, opts);
|
|
259
|
+
if (v.ok) {
|
|
260
|
+
granted.push({ issue: n, branch: v.grant.branch, by: v.grant.login, at: v.grant.at, redSha: v.grant.redSha, evidenceSha: v.grant.evidenceSha });
|
|
261
|
+
continue;
|
|
262
|
+
}
|
|
263
|
+
// #504: a reviewer grant is consulted only when the human one failed AND the issue carries a
|
|
264
|
+
// live reviewer marker โ so an issue with none keeps the human reason byte for byte.
|
|
265
|
+
const hasReviewer = !!rec && liveGrantRecords(rec.comments).some((g) => g.role !== 'human');
|
|
266
|
+
if (!hasReviewer) { missing.push({ issue: n, reason: v.reason }); continue; }
|
|
267
|
+
const r = evaluateReviewerIssue(rec, { branch, trunk, redTrunkSha, evidence, issueNum: n, labelName,
|
|
268
|
+
policy: opts && opts.policy, now: opts && opts.now, redJobs });
|
|
269
|
+
if (r.ok) {
|
|
270
|
+
granted.push({ issue: n, role: REVIEWER_ROLE, reviewer: r.grant.reviewer, head: r.grant.head,
|
|
271
|
+
branch: r.grant.branch, by: r.grant.login, at: r.grant.at, redSha: r.grant.redSha, evidenceSha: r.grant.head,
|
|
272
|
+
cures: parseCures(r.grant.record.cures) });
|
|
273
|
+
} else {
|
|
274
|
+
missing.push({ issue: n, reason: `reviewer grant: ${r.reason}` });
|
|
275
|
+
}
|
|
250
276
|
}
|
|
251
277
|
return { ok: missing.length === 0, granted, missing };
|
|
252
278
|
}
|
|
@@ -294,14 +320,255 @@ function stackingVerdict({ trunkIsRed, priorGrantMerge, redContinuousSincePriorG
|
|
|
294
320
|
return { ok: false, reason: 'trunk is not currently red โ nothing for a CI grant to exempt' };
|
|
295
321
|
}
|
|
296
322
|
if (priorGrantMerge && redContinuousSincePriorGrant) {
|
|
297
|
-
|
|
323
|
+
// `stacked`/`prior` are additive (#477): the cure rule may lift THIS refusal โ and only this
|
|
324
|
+
// one โ on measured progress (tools/lib/ci-cure.js redSetShrank); the grant CREATE path ignores them.
|
|
325
|
+
return { ok: false, stacked: true, prior: priorGrantMerge, reason: `a CI grant already merged ${priorGrantMerge.sha} against this red trunk and trunk has been red ever since โ a second exemption is how a permanently broken repo ships anyway. Revert the bad merge or fix trunk by hand instead of granting again.` };
|
|
298
326
|
}
|
|
299
327
|
return { ok: true, reason: '' };
|
|
300
328
|
}
|
|
301
329
|
|
|
330
|
+
// ============================================================================================
|
|
331
|
+
// THE REVIEWER ROLE (#504) โ `colab ci-grant <N> --role ci-reviewer`.
|
|
332
|
+
//
|
|
333
|
+
// Maintainer ruling 2026-10-05: the coordinator agent owns a red trunk end to end, including this
|
|
334
|
+
// exemption, where the cure rule (tools/lib/ci-cure.js) still refuses. Mirrors the reviewer
|
|
335
|
+
// migration grant (#397, #401): a declared reviewer, a review record, bound to ONE HEAD โ and, like
|
|
336
|
+
// every CI grant, to ONE red trunk sha. Unlike the migration reviewer it is minted WITHOUT
|
|
337
|
+
// COLAB_HUMAN=1, and only because the repo opted in on trunk (`ci-grant: reviewer`). Everything it
|
|
338
|
+
// relies on is MEASURED by the reader, never taken from the record:
|
|
339
|
+
// - the issue is open, labelled, and titled `TRUNK RED:` (the work is the red trunk's repair);
|
|
340
|
+
// - trunk is still at the red sha the review names;
|
|
341
|
+
// - the branch's own CI is green at the exact HEAD the review names;
|
|
342
|
+
// - every check the record claims to cure is red on trunk at that sha;
|
|
343
|
+
// - a host-imposed revoke window (`not-before`) has passed.
|
|
344
|
+
// Never-stacks is a MINT-time guard (stackingVerdict, as for the human grant): once any exemption
|
|
345
|
+
// merges, trunk's head moves, and a grant bound to the old red sha is dead.
|
|
346
|
+
//
|
|
347
|
+
// THE REVIEWER IDENTITY IS DECLARED, NOT ATTESTED โ same caveat as the migration reviewer. The
|
|
348
|
+
// anti-forgery properties are the label (write/triage permission) and TRUSTED_ASSOCIATIONS on read.
|
|
349
|
+
// ============================================================================================
|
|
350
|
+
|
|
351
|
+
const REVIEW_GRANT_MARK = codec.CI_REVIEW_GRANT_MARK;
|
|
352
|
+
const REVIEW_GRANT_RE = codec.CI_REVIEW_GRANT_RE;
|
|
353
|
+
const REVIEWER_ROLE = codec.CI_REVIEWER_ROLE;
|
|
354
|
+
const GRANT_ROLES = Object.freeze(['human', REVIEWER_ROLE]);
|
|
355
|
+
const REVIEW_RECORD_FIELDS = codec.CI_REVIEW_RECORD_FIELDS;
|
|
356
|
+
const REVIEW_RECORD_KEYS = new Set(REVIEW_RECORD_FIELDS.map((f) => f.key));
|
|
357
|
+
/** The issue-title prefix a reviewer grant requires: the branch's work IS the red trunk's repair. */
|
|
358
|
+
const TRUNK_RED_TITLE_PREFIX = 'TRUNK RED:';
|
|
359
|
+
/** `ci-grant:` values in project.yml (#504). Absent = human, the behaviour before #504. */
|
|
360
|
+
const GRANT_POLICIES = Object.freeze(['human', 'reviewer']);
|
|
361
|
+
|
|
362
|
+
/**
|
|
363
|
+
* `ci-grant:` from a parsed project.yml โ { policy, declared, valid, reason }. Same shape and the same
|
|
364
|
+
* fail-safe posture as migration-grant.js's parseGrantPolicy: an invalid value reads as `human` (the
|
|
365
|
+
* stricter reading) with `valid: false`, so the audit fails it.
|
|
366
|
+
*/
|
|
367
|
+
function parseGrantPolicy(doc) {
|
|
368
|
+
const has = !!doc && Object.prototype.hasOwnProperty.call(doc, 'ci-grant');
|
|
369
|
+
const raw = has ? doc['ci-grant'] : undefined;
|
|
370
|
+
if (!has || raw === null || raw === undefined) {
|
|
371
|
+
return { policy: 'human', declared: false, valid: true, reason: 'ci-grant absent โ human grants only' };
|
|
372
|
+
}
|
|
373
|
+
const v = typeof raw === 'string' ? raw.trim() : raw;
|
|
374
|
+
if (typeof v === 'string' && GRANT_POLICIES.includes(v)) {
|
|
375
|
+
return { policy: v, declared: true, valid: true, reason: `ci-grant: ${v}` };
|
|
376
|
+
}
|
|
377
|
+
return { policy: 'human', declared: true, valid: false,
|
|
378
|
+
reason: `ci-grant is ${JSON.stringify(raw)}, expected ${GRANT_POLICIES.join(' | ')} (omit for human)` };
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
/** The `cures:` value โ a list of check names, trimmed, empties dropped. */
|
|
382
|
+
function parseCures(value) {
|
|
383
|
+
return String(value == null ? '' : value).split(codec.CI_CURES_SEPARATOR).map((x) => x.trim()).filter(Boolean);
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
/** A list of check names โ the `cures:` value. */
|
|
387
|
+
function formatCures(list) {
|
|
388
|
+
return (Array.isArray(list) ? list : []).map((x) => String(x).trim()).filter(Boolean).join(`${codec.CI_CURES_SEPARATOR} `);
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
/**
|
|
392
|
+
* Validate a `ci-review` record โ from a parsed comment or from CLI flags, the SAME function for
|
|
393
|
+
* both. `marker` (optional) is the parsed first line; given, its head/reviewer/red/role must agree
|
|
394
|
+
* with the record. Returns { valid, passing, problems }; PASSING = valid AND `verdict: pass`.
|
|
395
|
+
*/
|
|
396
|
+
function validateReviewRecord(rec, marker) {
|
|
397
|
+
const problems = [];
|
|
398
|
+
const r = rec && typeof rec === 'object' ? rec : {};
|
|
399
|
+
for (const k of Object.keys(r)) {
|
|
400
|
+
if (!REVIEW_RECORD_KEYS.has(k)) problems.push(`unknown key "${k}" โ a v${codec.CI_REVIEW_RECORD_VERSION} ci-review record has no such field`);
|
|
401
|
+
}
|
|
402
|
+
for (const f of REVIEW_RECORD_FIELDS) {
|
|
403
|
+
const has = Object.prototype.hasOwnProperty.call(r, f.key) && r[f.key] !== undefined && r[f.key] !== null && String(r[f.key]) !== '';
|
|
404
|
+
if (!has) {
|
|
405
|
+
if (f.required) problems.push(`missing "${f.key}"`);
|
|
406
|
+
continue;
|
|
407
|
+
}
|
|
408
|
+
const v = String(r[f.key]);
|
|
409
|
+
if (f.values && !f.values.includes(v)) problems.push(`"${f.key}" is ${JSON.stringify(v)}, expected ${f.values.join(' | ')}`);
|
|
410
|
+
if (f.re && !f.re.test(v)) problems.push(`"${f.key}" is ${JSON.stringify(v)}, expected ${f.hint}`);
|
|
411
|
+
}
|
|
412
|
+
if (r['not-before'] && Number.isNaN(Date.parse(r['not-before']))) problems.push(`"not-before" is ${JSON.stringify(r['not-before'])}, not a parseable instant`);
|
|
413
|
+
if (marker) {
|
|
414
|
+
if (r.head && marker.head !== r.head) problems.push(`record head ${String(r.head).slice(0, 7)} differs from the marker's head ${String(marker.head).slice(0, 7)}`);
|
|
415
|
+
if (r.red && marker.redSha !== r.red) problems.push(`record red ${String(r.red).slice(0, 7)} differs from the marker's red ${String(marker.redSha).slice(0, 7)}`);
|
|
416
|
+
if (r.reviewer && marker.reviewer !== r.reviewer) problems.push(`record reviewer "${r.reviewer}" differs from the marker's reviewer "${marker.reviewer}"`);
|
|
417
|
+
if (marker.role !== REVIEWER_ROLE) problems.push(`marker role is "${marker.role}", expected "${REVIEWER_ROLE}"`);
|
|
418
|
+
}
|
|
419
|
+
const valid = problems.length === 0;
|
|
420
|
+
return { valid, passing: valid && r.verdict === 'pass', problems };
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
/** The exact reviewer-grant comment body. Only v1 fields are written. The caller validates `rec`
|
|
424
|
+
* (validateReviewRecord) BEFORE calling this. */
|
|
425
|
+
function reviewGrantCommentBody(branch, trunk, host, iso, rec) {
|
|
426
|
+
const record = {};
|
|
427
|
+
for (const f of REVIEW_RECORD_FIELDS) if (Object.prototype.hasOwnProperty.call(rec, f.key)) record[f.key] = rec[f.key];
|
|
428
|
+
return codec.encodeCiReviewGrant({ role: rec.role, reviewer: rec.reviewer, branch, head: rec.head,
|
|
429
|
+
trunk, redSha: rec.red, host, at: iso, record });
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
/** A reviewer-grant comment โ { marker, record, problems } or null. Syntax from the codec, values
|
|
433
|
+
* from validateReviewRecord. */
|
|
434
|
+
function parseReviewGrant(body) {
|
|
435
|
+
const d = codec.decodeCiReviewGrant(body);
|
|
436
|
+
if (!d) return null;
|
|
437
|
+
const marker = { role: d.role, reviewer: d.reviewer, branch: d.branch, head: d.head, trunk: d.trunk,
|
|
438
|
+
redSha: d.redSha, host: d.host, at: d.at };
|
|
439
|
+
if (!d.record) return { marker, record: null, problems: d.problems };
|
|
440
|
+
const v = validateReviewRecord(d.record, marker);
|
|
441
|
+
return { marker, record: d.record, problems: [...d.problems, ...v.problems] };
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
/**
|
|
445
|
+
* Every live grant of EVERY role โ human ones as liveGrants() reads them, plus reviewer grants โ
|
|
446
|
+
* after the same revoke rule (a revoke cancels every earlier grant, whichever role, whoever posted
|
|
447
|
+
* it). Oldest-first. Human entries carry role 'human' and liveGrants()'s fields; reviewer entries
|
|
448
|
+
* carry { role, reviewer, branch, head, trunk, redSha, record, problems, valid, passing }.
|
|
449
|
+
*/
|
|
450
|
+
function liveGrantRecords(comments) {
|
|
451
|
+
const list = Array.isArray(comments) ? comments : [];
|
|
452
|
+
const sorted = [...list].sort((a, b) => (a.createdAt < b.createdAt ? -1 : a.createdAt > b.createdAt ? 1 : 0));
|
|
453
|
+
let lastRevokeAt = null;
|
|
454
|
+
for (const c of sorted) {
|
|
455
|
+
if (REVOKE_RE.test(String(c.body || '').trim())) {
|
|
456
|
+
if (lastRevokeAt === null || c.createdAt > lastRevokeAt) lastRevokeAt = c.createdAt;
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
const out = [];
|
|
460
|
+
for (const c of sorted) {
|
|
461
|
+
const at = c.createdAt;
|
|
462
|
+
if (lastRevokeAt !== null && lastRevokeAt > at) continue;
|
|
463
|
+
const body = String(c.body || '').trim();
|
|
464
|
+
const base = { at, login: (c.author && c.author.login) || '', authorAssociation: c.authorAssociation || '' };
|
|
465
|
+
const h = body.match(GRANT_RE);
|
|
466
|
+
if (h) {
|
|
467
|
+
out.push({ role: 'human', branch: h[1], trunk: h[2], redSha: h[3], evidenceSha: h[4], host: h[5], ...base });
|
|
468
|
+
continue;
|
|
469
|
+
}
|
|
470
|
+
const r = parseReviewGrant(body);
|
|
471
|
+
if (r) {
|
|
472
|
+
const v = r.record ? validateReviewRecord(r.record, r.marker) : { valid: false, passing: false };
|
|
473
|
+
out.push({ role: r.marker.role, reviewer: r.marker.reviewer, branch: r.marker.branch, head: r.marker.head,
|
|
474
|
+
trunk: r.marker.trunk, redSha: r.marker.redSha, host: r.marker.host, ...base,
|
|
475
|
+
record: r.record, problems: r.problems,
|
|
476
|
+
valid: r.problems.length === 0 && v.valid, passing: r.problems.length === 0 && v.passing });
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
return out;
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
/** The label a check is named by in `cures:` and in reasons โ `workflow / job`, or the bare job
|
|
483
|
+
* name when the workflow is unknown (tools/lib/ci-cure.js jobLabel). */
|
|
484
|
+
function checkLabel(j) {
|
|
485
|
+
return j && j.workflowName ? `${j.workflowName} / ${j.name}` : String((j && j.name) || '');
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
/**
|
|
489
|
+
* Which claimed cures are NOT red on trunk. `redJobs` is ci-cure.js redJobSet's `[{name,
|
|
490
|
+
* workflowName}]` at the red sha, or null when it could not be measured. A claimed name matches a red
|
|
491
|
+
* job by its full `workflow / job` label, or by its bare job name when exactly one red job carries
|
|
492
|
+
* it (an ambiguous bare name matches nothing โ never a guess). Returns { ok, unmatched, reason }.
|
|
493
|
+
*/
|
|
494
|
+
function curesAreRed(cures, redJobs) {
|
|
495
|
+
if (!Array.isArray(redJobs)) {
|
|
496
|
+
return { ok: false, unmatched: [], reason: 'trunk\'s red checks at that sha could not be measured โ an unmeasured red set never confirms a cure' };
|
|
497
|
+
}
|
|
498
|
+
const list = Array.isArray(cures) ? cures : [];
|
|
499
|
+
if (list.length === 0) return { ok: false, unmatched: [], reason: 'the review names no red check it cures' };
|
|
500
|
+
const labelsSet = new Set(redJobs.map(checkLabel));
|
|
501
|
+
const byName = new Map();
|
|
502
|
+
for (const j of redJobs) byName.set(j.name, (byName.get(j.name) || 0) + 1);
|
|
503
|
+
const unmatched = list.filter((c) => !labelsSet.has(c) && byName.get(c) !== 1);
|
|
504
|
+
if (unmatched.length) {
|
|
505
|
+
const red = redJobs.length ? redJobs.map((j) => `\`${checkLabel(j)}\``).join(', ') : 'none';
|
|
506
|
+
return { ok: false, unmatched,
|
|
507
|
+
reason: `the review claims to cure ${unmatched.map((c) => `\`${c}\``).join(', ')}, which ${unmatched.length === 1 ? 'is' : 'are'} not red on trunk at that sha (red: ${red})` };
|
|
508
|
+
}
|
|
509
|
+
return { ok: true, unmatched: [], reason: '' };
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
function titleIsTrunkRed(title) {
|
|
513
|
+
return String(title || '').trimStart().startsWith(TRUNK_RED_TITLE_PREFIX);
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
/**
|
|
517
|
+
* The reviewer-grant verdict for one issue on a ship. `ctx` = { branch, trunk, redTrunkSha, evidence,
|
|
518
|
+
* issueNum, labelName, policy, now, redJobs } where `evidence` is `{ok, sha}` for the branch's CURRENT
|
|
519
|
+
* remote head (or null on a failed read), `now` is an ISO instant or ms (absent = Date.now()), and
|
|
520
|
+
* `redJobs` is a function returning the red-job set at `redTrunkSha` (or null) โ called only once
|
|
521
|
+
* everything cheaper has passed. Checks, cheapest first, each with its own reason. `record` must be a
|
|
522
|
+
* ghIssueView result carrying `title`. Returns { ok, grant, reason }.
|
|
523
|
+
*/
|
|
524
|
+
function evaluateReviewerIssue(record, ctx) {
|
|
525
|
+
const c = ctx || {};
|
|
526
|
+
const issue = c.issueNum;
|
|
527
|
+
const no = (reason, grant = null) => ({ issue, ok: false, grant, reason });
|
|
528
|
+
if (!record) return no(`#${issue} could not be read from the tracker โ a failed read is never a grant`);
|
|
529
|
+
if (record.state !== 'OPEN') return no(`#${issue} is ${record.state || 'not open'} โ a grant expires when its issue closes`);
|
|
530
|
+
const labelNames = (record.labels || []).map((l) => (l && typeof l === 'object' ? l.name : l));
|
|
531
|
+
if (!labelNames.includes(c.labelName)) return no(`#${issue} does not carry the \`${c.labelName}\` label`);
|
|
532
|
+
if (c.policy !== 'reviewer') return no(`this repo's ci-grant policy is "${c.policy || 'human'}" โ a reviewer grant is honoured only under ci-grant: reviewer`);
|
|
533
|
+
if (!titleIsTrunkRed(record.title)) {
|
|
534
|
+
return no(`#${issue}'s title does not start "${TRUNK_RED_TITLE_PREFIX}" โ a reviewer CI grant covers only a branch whose work is the red trunk's repair`);
|
|
535
|
+
}
|
|
536
|
+
const reviewer = liveGrantRecords(record.comments).filter((g) => g.role !== 'human');
|
|
537
|
+
if (reviewer.length === 0) return no(`#${issue} has no live reviewer grant (revoked, or never posted)`);
|
|
538
|
+
const g = reviewer[reviewer.length - 1];
|
|
539
|
+
if (g.branch !== c.branch) return no(`#${issue}'s reviewer grant is bound to branch "${g.branch}", not "${c.branch}"`, g);
|
|
540
|
+
if (!TRUSTED_ASSOCIATIONS.has(g.authorAssociation)) {
|
|
541
|
+
return no(`#${issue}'s reviewer grant was posted by ${g.login || '(unknown)'} (${g.authorAssociation || 'unknown association'}) โ not a repo owner/member/collaborator`, g);
|
|
542
|
+
}
|
|
543
|
+
if (!g.valid) return no(`#${issue}'s reviewer grant has an invalid review record: ${(g.problems || []).join('; ') || 'unreadable'}`, g);
|
|
544
|
+
if (!g.passing) return no(`#${issue}'s review record says verdict ${g.record && g.record.verdict} โ only a pass is a grant`, g);
|
|
545
|
+
if (g.trunk !== c.trunk || g.redSha !== c.redTrunkSha) {
|
|
546
|
+
return no(`#${issue}'s reviewer grant was reviewed against \`${g.trunk}\`@\`${String(g.redSha).slice(0, 7)}\`, not the current \`${c.trunk}\`@\`${String(c.redTrunkSha || '').slice(0, 7)}\` โ trunk moved since the review`, g);
|
|
547
|
+
}
|
|
548
|
+
const nb = g.record['not-before'];
|
|
549
|
+
if (nb) {
|
|
550
|
+
const now = c.now === undefined ? Date.now() : (typeof c.now === 'number' ? c.now : Date.parse(c.now));
|
|
551
|
+
if (!(now >= Date.parse(nb))) return no(`#${issue}'s reviewer grant is not yet usable โ its revoke window runs until ${nb}`, g);
|
|
552
|
+
}
|
|
553
|
+
if (!c.evidence) return no(`#${issue}'s reviewer grant could not be checked against the branch's current CI run โ a failed evidence read is never a grant`, g);
|
|
554
|
+
if (!c.evidence.ok) return no(`#${issue}'s reviewer grant requires a completed, successful CI run on \`${c.branch}\`'s current head โ none exists`, g);
|
|
555
|
+
if (String(c.evidence.sha || '').toLowerCase() !== String(g.head).toLowerCase()) {
|
|
556
|
+
return no(`#${issue}'s reviewer grant is bound to ${String(g.head).slice(0, 7)}, \`${c.branch}\` is at ${String(c.evidence.sha || '?').slice(0, 7)} โ a new commit voids it`, g);
|
|
557
|
+
}
|
|
558
|
+
let redJobs = null;
|
|
559
|
+
try { redJobs = typeof c.redJobs === 'function' ? c.redJobs() : (c.redJobs === undefined ? null : c.redJobs); } catch (_) { redJobs = null; }
|
|
560
|
+
const cr = curesAreRed(parseCures(g.record.cures), redJobs);
|
|
561
|
+
if (!cr.ok) return no(`#${issue}: ${cr.reason}`, g);
|
|
562
|
+
return { issue, ok: true, grant: g, reason: '' };
|
|
563
|
+
}
|
|
564
|
+
|
|
302
565
|
module.exports = {
|
|
303
566
|
GRANT_MARK, REVOKE_MARK, GRANT_RE, REVOKE_RE,
|
|
304
567
|
grantCommentBody, revokeCommentBody,
|
|
305
568
|
liveGrants, TRUSTED_ASSOCIATIONS,
|
|
306
569
|
evaluateIssue, evaluateShipSet, stackingVerdict, wentGreenSince,
|
|
570
|
+
// #504 โ the reviewer role
|
|
571
|
+
REVIEW_GRANT_MARK, REVIEW_GRANT_RE, REVIEWER_ROLE, GRANT_ROLES, REVIEW_RECORD_FIELDS, TRUNK_RED_TITLE_PREFIX,
|
|
572
|
+
GRANT_POLICIES, parseGrantPolicy, parseCures, formatCures, validateReviewRecord, reviewGrantCommentBody,
|
|
573
|
+
parseReviewGrant, liveGrantRecords, checkLabel, curesAreRed, titleIsTrunkRed, evaluateReviewerIssue,
|
|
307
574
|
};
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
/**
|
|
3
|
+
* #495 โ one CI-wait primitive, so no agent hand-rolls a `sleep N; gh run โฆ` loop again.
|
|
4
|
+
*
|
|
5
|
+
* Measured over one hour on one fleet: ~88% of ~4,500 REST calls on a shared agent identity were
|
|
6
|
+
* agents waiting for CI in their own shell loops โ `sleep 5`โ`sleep 20` around `gh run view` /
|
|
7
|
+
* `gh run list` / `colab trunk-ci`, two loops on the same run, one orphaned loop polling for 5ยฝ h
|
|
8
|
+
* with its stderr thrown away, and a loop that read a rate-limit error as "keep waiting". The quota
|
|
9
|
+
* (5,000/h) ran out and every agent's `gh` call failed for the rest of the hour.
|
|
10
|
+
*
|
|
11
|
+
* What this module fixes, by construction:
|
|
12
|
+
* - backoff, not a fixed interval: 30 s โ 60 s โ 120 s, then 120 s until a deadline. A 15-minute
|
|
13
|
+
* run costs ~10 polls instead of ~180 at `sleep 5`;
|
|
14
|
+
* - conditional requests: every poll after the first sends `If-None-Match`, and a `304 Not
|
|
15
|
+
* Modified` is not counted against the primary rate limit (GitHub REST docs, "conditional
|
|
16
|
+
* requests") โ capped (#505): after two 304s in a row, and on the deadline's poll, it re-reads
|
|
17
|
+
* unconditionally, because a validator that never changes would otherwise pin a stale state;
|
|
18
|
+
* - a rate limit (403 with remaining 0, or 429) ENDS the wait with its own outcome โ never a retry;
|
|
19
|
+
* - an unreadable or unrecognised state ends it too (UNKNOWN), never "keep waiting";
|
|
20
|
+
* - one wait per run per checkout: a second waiter on the same key is refused (ALREADY_WAITING).
|
|
21
|
+
*
|
|
22
|
+
* The loop is pure over injected `poll` / `sleep` / `now`, so the cost of a 15-minute wait is a
|
|
23
|
+
* unit test, not a guess. The `gh` transport lives in git.js (`ghApiConditional`).
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
const fs = require('fs');
|
|
27
|
+
const path = require('path');
|
|
28
|
+
|
|
29
|
+
/** Exit codes of `colab ci-wait` โ one per outcome, so a caller branches on `$?`, never on text. */
|
|
30
|
+
const EXIT = Object.freeze({
|
|
31
|
+
GREEN: 0,
|
|
32
|
+
RED: 1,
|
|
33
|
+
USAGE: 2,
|
|
34
|
+
TIMEOUT: 3,
|
|
35
|
+
RATE_LIMITED: 4,
|
|
36
|
+
UNKNOWN: 5,
|
|
37
|
+
ALREADY_WAITING: 6,
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
const DEFAULT_SCHEDULE_SEC = Object.freeze([30, 60, 120]);
|
|
41
|
+
const DEFAULT_DEADLINE_SEC = 45 * 60;
|
|
42
|
+
|
|
43
|
+
/** Seconds to sleep before poll number `i` (0-based, i โฅ 1); the last step repeats. */
|
|
44
|
+
function delayFor(i, schedule = DEFAULT_SCHEDULE_SEC) {
|
|
45
|
+
if (i <= 0) return 0;
|
|
46
|
+
return schedule[Math.min(i - 1, schedule.length - 1)];
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Parse `gh api -i` stdout: status line, headers, blank line, body. gh prints the head to stdout
|
|
51
|
+
* on a non-2xx too (a 304 exits 1 with `gh: HTTP 304` on stderr โ measured), so this is read
|
|
52
|
+
* whatever the exit code. Returns `{ status, headers, body }`; status null when no head was found.
|
|
53
|
+
*/
|
|
54
|
+
function parseHttp(stdout) {
|
|
55
|
+
const text = String(stdout || '');
|
|
56
|
+
const m = /^HTTP\/[\d.]+\s+(\d{3})[^\n]*\n/.exec(text);
|
|
57
|
+
if (!m) return { status: null, headers: {}, body: text };
|
|
58
|
+
const rest = text.slice(m[0].length);
|
|
59
|
+
const split = rest.search(/\r?\n\r?\n/);
|
|
60
|
+
const head = split === -1 ? rest : rest.slice(0, split);
|
|
61
|
+
const body = split === -1 ? '' : rest.slice(split).replace(/^\r?\n\r?\n/, '');
|
|
62
|
+
const headers = {};
|
|
63
|
+
for (const line of head.split(/\r?\n/)) {
|
|
64
|
+
const i = line.indexOf(':');
|
|
65
|
+
if (i > 0) headers[line.slice(0, i).trim().toLowerCase()] = line.slice(i + 1).trim();
|
|
66
|
+
}
|
|
67
|
+
return { status: Number(m[1]), headers, body };
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Classify one response: `ok` (2xx, body parsed) ยท `not-modified` (304) ยท `rate-limited` (429, or
|
|
72
|
+
* 403 with `x-ratelimit-remaining: 0`, or gh's own "rate limit" text) ยท `error` (anything else).
|
|
73
|
+
*/
|
|
74
|
+
function classifyResponse({ status, headers = {}, body, stderr = '' }) {
|
|
75
|
+
const remaining = headers['x-ratelimit-remaining'];
|
|
76
|
+
const resetAt = headers['x-ratelimit-reset'] ? Number(headers['x-ratelimit-reset']) * 1000 : null;
|
|
77
|
+
if (status === 429 || (status === 403 && (remaining === '0' || /rate limit/i.test(String(body) + stderr)))
|
|
78
|
+
|| (status === null && /rate limit/i.test(stderr))) {
|
|
79
|
+
return { kind: 'rate-limited', status, resetAt, detail: firstLine(stderr) || `HTTP ${status}` };
|
|
80
|
+
}
|
|
81
|
+
if (status === 304) return { kind: 'not-modified', status, etag: headers.etag || null };
|
|
82
|
+
if (status !== null && status >= 200 && status < 300) {
|
|
83
|
+
let json;
|
|
84
|
+
try { json = JSON.parse(body); } catch (_) { return { kind: 'error', status, detail: 'unparseable body' }; }
|
|
85
|
+
return { kind: 'ok', status, etag: headers.etag || null, json };
|
|
86
|
+
}
|
|
87
|
+
return { kind: 'error', status, detail: firstLine(stderr) || (status ? `HTTP ${status}` : 'no response') };
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function firstLine(s) { return String(s || '').split('\n').map((x) => x.trim()).find(Boolean) || ''; }
|
|
91
|
+
|
|
92
|
+
/** A REST workflow-run object โ the row shape git.summarizeRunsForCommit reads (`gh run list --json`). */
|
|
93
|
+
function restRow(x) {
|
|
94
|
+
return {
|
|
95
|
+
headSha: x.head_sha, status: x.status, conclusion: x.conclusion || null,
|
|
96
|
+
createdAt: x.created_at || null, databaseId: x.id, workflowName: x.name || null,
|
|
97
|
+
event: x.event || null, url: x.html_url || null,
|
|
98
|
+
// #510: the workflow FILE's id โ the cure rule's same-workflow test, which a display name cannot answer.
|
|
99
|
+
workflowId: x.workflow_id ?? null,
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* The state of what is being waited on, from a summarized run (`{status, conclusion}`):
|
|
105
|
+
* `green` ยท `red` ยท `pending` ยท `unknown`. `none` (no run at the sha yet) is pending: runs appear
|
|
106
|
+
* seconds after a push, and the deadline bounds the wait if they never do.
|
|
107
|
+
*/
|
|
108
|
+
function runState(s) {
|
|
109
|
+
if (!s) return 'unknown';
|
|
110
|
+
if (s.status === 'none') return 'pending';
|
|
111
|
+
if (s.status === 'completed') return s.conclusion === 'success' ? 'green' : 'red';
|
|
112
|
+
if (['queued', 'in_progress', 'waiting', 'requested', 'pending'].includes(s.status)) return 'pending';
|
|
113
|
+
return 'unknown';
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* #505: how many 304s in a row may stand for the state before the next poll re-reads without
|
|
118
|
+
* `If-None-Match`. Measured: the runs-list read kept answering 304 for ten minutes while every run
|
|
119
|
+
* at the sha had completed green โ the validator never changed, so a loop that trusted it would
|
|
120
|
+
* have reported TIMEOUT on a green sha. A cap of 2 bounds that to one paid call per three polls.
|
|
121
|
+
*/
|
|
122
|
+
const DEFAULT_MAX_NOT_MODIFIED = 2;
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* The wait loop. `poll(etag)` returns a classifyResponse() result, plus `state` (runState) and
|
|
126
|
+
* `summary` on `ok`. `sleep(ms)` blocks; `now()` is epoch ms. A 304 keeps the previous state โ but
|
|
127
|
+
* only for `maxNotModified` polls in a row, and never on the last poll before the deadline: those
|
|
128
|
+
* polls send no ETag (`poll(null)`), so a stale validator costs one paid read, not the wait (#505).
|
|
129
|
+
*
|
|
130
|
+
* Returns `{ outcome, polls, notModified, forced, waitedMs, last, detail }`, outcome one of the
|
|
131
|
+
* EXIT keys; `forced` counts the unconditional re-reads #505 added.
|
|
132
|
+
*/
|
|
133
|
+
function waitLoop({ poll, sleep, now = Date.now, deadlineSec = DEFAULT_DEADLINE_SEC,
|
|
134
|
+
schedule = DEFAULT_SCHEDULE_SEC, maxNotModified = DEFAULT_MAX_NOT_MODIFIED, onPoll = () => {} }) {
|
|
135
|
+
const start = now();
|
|
136
|
+
let etag = null;
|
|
137
|
+
let last = null;
|
|
138
|
+
let polls = 0;
|
|
139
|
+
let notModified = 0;
|
|
140
|
+
let streak = 0; // consecutive 304s
|
|
141
|
+
let forced = 0;
|
|
142
|
+
for (let i = 0; ; i++) {
|
|
143
|
+
const d = delayFor(i, schedule) * 1000;
|
|
144
|
+
if (d) {
|
|
145
|
+
const left = start + deadlineSec * 1000 - now();
|
|
146
|
+
if (left <= 0) return done('TIMEOUT', `still ${last ? last.state : 'unread'} at the ${fmtDuration(deadlineSec * 1000)} deadline`);
|
|
147
|
+
sleep(Math.min(d, left));
|
|
148
|
+
}
|
|
149
|
+
// The poll that lands on the deadline is the last one: it must read the truth, not a 304.
|
|
150
|
+
const final = now() - start >= deadlineSec * 1000;
|
|
151
|
+
const force = Boolean(etag) && (streak >= maxNotModified || final);
|
|
152
|
+
if (force) forced++;
|
|
153
|
+
const r = poll(force ? null : etag);
|
|
154
|
+
polls++;
|
|
155
|
+
if (r.kind === 'rate-limited') return done('RATE_LIMITED', r.detail + (r.resetAt ? ` โ quota resets ${new Date(r.resetAt).toISOString()}` : ''), r);
|
|
156
|
+
if (r.kind === 'error') return done('UNKNOWN', `read failed: ${r.detail}`, r);
|
|
157
|
+
if (r.kind === 'not-modified') {
|
|
158
|
+
notModified++;
|
|
159
|
+
streak++;
|
|
160
|
+
if (!last) return done('UNKNOWN', '304 on the first read โ nothing to compare against', r);
|
|
161
|
+
} else {
|
|
162
|
+
streak = 0;
|
|
163
|
+
etag = r.etag || etag;
|
|
164
|
+
last = r;
|
|
165
|
+
}
|
|
166
|
+
onPoll({ poll: polls, state: last.state, notModified: r.kind === 'not-modified', forced: force, elapsedMs: now() - start });
|
|
167
|
+
if (last.state === 'green') return done('GREEN', null);
|
|
168
|
+
if (last.state === 'red') return done('RED', null);
|
|
169
|
+
if (last.state !== 'pending') return done('UNKNOWN', `unrecognised state (${JSON.stringify(last.summary || null)})`);
|
|
170
|
+
if (now() - start >= deadlineSec * 1000) return done('TIMEOUT', `still pending at the ${fmtDuration(deadlineSec * 1000)} deadline`);
|
|
171
|
+
}
|
|
172
|
+
function done(outcome, detail, r) {
|
|
173
|
+
return { outcome, polls, notModified, forced, waitedMs: now() - start, last: last || r || null, detail };
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
function fmtDuration(ms) {
|
|
178
|
+
const s = Math.round(ms / 1000);
|
|
179
|
+
const m = Math.floor(s / 60);
|
|
180
|
+
return m ? `${m}m${String(s % 60).padStart(2, '0')}s` : `${s}s`;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** Parse `--timeout`: `45m`, `90s`, `1h`, or bare seconds. Null when unparseable. */
|
|
184
|
+
function parseDuration(v) {
|
|
185
|
+
const m = /^(\d+)\s*([smh]?)$/.exec(String(v || '').trim());
|
|
186
|
+
if (!m) return null;
|
|
187
|
+
return Number(m[1]) * ({ '': 1, s: 1, m: 60, h: 3600 })[m[2]];
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* One wait per key per checkout. The lock is `<dir>/ci-wait-<key>.lock` holding the waiter's pid;
|
|
192
|
+
* a lock whose pid is dead is taken over. Returns `{ ok, holder, release }`.
|
|
193
|
+
*/
|
|
194
|
+
function acquireLock(dir, key, pid = process.pid, alive = pidAlive) {
|
|
195
|
+
const file = path.join(dir, `ci-wait-${String(key).replace(/[^A-Za-z0-9._-]/g, '_')}.lock`);
|
|
196
|
+
try { fs.mkdirSync(dir, { recursive: true }); } catch (_) { /* best effort */ }
|
|
197
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
198
|
+
try {
|
|
199
|
+
fs.writeFileSync(file, String(pid), { flag: 'wx' });
|
|
200
|
+
return { ok: true, file, release: () => { try { fs.unlinkSync(file); } catch (_) {} } };
|
|
201
|
+
} catch (e) {
|
|
202
|
+
if (e.code !== 'EEXIST') return { ok: true, file: null, release: () => {} }; // cannot lock: do not block the wait
|
|
203
|
+
const holder = Number(String(safeRead(file)).trim());
|
|
204
|
+
if (holder && holder !== pid && alive(holder)) return { ok: false, holder, file, release: () => {} };
|
|
205
|
+
try { fs.unlinkSync(file); } catch (_) {}
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
return { ok: true, file: null, release: () => {} };
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
function safeRead(f) { try { return fs.readFileSync(f, 'utf8'); } catch (_) { return ''; } }
|
|
212
|
+
function pidAlive(pid) { try { process.kill(pid, 0); return true; } catch (e) { return e.code === 'EPERM'; } }
|
|
213
|
+
|
|
214
|
+
/** Blocking sleep without a busy loop โ the CLI's main() is synchronous. */
|
|
215
|
+
function sleepSync(ms) {
|
|
216
|
+
if (ms > 0) Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
module.exports = {
|
|
220
|
+
EXIT, DEFAULT_SCHEDULE_SEC, DEFAULT_DEADLINE_SEC, DEFAULT_MAX_NOT_MODIFIED,
|
|
221
|
+
delayFor, parseHttp, classifyResponse, restRow, runState, waitLoop, fmtDuration, parseDuration,
|
|
222
|
+
acquireLock, sleepSync,
|
|
223
|
+
};
|