-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathautomation.ts
More file actions
284 lines (257 loc) · 8.81 KB
/
automation.ts
File metadata and controls
284 lines (257 loc) · 8.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
import {
expandTemplate,
type AutomationTrigger,
type PushPolicy,
type SqliteDatabase,
type WorkItem,
} from "@r_masseater/ops-harbor-core";
import { randomUUID } from "node:crypto";
import { existsSync } from "node:fs";
import { spawn } from "node:child_process";
import type { OpsHarborConfig, PullRequestOverride, RepositoryConfig } from "./config";
import { env } from "../env";
import { ControlPlaneClient } from "./control-plane-client";
import { recordAutomationRun } from "./local-db";
type CommandResult = {
exitCode: number;
stdout: string;
stderr: string;
};
const validatedProcessEnv = Object.fromEntries(
Object.entries(env).filter((entry): entry is [string, string] => entry[1] !== undefined),
);
function resolveRepositoryConfig(
config: OpsHarborConfig,
repository: string,
): RepositoryConfig | null {
return config.repositories.find((entry) => entry.repository === repository) ?? null;
}
function resolveOverride(
config: OpsHarborConfig,
repository: string,
number: number,
): PullRequestOverride | null {
return (
config.pullRequestOverrides.find(
(entry) => entry.repository === repository && entry.number === number,
) ?? null
);
}
function resolvePushPolicy(
config: OpsHarborConfig,
repository: RepositoryConfig | null,
workItem: WorkItem,
): PushPolicy {
return (
resolveOverride(config, workItem.repository, workItem.number)?.pushPolicy ??
repository?.pushPolicyDefault ??
"always_push"
);
}
function isTriggerDisabled(
config: OpsHarborConfig,
repository: RepositoryConfig | null,
workItem: WorkItem,
trigger: AutomationTrigger,
): boolean {
const override = resolveOverride(config, workItem.repository, workItem.number);
if (override?.disabledTriggers?.includes(trigger)) return true;
return repository?.disabledTriggers?.includes(trigger) ?? false;
}
function runCommand(
command: string,
args: string[],
options: { cwd?: string; env?: Record<string, string>; timeoutMs?: number } = {},
): Promise<CommandResult> {
const timeoutMs = options.timeoutMs ?? 300_000;
return new Promise((resolve, reject) => {
const child = spawn(command, args, {
cwd: options.cwd,
env: {
...validatedProcessEnv,
...options.env,
},
stdio: ["ignore", "pipe", "pipe"],
});
const timeout = setTimeout(() => {
child.kill("SIGTERM");
setTimeout(() => {
child.kill("SIGKILL");
}, 5_000).unref();
reject(new Error(`Command timed out after ${timeoutMs}ms: ${command}`));
}, timeoutMs);
const MAX_OUTPUT_BYTES = 10 * 1024 * 1024; // 10 MB
let stdout = "";
let stderr = "";
child.stdout.on("data", (chunk) => {
if (stdout.length < MAX_OUTPUT_BYTES) {
stdout += String(chunk);
}
});
child.stderr.on("data", (chunk) => {
if (stderr.length < MAX_OUTPUT_BYTES) {
stderr += String(chunk);
}
});
child.on("error", (error) => {
clearTimeout(timeout);
reject(error);
});
child.on("close", (exitCode) => {
clearTimeout(timeout);
resolve({
exitCode: exitCode ?? 1,
stdout: stdout.trim(),
stderr: stderr.trim(),
});
});
});
}
async function runShell(command: string, cwd: string): Promise<CommandResult> {
return runCommand("/bin/sh", ["-lc", command], { cwd });
}
async function ensureExpectedBranch(cwd: string, expectedBranch: string): Promise<void> {
const result = await runCommand("git", ["rev-parse", "--abbrev-ref", "HEAD"], { cwd });
if (result.exitCode !== 0) {
throw new Error(result.stderr || "Failed to determine current branch.");
}
if (result.stdout !== expectedBranch) {
throw new Error(`Repository is on branch ${result.stdout}, expected ${expectedBranch}.`);
}
}
async function maybeCommitAndPush(
repository: RepositoryConfig,
workItem: WorkItem,
policy: PushPolicy,
validateResult: CommandResult | null,
): Promise<string> {
if (policy === "manual") {
return "Push skipped because policy is manual.";
}
if (policy === "validate_success" && validateResult && validateResult.exitCode !== 0) {
throw new Error("Validation failed and push policy requires success.");
}
const status = await runCommand("git", ["status", "--porcelain"], { cwd: repository.path });
if (status.exitCode !== 0) {
throw new Error(status.stderr || "Failed to inspect git status.");
}
if (!status.stdout) {
return "No file changes detected after automation.";
}
await runCommand("git", ["add", "-A"], { cwd: repository.path });
const commitMessage = `ops-harbor: automated update for ${workItem.repository}#${workItem.number}`;
const commit = await runCommand("git", ["commit", "-m", commitMessage], {
cwd: repository.path,
});
if (commit.exitCode !== 0 && !commit.stderr.includes("nothing to commit")) {
throw new Error(commit.stderr || "Failed to create commit.");
}
const push = await runCommand("git", ["push"], { cwd: repository.path });
if (push.exitCode !== 0) {
throw new Error(push.stderr || "Failed to push branch.");
}
return "Committed and pushed automation changes.";
}
export async function processNextAutomationJob(
db: SqliteDatabase,
config: OpsHarborConfig,
workerId: string,
): Promise<"idle" | "processed"> {
if (!config.runner?.command) {
return "idle";
}
const client = new ControlPlaneClient(config);
const leased = await client.leaseJob(workerId);
if (!leased.job || !leased.workItem) return "idle";
const startedAt = new Date().toISOString();
const runId = randomUUID();
const repository = resolveRepositoryConfig(config, leased.workItem.repository);
try {
if (isTriggerDisabled(config, repository, leased.workItem, leased.job.triggerType)) {
await client.completeJob(leased.job.id, "canceled", "Trigger disabled by local policy.");
recordAutomationRun(db, {
id: runId,
workItemId: leased.workItem.id,
repository: leased.workItem.repository,
triggerType: leased.job.triggerType,
status: "canceled",
startedAt,
finishedAt: new Date().toISOString(),
summary: "Canceled because the trigger is disabled.",
});
return "processed";
}
if (!repository) {
throw new Error(`No repository mapping configured for ${leased.workItem.repository}.`);
}
if (!existsSync(repository.path)) {
throw new Error(`Mapped repository path does not exist: ${repository.path}`);
}
await ensureExpectedBranch(repository.path, leased.workItem.headBranch);
const prompt = [leased.job.prompt, repository.promptSuffix].filter(Boolean).join("\n\n");
const values = {
prompt,
repository: leased.workItem.repository,
number: leased.workItem.number,
title: leased.workItem.title,
url: leased.workItem.url,
head_branch: leased.workItem.headBranch,
base_branch: leased.workItem.baseBranch,
local_path: repository.path,
trigger: leased.job.triggerType,
};
const args = config.runner.args.map((arg) => expandTemplate(arg, values));
const command = expandTemplate(config.runner.command, values);
const runnerResult = await runCommand(command, args, {
cwd: repository.path,
...(config.runner.env ? { env: config.runner.env } : {}),
});
if (runnerResult.exitCode !== 0) {
throw new Error(runnerResult.stderr || runnerResult.stdout || "Automation runner failed.");
}
let validateResult: CommandResult | null = null;
if (repository.validateCommand) {
validateResult = await runShell(repository.validateCommand, repository.path);
}
const pushPolicy = resolvePushPolicy(config, repository, leased.workItem);
const pushSummary = await maybeCommitAndPush(
repository,
leased.workItem,
pushPolicy,
validateResult,
);
const summary = [
`Runner command completed successfully.`,
validateResult
? `Validation exit code: ${validateResult.exitCode}.`
: "Validation command not configured.",
`Push policy: ${pushPolicy}.`,
pushSummary,
].join(" ");
await client.completeJob(leased.job.id, "completed", summary);
recordAutomationRun(db, {
id: runId,
workItemId: leased.workItem.id,
repository: leased.workItem.repository,
triggerType: leased.job.triggerType,
status: "completed",
startedAt,
finishedAt: new Date().toISOString(),
summary,
});
} catch (error) {
const summary = error instanceof Error ? error.message : String(error);
await client.completeJob(leased.job.id, "failed", summary);
recordAutomationRun(db, {
id: runId,
workItemId: leased.workItem.id,
repository: leased.workItem.repository,
triggerType: leased.job.triggerType,
status: "failed",
startedAt,
finishedAt: new Date().toISOString(),
summary,
});
}
return "processed";
}