|
| 1 | +import { readFileSync, statSync } from "node:fs"; |
| 2 | +import { join, relative, resolve } from "node:path"; |
| 3 | +import { isActionEventPublishPath } from "./action-ledger-paths.js"; |
| 4 | +import { |
| 5 | + ACTION_EVENT_SHARD_IMPORT_MAX_PUBLISH_PATHS, |
| 6 | + importActionEventShards, |
| 7 | + interruptOpenWorkflowActionEvents, |
| 8 | + workflowActionProducer, |
| 9 | +} from "./action-ledger-runtime.js"; |
| 10 | +import { ACTION_EVENT_REASON_CODES } from "./action-ledger.js"; |
| 11 | +import { boolArg, optionalNumberArg, stringArg, type Args } from "./clawsweeper-args.js"; |
| 12 | +import { UserFacingCommandError } from "./command.js"; |
| 13 | +import { type RepositoryProfile } from "./repository-profiles.js"; |
| 14 | +import { publishStateBlob } from "./state-blob-client.js"; |
| 15 | + |
| 16 | +interface CreateActionCommandsDependencies { |
| 17 | + defaultClosedDir: (profile?: RepositoryProfile) => string; |
| 18 | + defaultItemsDir: (profile?: RepositoryProfile) => string; |
| 19 | + repoFromArgs: (args: Args) => RepositoryProfile; |
| 20 | + ROOT: string; |
| 21 | + updateDashboard: (itemsDir?: string, closedDir?: string) => void; |
| 22 | +} |
| 23 | + |
| 24 | +export function createActionCommands(dependencies: CreateActionCommandsDependencies) { |
| 25 | + const { defaultClosedDir, defaultItemsDir, repoFromArgs, ROOT, updateDashboard } = dependencies; |
| 26 | + |
| 27 | + function publishActionEventsCommand(args: Args): void { |
| 28 | + const sourceRoot = resolve( |
| 29 | + stringArg(args.source_root, join(ROOT, ".clawsweeper-repair", "action-ledger-download")), |
| 30 | + ); |
| 31 | + const stateRoot = resolve(stringArg(args.state_root, ROOT)); |
| 32 | + const expectedProducerJob = stringArg(args.expected_producer_job, ""); |
| 33 | + if (!expectedProducerJob) { |
| 34 | + throw new UserFacingCommandError("--expected-producer-job is required"); |
| 35 | + } |
| 36 | + const expectedProducerRunAttempt = optionalNumberArg(args.expected_producer_run_attempt); |
| 37 | + if ( |
| 38 | + expectedProducerRunAttempt !== undefined && |
| 39 | + (!Number.isInteger(expectedProducerRunAttempt) || expectedProducerRunAttempt < 1) |
| 40 | + ) { |
| 41 | + throw new UserFacingCommandError( |
| 42 | + "--expected-producer-run-attempt must be a positive integer", |
| 43 | + ); |
| 44 | + } |
| 45 | + const expectedProducerRunId = stringArg(args.expected_producer_run_id, ""); |
| 46 | + if (expectedProducerRunId && !/^\d{1,30}$/.test(expectedProducerRunId)) { |
| 47 | + throw new UserFacingCommandError( |
| 48 | + "--expected-producer-run-id must be a numeric workflow run ID", |
| 49 | + ); |
| 50 | + } |
| 51 | + const expectedProducerSha = stringArg(args.expected_producer_sha, ""); |
| 52 | + if (expectedProducerSha && !/^[0-9a-f]{40}$/.test(expectedProducerSha)) { |
| 53 | + throw new UserFacingCommandError("--expected-producer-sha must be a lowercase commit SHA"); |
| 54 | + } |
| 55 | + const currentProducer = workflowActionProducer("action_event_publisher"); |
| 56 | + const result = importActionEventShards(sourceRoot, stateRoot, { |
| 57 | + expectedProducer: { |
| 58 | + repository: currentProducer.repository, |
| 59 | + sha: expectedProducerSha || currentProducer.sha, |
| 60 | + workflow: currentProducer.workflow, |
| 61 | + job: expectedProducerJob, |
| 62 | + runId: expectedProducerRunId || currentProducer.runId, |
| 63 | + runAttempt: expectedProducerRunAttempt ?? currentProducer.runAttempt, |
| 64 | + }, |
| 65 | + }); |
| 66 | + console.log(JSON.stringify(result, null, 2)); |
| 67 | + } |
| 68 | + |
| 69 | + const ACTION_EVENT_PUBLISH_PATH_FILE_MAX_BYTES = |
| 70 | + ACTION_EVENT_SHARD_IMPORT_MAX_PUBLISH_PATHS * 512; |
| 71 | + |
| 72 | + function actionEventPublishPathsForTest(content: string): string[] { |
| 73 | + if (Buffer.byteLength(content, "utf8") > ACTION_EVENT_PUBLISH_PATH_FILE_MAX_BYTES) { |
| 74 | + throw new Error( |
| 75 | + `action event publish path manifest exceeds ${ACTION_EVENT_PUBLISH_PATH_FILE_MAX_BYTES} bytes`, |
| 76 | + ); |
| 77 | + } |
| 78 | + const paths = content.split("\n").filter(Boolean); |
| 79 | + if (paths.length === 0) throw new Error("action event publish path manifest is empty"); |
| 80 | + if (paths.length > ACTION_EVENT_SHARD_IMPORT_MAX_PUBLISH_PATHS) { |
| 81 | + throw new Error( |
| 82 | + `action event publish path manifest exceeds ${ACTION_EVENT_SHARD_IMPORT_MAX_PUBLISH_PATHS} paths`, |
| 83 | + ); |
| 84 | + } |
| 85 | + let previous = ""; |
| 86 | + for (const path of paths) { |
| 87 | + if (!isActionEventPublishPath(path)) { |
| 88 | + throw new Error(`invalid action event publish path: ${path}`); |
| 89 | + } |
| 90 | + if (previous && path <= previous) { |
| 91 | + throw new Error("action event publish paths must be sorted and unique"); |
| 92 | + } |
| 93 | + previous = path; |
| 94 | + } |
| 95 | + return paths; |
| 96 | + } |
| 97 | + |
| 98 | + async function publishActionEventPathsCommand(args: Args): Promise<void> { |
| 99 | + const pathsFile = resolve(stringArg(args.paths_file, "")); |
| 100 | + if (!pathsFile || pathsFile === ROOT) { |
| 101 | + throw new UserFacingCommandError("--paths-file is required"); |
| 102 | + } |
| 103 | + const stat = statSync(pathsFile); |
| 104 | + if (!stat.isFile()) |
| 105 | + throw new Error(`action event publish path manifest is not a file: ${pathsFile}`); |
| 106 | + if (stat.size > ACTION_EVENT_PUBLISH_PATH_FILE_MAX_BYTES) { |
| 107 | + throw new Error( |
| 108 | + `action event publish path manifest exceeds ${ACTION_EVENT_PUBLISH_PATH_FILE_MAX_BYTES} bytes`, |
| 109 | + ); |
| 110 | + } |
| 111 | + const paths = actionEventPublishPathsForTest(readFileSync(pathsFile, "utf8")); |
| 112 | + for (const path of paths) { |
| 113 | + const source = resolve(ROOT, path); |
| 114 | + const rootRelativeSource = relative(ROOT, source); |
| 115 | + if ( |
| 116 | + rootRelativeSource.startsWith("..") || |
| 117 | + resolve(ROOT, rootRelativeSource) !== source || |
| 118 | + !statSync(source).isFile() |
| 119 | + ) { |
| 120 | + throw new Error(`action event publish path is not a regular file: ${path}`); |
| 121 | + } |
| 122 | + } |
| 123 | + const baseUrl = process.env.QUEUE_URL ?? process.env.CLAWSWEEPER_RECORDS_URL ?? ""; |
| 124 | + const webhookSecret = process.env.CLAWSWEEPER_WEBHOOK_SECRET ?? ""; |
| 125 | + let uploaded = 0; |
| 126 | + let unchanged = 0; |
| 127 | + for (const path of paths) { |
| 128 | + const result = await publishStateBlob({ |
| 129 | + baseUrl, |
| 130 | + webhookSecret, |
| 131 | + path, |
| 132 | + content: readFileSync(resolve(ROOT, path)), |
| 133 | + }); |
| 134 | + if (result.unchanged) unchanged += 1; |
| 135 | + else uploaded += 1; |
| 136 | + } |
| 137 | + console.log( |
| 138 | + JSON.stringify({ result: "published", path_count: paths.length, uploaded, unchanged }), |
| 139 | + ); |
| 140 | + } |
| 141 | + |
| 142 | + function isExplicitActionLedgerCommand(command: string): boolean { |
| 143 | + return ( |
| 144 | + command === "finalize-action-events" || |
| 145 | + command === "publish-action-events" || |
| 146 | + command === "publish-action-event-paths" |
| 147 | + ); |
| 148 | + } |
| 149 | + |
| 150 | + function dashboardCommand(args: Args): void { |
| 151 | + repoFromArgs(args); |
| 152 | + updateDashboard( |
| 153 | + resolve(stringArg(args.items_dir, defaultItemsDir())), |
| 154 | + resolve(stringArg(args.closed_dir, defaultClosedDir())), |
| 155 | + ); |
| 156 | + } |
| 157 | + |
| 158 | + function finalizeActionEventsCommand(args: Args): void { |
| 159 | + if (!boolArg(args.interrupt_open_attempts)) return; |
| 160 | + const reason = stringArg(args.reason, ACTION_EVENT_REASON_CODES.timeout); |
| 161 | + if ( |
| 162 | + reason !== ACTION_EVENT_REASON_CODES.timeout && |
| 163 | + reason !== ACTION_EVENT_REASON_CODES.cancelled && |
| 164 | + reason !== ACTION_EVENT_REASON_CODES.workflowFailed |
| 165 | + ) { |
| 166 | + throw new UserFacingCommandError( |
| 167 | + `Unsupported --reason for interrupted action events: ${reason}`, |
| 168 | + ); |
| 169 | + } |
| 170 | + const interrupted = interruptOpenWorkflowActionEvents(ROOT, { reasonCode: reason }); |
| 171 | + if (interrupted > 0) { |
| 172 | + console.error( |
| 173 | + `[action-ledger] recorded ${interrupted} ${reason} terminal event${ |
| 174 | + interrupted === 1 ? "" : "s" |
| 175 | + }`, |
| 176 | + ); |
| 177 | + } |
| 178 | + } |
| 179 | + |
| 180 | + return { |
| 181 | + actionEventPublishPathsForTest, |
| 182 | + dashboardCommand, |
| 183 | + finalizeActionEventsCommand, |
| 184 | + isExplicitActionLedgerCommand, |
| 185 | + publishActionEventPathsCommand, |
| 186 | + publishActionEventsCommand, |
| 187 | + }; |
| 188 | +} |
0 commit comments