@defrex/autobuild 1.8.0 → 1.9.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 +1 -1
- package/SPEC.md +92 -11
- package/docs/architecture.md +38 -14
- package/docs/configuration.md +247 -4
- package/docs/dispatcher-hosting.md +4 -0
- package/docs/merge-policy.md +45 -5
- package/docs/operating.md +21 -0
- package/docs/operator-api.md +11 -2
- package/docs/plugin-authoring.md +4 -1
- package/docs/restacking.md +4 -0
- package/docs/setup.md +3 -1
- package/docs/verification.md +7 -6
- package/package.json +4 -3
- package/packages/core/src/cli/attention.ts +3 -0
- package/packages/core/src/cli/dashboard/landing-display.ts +9 -1
- package/packages/core/src/cli/dashboard/model.ts +25 -6
- package/packages/core/src/cli/dashboard/render.ts +2 -2
- package/packages/core/src/cli/dispatch.ts +120 -1
- package/packages/core/src/cli/help.ts +6 -2
- package/packages/core/src/cli/repository-status.ts +66 -1
- package/packages/core/src/cli/status.ts +2 -2
- package/packages/core/src/cli/watch.ts +1074 -627
- package/packages/core/src/config/live.ts +1 -0
- package/packages/core/src/config/load.ts +19 -0
- package/packages/core/src/config/schema.ts +114 -0
- package/packages/core/src/events/catalog.ts +2 -0
- package/packages/core/src/events/payloads.ts +22 -0
- package/packages/core/src/events/policy.ts +9 -0
- package/packages/core/src/events/repository.ts +43 -0
- package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +31 -0
- package/packages/core/src/kernel/auto-merge.ts +33 -0
- package/packages/core/src/kernel/generators/repository-journals.ts +18 -0
- package/packages/core/src/kernel/landing-state.ts +56 -0
- package/packages/core/src/kernel/leaf-restack-base.ts +34 -0
- package/packages/core/src/kernel/leaf-restack-state.ts +1 -29
- package/packages/core/src/kernel/reducer.ts +1 -1
- package/packages/core/src/kernel/ticket-wait.ts +1 -1
- package/packages/core/src/plugin-sdk/index.ts +7 -1
- package/packages/core/src/ports/forge/fake.ts +128 -8
- package/packages/core/src/ports/forge/git-rewrite.ts +34 -3
- package/packages/core/src/ports/forge/github-squash-message.ts +89 -0
- package/packages/core/src/ports/forge/github-transport.ts +30 -0
- package/packages/core/src/ports/forge/github.ts +565 -164
- package/packages/core/src/ports/types.ts +47 -3
- package/packages/core/src/processes/build-execution-state.ts +4 -3
- package/packages/core/src/processes/dispatcher.ts +73 -4
- package/packages/core/src/processes/execution-no-progress.ts +2 -0
- package/packages/core/src/processes/hook-command.ts +125 -0
- package/packages/core/src/processes/hook-webhook.ts +144 -0
- package/packages/core/src/processes/hooks.ts +740 -0
- package/packages/core/src/store/contract.ts +28 -0
- package/packages/core/src/store/reducer-value-shapes.json +3729 -3297
- package/packages/core/src/store/remote/released-clients.json +22 -0
- package/packages/core/src/store/remote/released-reducer-values/1.9.0.json +29475 -0
- package/packages/core/src/store/remote/released-reducer-values/index.ts +2 -0
- package/packages/core/src/store/repo-state-events.ts +3 -0
- package/packages/core/src/store/retention.ts +16 -2
- package/packages/core/src/testing/index.ts +1 -0
- package/packages/core/src/testing/reduced-read-budget.ts +476 -1
- package/skills/guide/SKILL.md +81 -6
- package/skills/guide/references/merge-policy.md +45 -5
- package/skills/guide/references/operator-api.md +11 -2
- package/skills/guide/references/plugin-authoring.md +4 -1
- package/skills/guide/references/restacking.md +4 -0
- package/skills/guide/references/setup.md +3 -1
- package/skills/operate/SKILL.md +24 -4
- package/templates/hosted-service/package.json +2 -2
|
@@ -2,7 +2,7 @@ import type { SelectedAccount } from '../config/accounts'
|
|
|
2
2
|
export type { ForgeReadinessCheck, ForgeReadinessInput } from './forge/readiness'
|
|
3
3
|
import type { ForgeReadinessCheck, ForgeReadinessInput } from './forge/readiness'
|
|
4
4
|
import type { BuildStore } from '../store/types'
|
|
5
|
-
import { ForgeRejection } from './forge-failure'
|
|
5
|
+
import { ForgeRejection, isForgeRejection } from './forge-failure'
|
|
6
6
|
/**
|
|
7
7
|
* Ports (SPEC §3.2): interfaces to the world, each with swappable adapters.
|
|
8
8
|
* The kernel and processes depend only on these types; adapters live in
|
|
@@ -674,6 +674,19 @@ export type AutoMergeResult =
|
|
|
674
674
|
| { kind: 'applied' }
|
|
675
675
|
| { kind: 'ungated'; headSha: string }
|
|
676
676
|
| { kind: 'deferred'; reason?: AutoMergeDeferralReason }
|
|
677
|
+
/** A gated landing the forge cannot arm natively (GitHub GraphQL is
|
|
678
|
+
* unavailable from this environment). The caller lands it by polling:
|
|
679
|
+
* `clear` is true only when the forge reports the PR clear to merge at
|
|
680
|
+
* `headSha`, and then the caller squashes with `requireClearState`. */
|
|
681
|
+
| { kind: 'polling'; headSha: string; clear: boolean; detail: string }
|
|
682
|
+
/** A gated landing that cannot be armed natively and must not be merged
|
|
683
|
+
* by polling, because the base branch requires a merge queue. A human
|
|
684
|
+
* merges it on the forge. */
|
|
685
|
+
| {
|
|
686
|
+
kind: 'human-merge'
|
|
687
|
+
cause: 'merge-queue-rule' | 'merge-queue-activity'
|
|
688
|
+
detail: string
|
|
689
|
+
}
|
|
677
690
|
|
|
678
691
|
/** One explicitly designated image artifact to copy to a review-window host. */
|
|
679
692
|
export interface PrAttachmentUploadRequest {
|
|
@@ -703,14 +716,38 @@ export interface BuildLandingOptions {
|
|
|
703
716
|
buildSlug: string
|
|
704
717
|
/** Optional query hint, verified against the current provider PR base. */
|
|
705
718
|
baseBranch?: string
|
|
706
|
-
/** Refresh durable consent and pipeline eligibility before native mutation
|
|
719
|
+
/** Refresh durable consent and pipeline eligibility before native mutation,
|
|
720
|
+
* and before a `requireClearState` squash. */
|
|
707
721
|
canApply?: () => Promise<boolean>
|
|
722
|
+
/** Durable evidence that this exact candidate already took the polling
|
|
723
|
+
* route: a quiet poll may skip availability and gate probes and answer
|
|
724
|
+
* from the poll's PR read alone while the PR is not clear. */
|
|
725
|
+
polling?: boolean
|
|
726
|
+
/** Squash a gated PR only when a fresh read reports it clear to merge at
|
|
727
|
+
* the expected head; call `canApply` immediately before the merge request,
|
|
728
|
+
* and raise the forge's refusal of that request as a `ForgeRejection`. */
|
|
729
|
+
requireClearState?: boolean
|
|
708
730
|
/** The build's sealed issue links, passed only to a `closesIssues` forge
|
|
709
731
|
* for a leaf aimed at the default branch. The adapter composes them into
|
|
710
732
|
* the landed headline and message with `kernel/issue-keywords`. */
|
|
711
733
|
issueLinks?: readonly IssueLink[]
|
|
712
734
|
}
|
|
713
735
|
|
|
736
|
+
/** A gated squash withheld because the forge reports the base branch merges
|
|
737
|
+
* through a merge queue, which a squash request cannot enter. The polling
|
|
738
|
+
* route settles it as awaiting a human merge, like any refused merge. */
|
|
739
|
+
export class ForgeMergeQueueRejection extends ForgeRejection {
|
|
740
|
+
readonly mergeQueue = true as const
|
|
741
|
+
constructor(message: string, rejection: { forge: string; forgeMessage: string }) {
|
|
742
|
+
super(message, { forge: rejection.forge, status: 405, forgeMessage: rejection.forgeMessage })
|
|
743
|
+
this.name = 'ForgeMergeQueueRejection'
|
|
744
|
+
}
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
export function isForgeMergeQueueRejection(error: unknown): error is ForgeMergeQueueRejection {
|
|
748
|
+
return isForgeRejection(error) && (error as { mergeQueue?: unknown }).mergeQueue === true
|
|
749
|
+
}
|
|
750
|
+
|
|
714
751
|
/** GitHub's "No commits between" 422: a forge rejection the empty-node path
|
|
715
752
|
* recognizes by class. */
|
|
716
753
|
export class NoCommitsBetweenBranchesError extends ForgeRejection {
|
|
@@ -884,7 +921,10 @@ export interface Forge {
|
|
|
884
921
|
* is idempotent and safe to retry across the forge-call/event-append crash window.
|
|
885
922
|
* With options it is also called on every eligible poll while a request is
|
|
886
923
|
* armed: a matching request returns `applied` without mutation, and any
|
|
887
|
-
* repair calls `options.canApply` first.
|
|
924
|
+
* repair calls `options.canApply` first. A gated landing that cannot be
|
|
925
|
+
* armed natively returns `polling` (the caller squashes once it is clear)
|
|
926
|
+
* or `human-merge` (the base requires a merge queue); neither calls
|
|
927
|
+
* `options.canApply`.
|
|
888
928
|
*/
|
|
889
929
|
setAutoMerge(
|
|
890
930
|
workspacePath: string,
|
|
@@ -895,6 +935,10 @@ export interface Forge {
|
|
|
895
935
|
/**
|
|
896
936
|
* Perform a normal squash merge, guarded by the inspected PR head. This is
|
|
897
937
|
* never an admin/force operation: forge-side protection still applies.
|
|
938
|
+
* With `options.requireClearState` it is the polling route's gated squash:
|
|
939
|
+
* it re-reads the PR, refuses unless the forge reports it clear at the
|
|
940
|
+
* expected head, rechecks `options.canApply`, and raises the forge's
|
|
941
|
+
* refusal of the merge request as a `ForgeRejection`.
|
|
898
942
|
*/
|
|
899
943
|
squashMerge(
|
|
900
944
|
workspacePath: string,
|
|
@@ -20,11 +20,12 @@ export interface BuildRunnerDiagnostic {
|
|
|
20
20
|
|
|
21
21
|
/** JSON form of the normalized config's strict declarative input shape. */
|
|
22
22
|
export function effectiveBuildConfigContent(config: Config): string {
|
|
23
|
-
const { verify, finalize, profiles, ...root } = config
|
|
23
|
+
const { verify, finalize, profiles, hooks, ...root } = config
|
|
24
24
|
return JSON.stringify({
|
|
25
25
|
...root,
|
|
26
|
-
// Omitted when empty so repositories without profiles keep
|
|
27
|
-
// artifacts that an older client's strict root parse still accepts.
|
|
26
|
+
// Omitted when empty so repositories without profiles or hooks keep
|
|
27
|
+
// byte-identical artifacts that an older client's strict root parse still accepts.
|
|
28
|
+
...(hooks !== undefined && Object.keys(hooks).length > 0 ? { hooks } : {}),
|
|
28
29
|
...(profiles !== undefined && Object.keys(profiles).length > 0 ? { profiles } : {}),
|
|
29
30
|
verify: {
|
|
30
31
|
steps: verify.stages ?? verify.steps,
|
|
@@ -74,7 +74,7 @@ import {
|
|
|
74
74
|
type JanitorOperation,
|
|
75
75
|
} from '../kernel/janitor-failure'
|
|
76
76
|
import { KernelGitUnavailable, kernelGitUnavailableDetail } from '../kernel/kernel-git'
|
|
77
|
-
import { isForgeFailure } from '../ports/forge-failure'
|
|
77
|
+
import { isForgeFailure, isForgeRejection } from '../ports/forge-failure'
|
|
78
78
|
import {
|
|
79
79
|
ForgeRequestDeferred,
|
|
80
80
|
withForgeRequestContext,
|
|
@@ -103,6 +103,7 @@ import { changeBlockers } from '../ports/tickets/operations'
|
|
|
103
103
|
import { evaluateLandingPolicy } from '../kernel/landing-policy'
|
|
104
104
|
import { landingPolicyIdentity } from '../kernel/landing-policy-identity'
|
|
105
105
|
import {
|
|
106
|
+
currentLandingFallback,
|
|
106
107
|
landingAuthorized,
|
|
107
108
|
nativeLandingApplied,
|
|
108
109
|
sameLandingCandidate,
|
|
@@ -232,7 +233,11 @@ import type {
|
|
|
232
233
|
WorkspaceProvider,
|
|
233
234
|
WorkspaceProvisionResult,
|
|
234
235
|
} from '../ports/types'
|
|
235
|
-
import {
|
|
236
|
+
import {
|
|
237
|
+
isForgeMergeQueueRejection,
|
|
238
|
+
NoCommitsBetweenBranchesError,
|
|
239
|
+
TicketSourceRateLimitError,
|
|
240
|
+
} from '../ports/types'
|
|
236
241
|
import { issueLinksForForge } from '../kernel/issue-keywords'
|
|
237
242
|
import {
|
|
238
243
|
contributedIssueLinks,
|
|
@@ -4277,15 +4282,27 @@ export class Dispatcher {
|
|
|
4277
4282
|
prState.nativeAutoMerge === true &&
|
|
4278
4283
|
!nativeCancelled &&
|
|
4279
4284
|
isReady
|
|
4285
|
+
// A landing that cannot be armed natively lands by polling; a quiet
|
|
4286
|
+
// polling tick needs no consent read, because the forge answers from the
|
|
4287
|
+
// poll's PR read and consent is rechecked before any merge. A landing
|
|
4288
|
+
// settled as awaiting a human merge makes no landing call at all; the PR
|
|
4289
|
+
// read above still records the human's merge.
|
|
4290
|
+
const fallback = currentLandingFallback(state.landing)
|
|
4291
|
+
const polling =
|
|
4292
|
+
fallback?.mode === 'polling' &&
|
|
4293
|
+
prState.state === 'open' &&
|
|
4294
|
+
prState.nativeAutoMerge !== true &&
|
|
4295
|
+
isReady
|
|
4280
4296
|
if (
|
|
4281
4297
|
!integration &&
|
|
4282
4298
|
!nodeTarget &&
|
|
4283
4299
|
prState.state === 'open' &&
|
|
4284
4300
|
landingAuthorized(state.landing) &&
|
|
4301
|
+
fallback?.mode !== 'human-merge' &&
|
|
4285
4302
|
(prState.nativeAutoMerge === false || !acknowledged || maintain) &&
|
|
4286
4303
|
(!retry || Date.parse(retry.after) <= this.deps.clock().getTime()) &&
|
|
4287
4304
|
commandSeq !== undefined &&
|
|
4288
|
-
(maintain || (await canApply()))
|
|
4305
|
+
(maintain || polling || (await canApply()))
|
|
4289
4306
|
) {
|
|
4290
4307
|
const decision = state.landing!.decision!
|
|
4291
4308
|
// The provider checks eligibility immediately before mutating. Inspection
|
|
@@ -4323,6 +4340,7 @@ export class Dispatcher {
|
|
|
4323
4340
|
buildSlug: record.slug,
|
|
4324
4341
|
baseBranch: state.baseBranch ?? this.deps.config.baseBranch,
|
|
4325
4342
|
...issueLinksForForge(state, forge),
|
|
4343
|
+
...(polling ? { polling: true } : {}),
|
|
4326
4344
|
canApply: async () => {
|
|
4327
4345
|
if (!(await canApply())) return false
|
|
4328
4346
|
if (enableSeq === undefined)
|
|
@@ -4363,7 +4381,58 @@ export class Dispatcher {
|
|
|
4363
4381
|
await settleFailedEnable()
|
|
4364
4382
|
throw error
|
|
4365
4383
|
})
|
|
4366
|
-
|
|
4384
|
+
const fallbackFact = {
|
|
4385
|
+
candidate: decision.candidate,
|
|
4386
|
+
decisionSeq: decision.seq,
|
|
4387
|
+
...(state.landing?.command ? { commandSeq: state.landing.command.seq } : {}),
|
|
4388
|
+
}
|
|
4389
|
+
const requireHumanMerge = (
|
|
4390
|
+
cause: EventPayload<'landing.human-merge-required'>['cause'],
|
|
4391
|
+
detail: string,
|
|
4392
|
+
) =>
|
|
4393
|
+
store.append(record.slug, {
|
|
4394
|
+
actor: DISPATCHER,
|
|
4395
|
+
type: 'landing.human-merge-required',
|
|
4396
|
+
payload: { ...fallbackFact, cause, detail },
|
|
4397
|
+
})
|
|
4398
|
+
if (result.kind === 'human-merge') {
|
|
4399
|
+
// Settled once: later ticks make no landing call for this candidate.
|
|
4400
|
+
await requireHumanMerge(result.cause, result.detail)
|
|
4401
|
+
} else if (result.kind === 'polling') {
|
|
4402
|
+
// The forge never called the consent guard, so nothing was mutated.
|
|
4403
|
+
if (fallback?.mode !== 'polling')
|
|
4404
|
+
await store.append(record.slug, {
|
|
4405
|
+
actor: DISPATCHER,
|
|
4406
|
+
type: 'landing.polling-selected',
|
|
4407
|
+
payload: { ...fallbackFact, detail: result.detail },
|
|
4408
|
+
})
|
|
4409
|
+
if (
|
|
4410
|
+
result.clear &&
|
|
4411
|
+
prState.mergeable === true &&
|
|
4412
|
+
result.headSha === decision.candidate.head &&
|
|
4413
|
+
(await canApply())
|
|
4414
|
+
) {
|
|
4415
|
+
try {
|
|
4416
|
+
// Re-reads the PR clear at the candidate head and rechecks
|
|
4417
|
+
// consent immediately before the merge request.
|
|
4418
|
+
await forge.squashMerge(workspacePath, pr.number, decision.candidate.head, {
|
|
4419
|
+
buildSlug: record.slug,
|
|
4420
|
+
baseBranch: state.baseBranch ?? this.deps.config.baseBranch,
|
|
4421
|
+
...issueLinksForForge(state, forge),
|
|
4422
|
+
requireClearState: true,
|
|
4423
|
+
canApply,
|
|
4424
|
+
})
|
|
4425
|
+
} catch (error) {
|
|
4426
|
+
// Only the forge refusing a merge it reported clear settles;
|
|
4427
|
+
// pre-merge checks throw ordinary errors and poll again.
|
|
4428
|
+
if (!isForgeRejection(error)) throw error
|
|
4429
|
+
await requireHumanMerge(
|
|
4430
|
+
isForgeMergeQueueRejection(error) ? 'merge-queue-activity' : 'merge-refused',
|
|
4431
|
+
error.forgeMessage,
|
|
4432
|
+
)
|
|
4433
|
+
}
|
|
4434
|
+
}
|
|
4435
|
+
} else if (maintain && enableSeq === undefined) {
|
|
4367
4436
|
// Quiet maintenance: no consent check passed, so nothing was mutated.
|
|
4368
4437
|
// A vanished request is reconciled by the next poll's PR read.
|
|
4369
4438
|
if (result.kind === 'deferred' && result.reason)
|
|
@@ -25,6 +25,8 @@ export const executionProgress = {
|
|
|
25
25
|
'build.land-requested': 'progress',
|
|
26
26
|
'landing.command-acknowledged': 'progress',
|
|
27
27
|
'landing.native-enable-started': 'bookkeeping',
|
|
28
|
+
'landing.polling-selected': 'bookkeeping',
|
|
29
|
+
'landing.human-merge-required': 'bookkeeping',
|
|
28
30
|
'landing.forge-merged': 'progress',
|
|
29
31
|
'landing.native-applied': 'bookkeeping',
|
|
30
32
|
'target.distance': 'bookkeeping',
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The production invoker for configured command hooks (§16.1 `[hooks]`): one
|
|
3
|
+
* `sh -c` process per record, the record on stdin as one JSON line. Exit 0
|
|
4
|
+
* within the hook's timeout is success; anything else is a failure whose text
|
|
5
|
+
* the hook runtime reports. The command runs in its own process group so a
|
|
6
|
+
* timeout, a stop, or a natural exit reaps every descendant it started.
|
|
7
|
+
*/
|
|
8
|
+
import type { HookConfig } from '../config/schema'
|
|
9
|
+
import { terminateProcessGroup } from './process-group'
|
|
10
|
+
import type { HookInvoke, HookInvokeResult } from './hooks'
|
|
11
|
+
|
|
12
|
+
/** Build- and session-identity variables a hook must never inherit. */
|
|
13
|
+
const STRIPPED_ENV = [
|
|
14
|
+
'AB_BUILD',
|
|
15
|
+
'AB_SESSION',
|
|
16
|
+
'AB_PHASE',
|
|
17
|
+
'AB_ROUND',
|
|
18
|
+
'AB_HARVEST',
|
|
19
|
+
'AB_CONTEXT_DIR',
|
|
20
|
+
'AB_DISPATCH_GENERATION',
|
|
21
|
+
] as const
|
|
22
|
+
|
|
23
|
+
const OUTPUT_TAIL_BYTES = 4 * 1024
|
|
24
|
+
const ERROR_MAX = 1_000
|
|
25
|
+
|
|
26
|
+
export function hookCommandEnv(
|
|
27
|
+
env: Record<string, string | undefined>,
|
|
28
|
+
name: string,
|
|
29
|
+
): Record<string, string> {
|
|
30
|
+
const result: Record<string, string> = {}
|
|
31
|
+
for (const [key, value] of Object.entries(env))
|
|
32
|
+
if (value !== undefined && !(STRIPPED_ENV as readonly string[]).includes(key))
|
|
33
|
+
result[key] = value
|
|
34
|
+
result.AB_HOOK = name
|
|
35
|
+
return result
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function truncate(text: string): string {
|
|
39
|
+
return text.length > ERROR_MAX ? `${text.slice(0, ERROR_MAX - 1)}…` : text
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Keep only the last `OUTPUT_TAIL_BYTES` of a stream, read to its end. */
|
|
43
|
+
async function tail(stream: ReadableStream<Uint8Array>, sink: { text: string }): Promise<void> {
|
|
44
|
+
const decoder = new TextDecoder()
|
|
45
|
+
for await (const chunk of stream) {
|
|
46
|
+
sink.text = (sink.text + decoder.decode(chunk, { stream: true })).slice(-OUTPUT_TAIL_BYTES)
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function commandHookInvoker(opts: {
|
|
51
|
+
checkout: string
|
|
52
|
+
env: Record<string, string | undefined>
|
|
53
|
+
stopTimeoutMs?: number
|
|
54
|
+
}): HookInvoke {
|
|
55
|
+
return async (hook, line, signal) => runCommandHook(hook, line, signal, opts)
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export async function runCommandHook(
|
|
59
|
+
hook: { name: string; config: HookConfig },
|
|
60
|
+
line: string,
|
|
61
|
+
signal: AbortSignal,
|
|
62
|
+
opts: { checkout: string; env: Record<string, string | undefined>; stopTimeoutMs?: number },
|
|
63
|
+
): Promise<HookInvokeResult> {
|
|
64
|
+
const command = hook.config.command
|
|
65
|
+
if (command === undefined) return { ok: false, error: 'could not start: no command' }
|
|
66
|
+
let child: ReturnType<typeof Bun.spawn>
|
|
67
|
+
try {
|
|
68
|
+
child = Bun.spawn(['sh', '-c', command], {
|
|
69
|
+
cwd: opts.checkout,
|
|
70
|
+
env: hookCommandEnv(opts.env, hook.name),
|
|
71
|
+
stdin: 'pipe',
|
|
72
|
+
stdout: 'pipe',
|
|
73
|
+
stderr: 'pipe',
|
|
74
|
+
detached: true,
|
|
75
|
+
})
|
|
76
|
+
} catch (error) {
|
|
77
|
+
return {
|
|
78
|
+
ok: false,
|
|
79
|
+
error: truncate(`could not start: ${error instanceof Error ? error.message : String(error)}`),
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
const output = { text: '' }
|
|
83
|
+
const drained = Promise.all([
|
|
84
|
+
tail(child.stdout as ReadableStream<Uint8Array>, output),
|
|
85
|
+
tail(child.stderr as ReadableStream<Uint8Array>, output),
|
|
86
|
+
]).catch(() => {})
|
|
87
|
+
let reaping: Promise<void> | undefined
|
|
88
|
+
const reap = (): Promise<void> =>
|
|
89
|
+
(reaping ??= terminateProcessGroup(child.pid, opts.stopTimeoutMs).catch(() => {}))
|
|
90
|
+
// Timeout and abort are armed before any stdin is written: a command that
|
|
91
|
+
// never reads a record larger than the pipe buffer must not hold delivery
|
|
92
|
+
// past its timeout or a stop.
|
|
93
|
+
let timedOut = false
|
|
94
|
+
const timer = setTimeout(() => {
|
|
95
|
+
timedOut = true
|
|
96
|
+
void reap()
|
|
97
|
+
}, hook.config.timeoutSeconds * 1000)
|
|
98
|
+
const onAbort = (): void => void reap()
|
|
99
|
+
signal.addEventListener('abort', onAbort, { once: true })
|
|
100
|
+
if (signal.aborted) onAbort()
|
|
101
|
+
// The write runs inside the protected lifetime and is never awaited: the
|
|
102
|
+
// command's exit decides, and one that closes stdin first only fails it.
|
|
103
|
+
void (async () => {
|
|
104
|
+
const stdin = child.stdin as import('bun').FileSink
|
|
105
|
+
stdin.write(line)
|
|
106
|
+
await stdin.end()
|
|
107
|
+
})().catch(() => {})
|
|
108
|
+
try {
|
|
109
|
+
const exitCode = await child.exited
|
|
110
|
+
// Descendants that outlive a natural exit are reaped with the group.
|
|
111
|
+
await reap()
|
|
112
|
+
await drained
|
|
113
|
+
if (signal.aborted) return { ok: false, error: 'stopped' }
|
|
114
|
+
if (timedOut) return { ok: false, error: `timed out after ${hook.config.timeoutSeconds}s` }
|
|
115
|
+
if (exitCode === 0) return { ok: true }
|
|
116
|
+
const detail = output.text.trim()
|
|
117
|
+
return {
|
|
118
|
+
ok: false,
|
|
119
|
+
error: truncate(`exit status ${exitCode}${detail.length > 0 ? `: ${detail}` : ''}`),
|
|
120
|
+
}
|
|
121
|
+
} finally {
|
|
122
|
+
clearTimeout(timer)
|
|
123
|
+
signal.removeEventListener('abort', onAbort)
|
|
124
|
+
}
|
|
125
|
+
}
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The production invoker for URL hooks (§16.1 `[hooks]`), and the router that
|
|
3
|
+
* picks a hook's transport. Each record is one HTTP POST whose body is the
|
|
4
|
+
* exact JSON line a command hook reads on stdin, without its newline, signed
|
|
5
|
+
* with HMAC-SHA256 over `<timestamp>.<body>` using the secret named by
|
|
6
|
+
* `secretEnv` in the dispatcher's environment. A 2xx response within the
|
|
7
|
+
* hook's timeout is success; any other status, a redirect (never followed), a
|
|
8
|
+
* timeout or a connection error is a failure the hook runtime reports.
|
|
9
|
+
*
|
|
10
|
+
* Failure text never carries the secret, the URL, the request headers or the
|
|
11
|
+
* response body.
|
|
12
|
+
*/
|
|
13
|
+
import { createHmac } from 'node:crypto'
|
|
14
|
+
import type { HookConfig } from '../config/schema'
|
|
15
|
+
import { runCommandHook } from './hook-command'
|
|
16
|
+
import type { HookInvoke, HookInvokeResult } from './hooks'
|
|
17
|
+
|
|
18
|
+
const ERROR_MAX = 1_000
|
|
19
|
+
|
|
20
|
+
type Fetch = (url: string, init: RequestInit) => Promise<Response>
|
|
21
|
+
|
|
22
|
+
export interface WebhookOpts {
|
|
23
|
+
env: Record<string, string | undefined>
|
|
24
|
+
clock: () => Date
|
|
25
|
+
/** Test seam; defaults to the global `fetch`. */
|
|
26
|
+
fetch?: Fetch
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** `v1=<lowercase hex HMAC-SHA256(secret, "<timestamp>.<body>")>`. */
|
|
30
|
+
export function signHookBody(secret: string, timestamp: number, body: string): string {
|
|
31
|
+
return `v1=${createHmac('sha256', secret).update(`${timestamp}.${body}`).digest('hex')}`
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** The request for one record, without transport options. Pure. */
|
|
35
|
+
export function webhookRequest(
|
|
36
|
+
hook: { name: string; config: HookConfig },
|
|
37
|
+
record: { id: string },
|
|
38
|
+
line: string,
|
|
39
|
+
secret: string,
|
|
40
|
+
now: Date,
|
|
41
|
+
): { url: string; init: { method: 'POST'; headers: Record<string, string>; body: string } } {
|
|
42
|
+
const body = line.endsWith('\n') ? line.slice(0, -1) : line
|
|
43
|
+
const timestamp = Math.floor(now.getTime() / 1000)
|
|
44
|
+
return {
|
|
45
|
+
url: hook.config.url ?? '',
|
|
46
|
+
init: {
|
|
47
|
+
method: 'POST',
|
|
48
|
+
headers: {
|
|
49
|
+
'Content-Type': 'application/json',
|
|
50
|
+
'User-Agent': 'autobuild-hook',
|
|
51
|
+
'Autobuild-Hook': hook.name,
|
|
52
|
+
'Autobuild-Delivery': record.id,
|
|
53
|
+
'Autobuild-Timestamp': String(timestamp),
|
|
54
|
+
'Autobuild-Signature': signHookBody(secret, timestamp, body),
|
|
55
|
+
},
|
|
56
|
+
body,
|
|
57
|
+
},
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function truncate(text: string): string {
|
|
62
|
+
return text.length > ERROR_MAX ? `${text.slice(0, ERROR_MAX - 1)}…` : text
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function recordId(line: string): string {
|
|
66
|
+
try {
|
|
67
|
+
const id = (JSON.parse(line) as { id?: unknown }).id
|
|
68
|
+
return typeof id === 'string' ? id : ''
|
|
69
|
+
} catch {
|
|
70
|
+
return ''
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export async function runWebhookHook(
|
|
75
|
+
hook: { name: string; config: HookConfig },
|
|
76
|
+
line: string,
|
|
77
|
+
signal: AbortSignal,
|
|
78
|
+
record: { id: string } | undefined,
|
|
79
|
+
opts: WebhookOpts,
|
|
80
|
+
): Promise<HookInvokeResult> {
|
|
81
|
+
const { url, secretEnv, timeoutSeconds } = hook.config
|
|
82
|
+
if (url === undefined) return { ok: false, error: 'could not start: no url' }
|
|
83
|
+
const secret = secretEnv === undefined ? undefined : opts.env[secretEnv]
|
|
84
|
+
if (secret === undefined || secret.trim() === '')
|
|
85
|
+
return {
|
|
86
|
+
ok: false,
|
|
87
|
+
error: `signing secret variable ${secretEnv ?? '(none)'} is unset or empty`,
|
|
88
|
+
}
|
|
89
|
+
if (signal.aborted) return { ok: false, error: 'stopped' }
|
|
90
|
+
const request = webhookRequest(hook, record ?? { id: recordId(line) }, line, secret, opts.clock())
|
|
91
|
+
const controller = new AbortController()
|
|
92
|
+
let timedOut = false
|
|
93
|
+
const timer = setTimeout(() => {
|
|
94
|
+
timedOut = true
|
|
95
|
+
controller.abort()
|
|
96
|
+
}, timeoutSeconds * 1000)
|
|
97
|
+
const onAbort = (): void => controller.abort()
|
|
98
|
+
signal.addEventListener('abort', onAbort, { once: true })
|
|
99
|
+
try {
|
|
100
|
+
let response: Response
|
|
101
|
+
try {
|
|
102
|
+
response = await (opts.fetch ?? fetch)(request.url, {
|
|
103
|
+
...request.init,
|
|
104
|
+
redirect: 'manual',
|
|
105
|
+
signal: controller.signal,
|
|
106
|
+
})
|
|
107
|
+
} catch (error) {
|
|
108
|
+
if (signal.aborted) return { ok: false, error: 'stopped' }
|
|
109
|
+
if (timedOut) return { ok: false, error: `timed out after ${timeoutSeconds}s` }
|
|
110
|
+
const detail =
|
|
111
|
+
error instanceof Error ? `${error.name}: ${error.message}` : String(error ?? 'error')
|
|
112
|
+
return {
|
|
113
|
+
ok: false,
|
|
114
|
+
error: truncate(
|
|
115
|
+
`request failed: ${detail.replaceAll(url, '<url>').replaceAll(secret, '<secret>')}`,
|
|
116
|
+
),
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
await response.body?.cancel().catch(() => {})
|
|
120
|
+
if (signal.aborted) return { ok: false, error: 'stopped' }
|
|
121
|
+
const status = response.status
|
|
122
|
+
if (status >= 200 && status < 300) return { ok: true }
|
|
123
|
+
if ((status >= 300 && status < 400) || status === 0 || response.type === 'opaqueredirect')
|
|
124
|
+
return { ok: false, error: `redirect (HTTP ${status}) not followed` }
|
|
125
|
+
return { ok: false, error: `HTTP ${status}` }
|
|
126
|
+
} finally {
|
|
127
|
+
clearTimeout(timer)
|
|
128
|
+
signal.removeEventListener('abort', onAbort)
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export function webhookHookInvoker(opts: WebhookOpts): HookInvoke {
|
|
133
|
+
return async (hook, line, signal, record) => runWebhookHook(hook, line, signal, record, opts)
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** The dispatcher's invoker: url hooks POST, every other hook runs its command. */
|
|
137
|
+
export function hookInvoker(
|
|
138
|
+
opts: WebhookOpts & { checkout: string; stopTimeoutMs?: number },
|
|
139
|
+
): HookInvoke {
|
|
140
|
+
return async (hook, line, signal, record) =>
|
|
141
|
+
hook.config.url !== undefined
|
|
142
|
+
? runWebhookHook(hook, line, signal, record, opts)
|
|
143
|
+
: runCommandHook(hook, line, signal, opts)
|
|
144
|
+
}
|