@pipeline-builder/pipeline-manager 6.5.5 → 6.5.6
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 +2 -2
- package/dist/agent/post-steps.d.ts +1 -1
- package/dist/agent/post-steps.d.ts.map +1 -1
- package/dist/agent/post-steps.js +27 -31
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +8 -9
- package/dist/commands/audit-stacks.d.ts +2 -1
- package/dist/commands/audit-stacks.d.ts.map +1 -1
- package/dist/commands/audit-stacks.js +12 -2
- package/dist/commands/provision-steps.d.ts +1 -1
- package/dist/commands/provision-steps.js +2 -2
- package/dist/commands/provision.js +2 -2
- package/dist/commands/redrive-events.d.ts +4 -3
- package/dist/commands/redrive-events.d.ts.map +1 -1
- package/dist/commands/redrive-events.js +51 -18
- package/dist/commands/runner-signing-key.js +2 -2
- package/dist/commands/{setup-runner.d.ts → setup-account.d.ts} +119 -71
- package/dist/commands/setup-account.d.ts.map +1 -0
- package/dist/commands/setup-account.js +1345 -0
- package/dist/commands/store-token.d.ts +6 -28
- package/dist/commands/store-token.d.ts.map +1 -1
- package/dist/commands/store-token.js +12 -139
- package/dist/config/cli.constants.d.ts +0 -8
- package/dist/config/cli.constants.d.ts.map +1 -1
- package/dist/config/cli.constants.js +1 -9
- package/dist/lambda/events-handler.js +1529 -0
- package/dist/lambda/runner-handler.d.ts +25 -1
- package/dist/lambda/runner-handler.d.ts.map +1 -1
- package/dist/lambda/runner-handler.js +390 -44
- package/dist/lambda/runner-inspect-connection.d.ts +32 -0
- package/dist/lambda/runner-inspect-connection.d.ts.map +1 -0
- package/dist/lambda/runner-inspect-connection.js +144 -0
- package/dist/lambda/runner-jws.d.ts.map +1 -1
- package/dist/lambda/runner-jws.js +57 -5
- package/dist/lambda/runner-sources.d.ts +12 -0
- package/dist/lambda/runner-sources.d.ts.map +1 -1
- package/dist/lambda/runner-sources.js +25 -16
- package/dist/lambda/token-renew-handler.d.ts +3 -2
- package/dist/lambda/token-renew-handler.d.ts.map +1 -1
- package/dist/lambda/token-renew-handler.js +17 -5
- package/dist/templates/account-stack.json +2049 -0
- package/dist/templates/forwarder-stack.json +133 -0
- package/dist/utils/{runner-template.d.ts → account-template.d.ts} +68 -17
- package/dist/utils/account-template.d.ts.map +1 -0
- package/dist/utils/account-template.js +316 -0
- package/dist/utils/inspect-buildspec.d.ts +9 -0
- package/dist/utils/inspect-buildspec.d.ts.map +1 -0
- package/dist/utils/inspect-buildspec.js +209 -0
- package/package.json +5 -4
- package/dist/commands/setup-events.d.ts +0 -15
- package/dist/commands/setup-events.d.ts.map +0 -1
- package/dist/commands/setup-events.js +0 -182
- package/dist/commands/setup-runner.d.ts.map +0 -1
- package/dist/commands/setup-runner.js +0 -1132
- package/dist/templates/events-stack.json +0 -192
- package/dist/templates/runner-stack.json +0 -960
- package/dist/templates/token-renew-stack.json +0 -115
- package/dist/utils/cron.d.ts +0 -28
- package/dist/utils/cron.d.ts.map +0 -1
- package/dist/utils/cron.js +0 -119
- package/dist/utils/runner-template.d.ts.map +0 -1
- package/dist/utils/runner-template.js +0 -238
|
@@ -0,0 +1,1529 @@
|
|
|
1
|
+
// ../pipeline-events/src/index.ts
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
|
|
4
|
+
// ../pipeline-core/lib/handlers/platform-credential.js
|
|
5
|
+
import { GetSecretValueCommand, SecretsManagerClient } from "@aws-sdk/client-secrets-manager";
|
|
6
|
+
var ACCESS_KEY_PREFIXES = ["pb_sa_", "pb_pat_"];
|
|
7
|
+
function assertAccessKey(value, source) {
|
|
8
|
+
if (ACCESS_KEY_PREFIXES.some((p) => value.startsWith(p)))
|
|
9
|
+
return;
|
|
10
|
+
const looksLikeJwt = value.split(".").length === 3;
|
|
11
|
+
throw new Error(`${source} does not hold an opaque access key (expected a "pb_sa_\u2026" value)` + (looksLikeJwt ? ' \u2014 it holds a JWT, not a service-account key. Re-run "pipeline-manager infra store-token" to issue one.' : "."));
|
|
12
|
+
}
|
|
13
|
+
async function readCredentialSecret(secretName, client2 = new SecretsManagerClient({})) {
|
|
14
|
+
const response = await client2.send(new GetSecretValueCommand({ SecretId: secretName }));
|
|
15
|
+
if (!response.SecretString)
|
|
16
|
+
throw new Error(`Secret "${secretName}" is empty`);
|
|
17
|
+
let parsed;
|
|
18
|
+
try {
|
|
19
|
+
parsed = JSON.parse(response.SecretString);
|
|
20
|
+
} catch {
|
|
21
|
+
parsed = void 0;
|
|
22
|
+
}
|
|
23
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
|
|
24
|
+
throw new Error(`Secret "${secretName}" is not a JSON object \u2014 re-run "pipeline-manager infra store-token" to provision a service-account key`);
|
|
25
|
+
}
|
|
26
|
+
return parsed;
|
|
27
|
+
}
|
|
28
|
+
async function readAccessKeyFromSecret(secretName) {
|
|
29
|
+
const secret = await readCredentialSecret(secretName);
|
|
30
|
+
const key = typeof secret.password === "string" ? secret.password : "";
|
|
31
|
+
if (!key) {
|
|
32
|
+
throw new Error(`Secret "${secretName}" missing password \u2014 run "pipeline-manager infra store-token" to provision a service-account key`);
|
|
33
|
+
}
|
|
34
|
+
assertAccessKey(key, `secret "${secretName}"`);
|
|
35
|
+
return key;
|
|
36
|
+
}
|
|
37
|
+
function createPlatformCredential(opts) {
|
|
38
|
+
let cached = null;
|
|
39
|
+
let fromEnv = false;
|
|
40
|
+
return {
|
|
41
|
+
async getKey() {
|
|
42
|
+
if (cached)
|
|
43
|
+
return cached;
|
|
44
|
+
const direct = opts.envKeyVar ? process.env[opts.envKeyVar] : void 0;
|
|
45
|
+
if (direct) {
|
|
46
|
+
assertAccessKey(direct, opts.envKeyVar);
|
|
47
|
+
cached = direct;
|
|
48
|
+
fromEnv = true;
|
|
49
|
+
return cached;
|
|
50
|
+
}
|
|
51
|
+
const secretName = typeof opts.secretName === "function" ? opts.secretName() : opts.secretName;
|
|
52
|
+
if (!secretName) {
|
|
53
|
+
throw new Error(`${opts.envKeyVar ? `${opts.envKeyVar} or ` : ""}PLATFORM_SECRET_NAME environment variable is required`);
|
|
54
|
+
}
|
|
55
|
+
cached = await readAccessKeyFromSecret(secretName);
|
|
56
|
+
fromEnv = false;
|
|
57
|
+
return cached;
|
|
58
|
+
},
|
|
59
|
+
invalidate() {
|
|
60
|
+
if (!fromEnv)
|
|
61
|
+
cached = null;
|
|
62
|
+
},
|
|
63
|
+
reset() {
|
|
64
|
+
cached = null;
|
|
65
|
+
fromEnv = false;
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// ../pipeline-core/lib/core/audit-correlation.js
|
|
71
|
+
var REQUEST_ID_HEADER = "X-Request-Id";
|
|
72
|
+
var PIPELINE_EXECUTION_ID_HEADER = "X-Pipeline-Execution-Id";
|
|
73
|
+
var CODEBUILD_BUILD_ID_HEADER = "X-CodeBuild-Build-Id";
|
|
74
|
+
var MAX_CORRELATION_VALUE = 128;
|
|
75
|
+
function sanitizeCorrelationValue(value) {
|
|
76
|
+
if (typeof value !== "string")
|
|
77
|
+
return void 0;
|
|
78
|
+
const clean = value.replace(/[^\x21-\x7e]/g, "").slice(0, MAX_CORRELATION_VALUE);
|
|
79
|
+
return clean.length > 0 ? clean : void 0;
|
|
80
|
+
}
|
|
81
|
+
function correlationHeaders(ids) {
|
|
82
|
+
const headers = {};
|
|
83
|
+
const requestId = sanitizeCorrelationValue(ids.requestId);
|
|
84
|
+
const executionId = sanitizeCorrelationValue(ids.pipelineExecutionId);
|
|
85
|
+
const buildId = sanitizeCorrelationValue(ids.codeBuildBuildId);
|
|
86
|
+
if (requestId)
|
|
87
|
+
headers[REQUEST_ID_HEADER] = requestId;
|
|
88
|
+
if (executionId)
|
|
89
|
+
headers[PIPELINE_EXECUTION_ID_HEADER] = executionId;
|
|
90
|
+
if (buildId)
|
|
91
|
+
headers[CODEBUILD_BUILD_ID_HEADER] = buildId;
|
|
92
|
+
return headers;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// ../pipeline-core/lib/core/synth-failure.js
|
|
96
|
+
var SYNTH_FAILURE_MARKER = "PB_SYNTH_FAILURE";
|
|
97
|
+
var MAX_MESSAGE = 1e3;
|
|
98
|
+
var MAX_PLUGINS = 10;
|
|
99
|
+
var MAX_PLUGIN_MESSAGE = 300;
|
|
100
|
+
var clip = (s, max) => s.length > max ? `${s.slice(0, max - 1)}\u2026` : s;
|
|
101
|
+
function synthFailure(message, plugins = []) {
|
|
102
|
+
const codes = [...new Set(plugins.map((p) => p.code))];
|
|
103
|
+
const code = plugins.length === 0 ? "SYNTH_FAILED" : codes.length === 1 ? codes[0] : "PLUGINS_REFUSED";
|
|
104
|
+
return {
|
|
105
|
+
code,
|
|
106
|
+
message: clip(message, MAX_MESSAGE),
|
|
107
|
+
plugins: plugins.slice(0, MAX_PLUGINS).map((p) => ({
|
|
108
|
+
plugin: clip(p.plugin, 100),
|
|
109
|
+
code: clip(p.code, 100),
|
|
110
|
+
message: clip(p.message, MAX_PLUGIN_MESSAGE)
|
|
111
|
+
}))
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
function parseSynthFailure(line) {
|
|
115
|
+
const at = line.indexOf(`${SYNTH_FAILURE_MARKER} {`);
|
|
116
|
+
if (at === -1)
|
|
117
|
+
return null;
|
|
118
|
+
try {
|
|
119
|
+
const parsed = JSON.parse(line.slice(at + SYNTH_FAILURE_MARKER.length + 1).trim());
|
|
120
|
+
if (typeof parsed.code !== "string" || typeof parsed.message !== "string")
|
|
121
|
+
return null;
|
|
122
|
+
const plugins = Array.isArray(parsed.plugins) ? parsed.plugins.filter((p) => !!p && typeof p.plugin === "string" && typeof p.code === "string" && typeof p.message === "string") : [];
|
|
123
|
+
return { ...synthFailure(parsed.message, plugins), code: clip(parsed.code, 100) };
|
|
124
|
+
} catch {
|
|
125
|
+
return null;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// ../api-core/lib/utils/env.js
|
|
130
|
+
var problems = /* @__PURE__ */ new Map();
|
|
131
|
+
var bootChecked = false;
|
|
132
|
+
function recordProblem(name, message) {
|
|
133
|
+
if (problems.has(name))
|
|
134
|
+
return;
|
|
135
|
+
problems.set(name, message);
|
|
136
|
+
if (bootChecked) {
|
|
137
|
+
console.warn(`Invalid environment variable ${message}`);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
function clampRange(name, raw, n, opts) {
|
|
141
|
+
let out = n;
|
|
142
|
+
if (opts?.min !== void 0 && out < opts.min)
|
|
143
|
+
out = opts.min;
|
|
144
|
+
if (opts?.max !== void 0 && out > opts.max)
|
|
145
|
+
out = opts.max;
|
|
146
|
+
if (out !== n && raw !== void 0) {
|
|
147
|
+
const range = `${opts?.min ?? "-\u221E"}..${opts?.max ?? "\u221E"}`;
|
|
148
|
+
recordProblem(name, `${name}="${raw}" is outside the allowed range ${range}`);
|
|
149
|
+
}
|
|
150
|
+
return out;
|
|
151
|
+
}
|
|
152
|
+
function envInt(name, def, opts) {
|
|
153
|
+
const raw = process.env[name];
|
|
154
|
+
const trimmed = raw?.trim() ?? "";
|
|
155
|
+
if (trimmed === "")
|
|
156
|
+
return clampRange(name, void 0, def, opts);
|
|
157
|
+
if (!/^[+-]?\d+$/.test(trimmed) || !Number.isSafeInteger(Number.parseInt(trimmed, 10))) {
|
|
158
|
+
recordProblem(name, `${name}="${raw}" is not an integer`);
|
|
159
|
+
return clampRange(name, void 0, def, opts);
|
|
160
|
+
}
|
|
161
|
+
return clampRange(name, trimmed, Number.parseInt(trimmed, 10), opts);
|
|
162
|
+
}
|
|
163
|
+
function envBool(name, def) {
|
|
164
|
+
const raw = process.env[name];
|
|
165
|
+
if (raw === void 0 || raw.trim() === "")
|
|
166
|
+
return def;
|
|
167
|
+
const v = raw.trim().toLowerCase();
|
|
168
|
+
if (v === "true" || v === "1" || v === "yes" || v === "on")
|
|
169
|
+
return true;
|
|
170
|
+
if (v === "false" || v === "0" || v === "no" || v === "off")
|
|
171
|
+
return false;
|
|
172
|
+
recordProblem(name, `${name}="${raw}" is not a boolean (true/false, 1/0, yes/no, on/off)`);
|
|
173
|
+
return def;
|
|
174
|
+
}
|
|
175
|
+
function envStr(name, def) {
|
|
176
|
+
const raw = process.env[name];
|
|
177
|
+
return raw === void 0 || raw.trim() === "" ? def : raw;
|
|
178
|
+
}
|
|
179
|
+
function strict(name, read) {
|
|
180
|
+
const before = problems.get(name);
|
|
181
|
+
problems.delete(name);
|
|
182
|
+
const value = read();
|
|
183
|
+
const problem = problems.get(name);
|
|
184
|
+
if (problem !== void 0)
|
|
185
|
+
throw new Error(`Invalid environment variable ${problem}`);
|
|
186
|
+
if (before !== void 0)
|
|
187
|
+
problems.set(name, before);
|
|
188
|
+
return value;
|
|
189
|
+
}
|
|
190
|
+
function envIntStrict(name, def, opts) {
|
|
191
|
+
return strict(name, () => envInt(name, def, opts));
|
|
192
|
+
}
|
|
193
|
+
function envBoolStrict(name, def) {
|
|
194
|
+
return strict(name, () => envBool(name, def));
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
// ../pipeline-events/src/config.ts
|
|
198
|
+
var PLATFORM_ACCESS_KEY_ENV = "PLATFORM_ACCESS_KEY";
|
|
199
|
+
var EVENTS_CONFIG_DEFAULTS = {
|
|
200
|
+
reportingFetchTimeoutMs: 5e3,
|
|
201
|
+
scmFetchTimeoutMs: 3e3,
|
|
202
|
+
healthIntervalMs: 60 * 1e3,
|
|
203
|
+
redriveIntervalMs: 5 * 60 * 1e3,
|
|
204
|
+
redriveMaxAgeSec: 6 * 60 * 60,
|
|
205
|
+
tagCacheTtlMs: 15 * 60 * 1e3,
|
|
206
|
+
tagMissCacheTtlMs: 5 * 60 * 1e3
|
|
207
|
+
};
|
|
208
|
+
function str(name) {
|
|
209
|
+
return envStr(name, "").trim() || void 0;
|
|
210
|
+
}
|
|
211
|
+
function baseUrl() {
|
|
212
|
+
const raw = str("PLATFORM_BASE_URL");
|
|
213
|
+
if (raw === void 0) return void 0;
|
|
214
|
+
let url;
|
|
215
|
+
try {
|
|
216
|
+
url = new URL(raw);
|
|
217
|
+
} catch {
|
|
218
|
+
throw new Error(`PLATFORM_BASE_URL must be an absolute http(s) URL (got "${raw}")`);
|
|
219
|
+
}
|
|
220
|
+
if (url.protocol !== "https:" && url.protocol !== "http:") {
|
|
221
|
+
throw new Error(`PLATFORM_BASE_URL must be an absolute http(s) URL (got "${raw}")`);
|
|
222
|
+
}
|
|
223
|
+
return raw.replace(/\/+$/, "");
|
|
224
|
+
}
|
|
225
|
+
var SQS_ARN_RE = /^arn:[a-z-]+:sqs:[a-z0-9-]+:\d{12}:[A-Za-z0-9_-]{1,80}$/;
|
|
226
|
+
function dlqArn() {
|
|
227
|
+
const raw = str("EVENT_DLQ_ARN");
|
|
228
|
+
if (raw !== void 0 && !SQS_ARN_RE.test(raw)) {
|
|
229
|
+
throw new Error("EVENT_DLQ_ARN must be an SQS queue ARN (arn:<partition>:sqs:<region>:<account>:<name>)");
|
|
230
|
+
}
|
|
231
|
+
return raw;
|
|
232
|
+
}
|
|
233
|
+
function loadEventsConfig() {
|
|
234
|
+
const d = EVENTS_CONFIG_DEFAULTS;
|
|
235
|
+
const positive = (name, def) => envIntStrict(name, def, { min: 1 });
|
|
236
|
+
return {
|
|
237
|
+
platformBaseUrl: baseUrl(),
|
|
238
|
+
platformSecretName: str("PLATFORM_SECRET_NAME"),
|
|
239
|
+
doraEnabled: envBoolStrict("DORA_ENABLED", false),
|
|
240
|
+
dlqArn: dlqArn(),
|
|
241
|
+
reportingFetchTimeoutMs: positive("REPORTING_FETCH_TIMEOUT_MS", d.reportingFetchTimeoutMs),
|
|
242
|
+
scmFetchTimeoutMs: positive("SCM_FETCH_TIMEOUT_MS", d.scmFetchTimeoutMs),
|
|
243
|
+
healthIntervalMs: positive("EVENT_HEALTH_INTERVAL_MS", d.healthIntervalMs),
|
|
244
|
+
redriveIntervalMs: positive("EVENT_DLQ_REDRIVE_INTERVAL_MS", d.redriveIntervalMs),
|
|
245
|
+
redriveMaxAgeSec: positive("EVENT_DLQ_REDRIVE_MAX_AGE_SEC", d.redriveMaxAgeSec),
|
|
246
|
+
tagCacheTtlMs: positive("EVENT_TAG_CACHE_TTL_MS", d.tagCacheTtlMs),
|
|
247
|
+
tagMissCacheTtlMs: positive("EVENT_TAG_MISS_CACHE_TTL_MS", d.tagMissCacheTtlMs)
|
|
248
|
+
};
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
// ../pipeline-events/src/util.ts
|
|
252
|
+
import { createHash } from "node:crypto";
|
|
253
|
+
var log = {
|
|
254
|
+
info: (msg, data) => console.log(JSON.stringify({ level: "INFO", message: msg, data, ts: (/* @__PURE__ */ new Date()).toISOString() })),
|
|
255
|
+
warn: (msg, data) => console.log(JSON.stringify({ level: "WARN", message: msg, data, ts: (/* @__PURE__ */ new Date()).toISOString() })),
|
|
256
|
+
error: (msg, data) => console.error(JSON.stringify({ level: "ERROR", message: msg, data, ts: (/* @__PURE__ */ new Date()).toISOString() }))
|
|
257
|
+
};
|
|
258
|
+
var BoundedMap = class extends Map {
|
|
259
|
+
constructor(max) {
|
|
260
|
+
super();
|
|
261
|
+
this.max = max;
|
|
262
|
+
}
|
|
263
|
+
max;
|
|
264
|
+
set(key, value) {
|
|
265
|
+
if (super.has(key)) {
|
|
266
|
+
super.delete(key);
|
|
267
|
+
} else if (this.size >= this.max) {
|
|
268
|
+
const oldest = this.keys().next().value;
|
|
269
|
+
if (oldest !== void 0) super.delete(oldest);
|
|
270
|
+
}
|
|
271
|
+
return super.set(key, value);
|
|
272
|
+
}
|
|
273
|
+
};
|
|
274
|
+
function arnRef(arn) {
|
|
275
|
+
return `arn#${createHash("sha256").update(arn).digest("hex").slice(0, 12)}`;
|
|
276
|
+
}
|
|
277
|
+
var AWS_PARTITIONS = {
|
|
278
|
+
"aws": { regionPrefix: null, dnsSuffix: "amazonaws.com" },
|
|
279
|
+
"aws-cn": { regionPrefix: "cn-", dnsSuffix: "amazonaws.com.cn" },
|
|
280
|
+
"aws-us-gov": { regionPrefix: "us-gov-", dnsSuffix: "amazonaws.com" },
|
|
281
|
+
"aws-iso": { regionPrefix: "us-iso-", dnsSuffix: "c2s.ic.gov" },
|
|
282
|
+
"aws-iso-b": { regionPrefix: "us-isob-", dnsSuffix: "sc2s.sgov.gov" }
|
|
283
|
+
};
|
|
284
|
+
var PARTITION_ENTRIES = Object.entries(AWS_PARTITIONS);
|
|
285
|
+
function partitionForRegion(region) {
|
|
286
|
+
if (!region) return "aws";
|
|
287
|
+
for (const [partition, { regionPrefix }] of PARTITION_ENTRIES) {
|
|
288
|
+
if (regionPrefix && region.startsWith(regionPrefix)) return partition;
|
|
289
|
+
}
|
|
290
|
+
return "aws";
|
|
291
|
+
}
|
|
292
|
+
function dnsSuffixForPartition(partition) {
|
|
293
|
+
return Object.hasOwn(AWS_PARTITIONS, partition) ? AWS_PARTITIONS[partition].dnsSuffix : AWS_PARTITIONS.aws.dnsSuffix;
|
|
294
|
+
}
|
|
295
|
+
var CACHE_MAX_ENTRIES = 5e3;
|
|
296
|
+
async function loadSdk(pkg) {
|
|
297
|
+
return await import(pkg);
|
|
298
|
+
}
|
|
299
|
+
function fetchWithTimeout(url, init = {}, timeoutMs = loadEventsConfig().reportingFetchTimeoutMs) {
|
|
300
|
+
return fetch(url, { ...init, signal: AbortSignal.timeout(timeoutMs) });
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
// ../pipeline-events/src/auth.ts
|
|
304
|
+
var TOKEN_REFRESH_FRACTION = 0.8;
|
|
305
|
+
var credential = createPlatformCredential({
|
|
306
|
+
secretName: () => loadEventsConfig().platformSecretName,
|
|
307
|
+
envKeyVar: PLATFORM_ACCESS_KEY_ENV
|
|
308
|
+
});
|
|
309
|
+
var cachedToken = null;
|
|
310
|
+
var cachedTokenExpiresAt = 0;
|
|
311
|
+
async function getAuthToken() {
|
|
312
|
+
if (cachedToken && Date.now() < cachedTokenExpiresAt) return cachedToken;
|
|
313
|
+
const baseUrl2 = loadEventsConfig().platformBaseUrl;
|
|
314
|
+
if (!baseUrl2) throw new Error("PLATFORM_BASE_URL environment variable is required");
|
|
315
|
+
const key = await credential.getKey();
|
|
316
|
+
const res = await fetchWithTimeout(`${baseUrl2}/api/auth/token/exchange`, {
|
|
317
|
+
method: "POST",
|
|
318
|
+
headers: { "Content-Type": "application/json", "Accept": "application/json" },
|
|
319
|
+
body: JSON.stringify({ key })
|
|
320
|
+
});
|
|
321
|
+
if (!res.ok) {
|
|
322
|
+
if (res.status === 401 || res.status === 403) {
|
|
323
|
+
credential.invalidate();
|
|
324
|
+
throw new Error(
|
|
325
|
+
`Access-key exchange refused (${res.status}) \u2014 the stored key is unknown, revoked, expired, its service account is disabled, or this address is outside the key\u2019s IP allowlist`
|
|
326
|
+
);
|
|
327
|
+
}
|
|
328
|
+
throw new Error(`Access-key exchange failed: ${res.status}`);
|
|
329
|
+
}
|
|
330
|
+
const body = await res.json().catch(() => ({}));
|
|
331
|
+
const accessToken = body.data?.accessToken;
|
|
332
|
+
if (!accessToken) throw new Error("Access-key exchange returned no access token");
|
|
333
|
+
const ttlMs = (typeof body.data?.expiresIn === "number" && body.data.expiresIn > 0 ? body.data.expiresIn : 300) * 1e3;
|
|
334
|
+
cachedToken = accessToken;
|
|
335
|
+
cachedTokenExpiresAt = Date.now() + ttlMs * TOKEN_REFRESH_FRACTION;
|
|
336
|
+
log.info("Exchanged the stored service-account key for a platform token");
|
|
337
|
+
return accessToken;
|
|
338
|
+
}
|
|
339
|
+
function invalidateCredential() {
|
|
340
|
+
cachedToken = null;
|
|
341
|
+
cachedTokenExpiresAt = 0;
|
|
342
|
+
credential.invalidate();
|
|
343
|
+
}
|
|
344
|
+
function _resetAuthForTests() {
|
|
345
|
+
cachedToken = null;
|
|
346
|
+
cachedTokenExpiresAt = 0;
|
|
347
|
+
credential.reset();
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
// ../pipeline-events/src/health.ts
|
|
351
|
+
var sqsMod;
|
|
352
|
+
var cwMod;
|
|
353
|
+
var cwClientsByRegion;
|
|
354
|
+
async function cwClient(region) {
|
|
355
|
+
if (!cwMod) cwMod = await loadSdk("@aws-sdk/client-cloudwatch");
|
|
356
|
+
if (!cwClientsByRegion) cwClientsByRegion = /* @__PURE__ */ new Map();
|
|
357
|
+
let client2 = cwClientsByRegion.get(region);
|
|
358
|
+
if (!client2) {
|
|
359
|
+
client2 = new cwMod.CloudWatchClient({ region });
|
|
360
|
+
cwClientsByRegion.set(region, client2);
|
|
361
|
+
}
|
|
362
|
+
return client2;
|
|
363
|
+
}
|
|
364
|
+
var sqsClientsByRegion;
|
|
365
|
+
async function sqsClient(region) {
|
|
366
|
+
if (!sqsMod) sqsMod = await loadSdk("@aws-sdk/client-sqs");
|
|
367
|
+
if (!sqsClientsByRegion) sqsClientsByRegion = /* @__PURE__ */ new Map();
|
|
368
|
+
let client2 = sqsClientsByRegion.get(region);
|
|
369
|
+
if (!client2) {
|
|
370
|
+
client2 = new sqsMod.SQSClient({ region });
|
|
371
|
+
sqsClientsByRegion.set(region, client2);
|
|
372
|
+
}
|
|
373
|
+
return client2;
|
|
374
|
+
}
|
|
375
|
+
var forwardedByOrg = new BoundedMap(CACHE_MAX_ENTRIES);
|
|
376
|
+
var lastEventAtByOrg = new BoundedMap(CACHE_MAX_ENTRIES);
|
|
377
|
+
var lastHealthAt = 0;
|
|
378
|
+
var lastRedriveAt = 0;
|
|
379
|
+
function deriveQueues(mainQueueArn) {
|
|
380
|
+
if (!mainQueueArn) return void 0;
|
|
381
|
+
const parts = mainQueueArn.split(":");
|
|
382
|
+
if (parts.length < 6 || parts[0] !== "arn" || parts[2] !== "sqs") return void 0;
|
|
383
|
+
const [, partition, , region, account, name] = parts;
|
|
384
|
+
const dlqArn2 = loadEventsConfig().dlqArn || `arn:${partition}:sqs:${region}:${account}:${name}-dlq`;
|
|
385
|
+
const dlqName = dlqArn2.split(":").pop() ?? `${name}-dlq`;
|
|
386
|
+
const dlqUrl = `https://sqs.${region}.${dnsSuffixForPartition(partition)}/${account}/${dlqName}`;
|
|
387
|
+
return { region, mainArn: mainQueueArn, dlqArn: dlqArn2, dlqName, dlqUrl };
|
|
388
|
+
}
|
|
389
|
+
async function dlqDepth(region, dlqUrl) {
|
|
390
|
+
if (!sqsMod) sqsMod = await loadSdk("@aws-sdk/client-sqs");
|
|
391
|
+
const client2 = await sqsClient(region);
|
|
392
|
+
const out = await client2.send(new sqsMod.GetQueueAttributesCommand({
|
|
393
|
+
QueueUrl: dlqUrl,
|
|
394
|
+
AttributeNames: ["ApproximateNumberOfMessages"]
|
|
395
|
+
}));
|
|
396
|
+
const n = Number(out.Attributes?.ApproximateNumberOfMessages ?? "0");
|
|
397
|
+
return Number.isFinite(n) ? n : 0;
|
|
398
|
+
}
|
|
399
|
+
async function dlqOldestAgeSec(region, dlqName) {
|
|
400
|
+
if (!cwMod) cwMod = await loadSdk("@aws-sdk/client-cloudwatch");
|
|
401
|
+
const client2 = await cwClient(region);
|
|
402
|
+
const end = /* @__PURE__ */ new Date();
|
|
403
|
+
const out = await client2.send(new cwMod.GetMetricStatisticsCommand({
|
|
404
|
+
Namespace: "AWS/SQS",
|
|
405
|
+
MetricName: "ApproximateAgeOfOldestMessage",
|
|
406
|
+
Dimensions: [{ Name: "QueueName", Value: dlqName }],
|
|
407
|
+
StartTime: new Date(end.getTime() - 15 * 60 * 1e3),
|
|
408
|
+
EndTime: end,
|
|
409
|
+
Period: 60,
|
|
410
|
+
Statistics: ["Maximum"]
|
|
411
|
+
}));
|
|
412
|
+
const latest = (out.Datapoints ?? []).filter((d) => Number.isFinite(d.Maximum)).sort((a, b) => new Date(b.Timestamp ?? 0).getTime() - new Date(a.Timestamp ?? 0).getTime())[0];
|
|
413
|
+
return latest?.Maximum;
|
|
414
|
+
}
|
|
415
|
+
async function hasActiveMoveTask(region, dlqArn2) {
|
|
416
|
+
if (!sqsMod) sqsMod = await loadSdk("@aws-sdk/client-sqs");
|
|
417
|
+
const client2 = await sqsClient(region);
|
|
418
|
+
const out = await client2.send(new sqsMod.ListMessageMoveTasksCommand({ SourceArn: dlqArn2 }));
|
|
419
|
+
return (out.Results ?? []).some((t) => t.Status === "RUNNING");
|
|
420
|
+
}
|
|
421
|
+
async function startMoveTask(region, dlqArn2, mainArn) {
|
|
422
|
+
if (!sqsMod) sqsMod = await loadSdk("@aws-sdk/client-sqs");
|
|
423
|
+
const client2 = await sqsClient(region);
|
|
424
|
+
await client2.send(new sqsMod.StartMessageMoveTaskCommand({ SourceArn: dlqArn2, DestinationArn: mainArn }));
|
|
425
|
+
}
|
|
426
|
+
async function postIngestHealth(baseUrl2, body, requestId) {
|
|
427
|
+
try {
|
|
428
|
+
const token = await getAuthToken();
|
|
429
|
+
const res = await fetchWithTimeout(`${baseUrl2}/api/reports/ingest-health`, {
|
|
430
|
+
method: "POST",
|
|
431
|
+
headers: { "Content-Type": "application/json", "Authorization": `Bearer ${token}`, ...correlationHeaders({ requestId }) },
|
|
432
|
+
body: JSON.stringify(body)
|
|
433
|
+
});
|
|
434
|
+
if (!res.ok) {
|
|
435
|
+
log.warn("ingest-health POST returned non-2xx (ignored)", { status: res.status, orgId: body.orgId });
|
|
436
|
+
return false;
|
|
437
|
+
}
|
|
438
|
+
return true;
|
|
439
|
+
} catch (err) {
|
|
440
|
+
log.warn("ingest-health POST failed (ignored)", { error: String(err), orgId: body.orgId });
|
|
441
|
+
return false;
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
async function reportHealthAndRedrive(baseUrl2, mainQueueArn, requestId) {
|
|
445
|
+
const { healthIntervalMs, redriveIntervalMs, redriveMaxAgeSec } = loadEventsConfig();
|
|
446
|
+
const now = Date.now();
|
|
447
|
+
if (now - lastHealthAt < healthIntervalMs) return;
|
|
448
|
+
lastHealthAt = now;
|
|
449
|
+
try {
|
|
450
|
+
const q = deriveQueues(mainQueueArn);
|
|
451
|
+
let depth = 0;
|
|
452
|
+
if (q) {
|
|
453
|
+
try {
|
|
454
|
+
depth = await dlqDepth(q.region, q.dlqUrl);
|
|
455
|
+
} catch (err) {
|
|
456
|
+
log.warn("DLQ stats check failed (ignored)", { error: err?.name ?? String(err) });
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
const orgKeys = /* @__PURE__ */ new Set([...forwardedByOrg.keys(), ...lastEventAtByOrg.keys()]);
|
|
460
|
+
if (orgKeys.size === 0) orgKeys.add("");
|
|
461
|
+
for (const key of orgKeys) {
|
|
462
|
+
const forwarded = forwardedByOrg.get(key) ?? 0;
|
|
463
|
+
const lastEventAt = lastEventAtByOrg.get(key);
|
|
464
|
+
const ok = await postIngestHealth(baseUrl2, {
|
|
465
|
+
...key ? { orgId: key } : {},
|
|
466
|
+
forwarded,
|
|
467
|
+
dropped: depth,
|
|
468
|
+
lastEventAt
|
|
469
|
+
}, requestId);
|
|
470
|
+
if (ok) forwardedByOrg.set(key, 0);
|
|
471
|
+
}
|
|
472
|
+
if (q && depth > 0 && now - lastRedriveAt >= redriveIntervalMs) {
|
|
473
|
+
let oldestAgeSec;
|
|
474
|
+
try {
|
|
475
|
+
oldestAgeSec = await dlqOldestAgeSec(q.region, q.dlqName);
|
|
476
|
+
} catch (err) {
|
|
477
|
+
log.warn("DLQ oldest-message age read failed \u2014 skipping redrive (ignored)", { error: err?.name ?? String(err) });
|
|
478
|
+
}
|
|
479
|
+
if (oldestAgeSec === void 0) {
|
|
480
|
+
log.info("DLQ oldest-message age not available yet \u2014 redrive deferred", { dlq: arnRef(q.dlqArn), dropped: depth });
|
|
481
|
+
} else if (oldestAgeSec > redriveMaxAgeSec) {
|
|
482
|
+
log.warn("DLQ oldest message exceeds poison-age ceiling \u2014 skipping redrive (needs manual attention)", {
|
|
483
|
+
dlq: arnRef(q.dlqArn),
|
|
484
|
+
dropped: depth,
|
|
485
|
+
oldestAgeSec,
|
|
486
|
+
ceilingSec: redriveMaxAgeSec
|
|
487
|
+
});
|
|
488
|
+
} else {
|
|
489
|
+
try {
|
|
490
|
+
if (!await hasActiveMoveTask(q.region, q.dlqArn)) {
|
|
491
|
+
lastRedriveAt = now;
|
|
492
|
+
await startMoveTask(q.region, q.dlqArn, q.mainArn);
|
|
493
|
+
log.info("Started self-healing DLQ\u2192main redrive", { dlq: arnRef(q.dlqArn), dropped: depth, oldestAgeSec });
|
|
494
|
+
}
|
|
495
|
+
} catch (err) {
|
|
496
|
+
log.warn("DLQ redrive failed (ignored)", { error: err?.name ?? String(err) });
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
} catch (err) {
|
|
501
|
+
log.warn("health/redrive step failed (ignored)", { error: String(err) });
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
function recordForwarded(events) {
|
|
505
|
+
for (const e of events) {
|
|
506
|
+
const key = e.orgId ?? "";
|
|
507
|
+
forwardedByOrg.set(key, (forwardedByOrg.get(key) ?? 0) + 1);
|
|
508
|
+
const at = e.completedAt || e.startedAt;
|
|
509
|
+
if (at) {
|
|
510
|
+
const prev = lastEventAtByOrg.get(key);
|
|
511
|
+
if (!prev || at > prev) lastEventAtByOrg.set(key, at);
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
var ssmMod;
|
|
516
|
+
var ssm;
|
|
517
|
+
var lastStampAt = 0;
|
|
518
|
+
var STAMP_EVERY_MS = 6e4;
|
|
519
|
+
async function stampLastEvent(now = Date.now()) {
|
|
520
|
+
const name = process.env.LAST_EVENT_PARAMETER?.trim();
|
|
521
|
+
if (!name || now - lastStampAt < STAMP_EVERY_MS) return;
|
|
522
|
+
lastStampAt = now;
|
|
523
|
+
try {
|
|
524
|
+
if (!ssmMod) ssmMod = await loadSdk("@aws-sdk/client-ssm");
|
|
525
|
+
ssm ??= new ssmMod.SSMClient({});
|
|
526
|
+
await ssm.send(new ssmMod.PutParameterCommand({ Name: name, Value: new Date(now).toISOString(), Type: "String", Overwrite: true }));
|
|
527
|
+
} catch (err) {
|
|
528
|
+
log.warn("Last-event stamp failed (ignored)", { error: String(err) });
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
function _resetHealthForTests() {
|
|
532
|
+
forwardedByOrg.clear();
|
|
533
|
+
lastEventAtByOrg.clear();
|
|
534
|
+
lastHealthAt = 0;
|
|
535
|
+
lastRedriveAt = 0;
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
// ../pipeline-events/src/failure-reason.ts
|
|
539
|
+
function phaseMs(p) {
|
|
540
|
+
const toMs = (v) => v instanceof Date || typeof v === "string" || typeof v === "number" ? new Date(v).getTime() : NaN;
|
|
541
|
+
const exact = toMs(p.endTime) - toMs(p.startTime);
|
|
542
|
+
if (Number.isFinite(exact) && exact >= 0) return Math.round(exact);
|
|
543
|
+
const d = p.durationInSeconds;
|
|
544
|
+
return typeof d === "number" && Number.isFinite(d) && d >= 0 ? Math.round(d * 1e3) : void 0;
|
|
545
|
+
}
|
|
546
|
+
function buildPhasesOf(phases) {
|
|
547
|
+
if (!Array.isArray(phases)) return null;
|
|
548
|
+
const out = {};
|
|
549
|
+
for (const p of phases) {
|
|
550
|
+
const ms = phaseMs(p);
|
|
551
|
+
if (ms === void 0) continue;
|
|
552
|
+
if (p.phaseType === "QUEUED") out.queuedMs = ms;
|
|
553
|
+
else if (p.phaseType === "PROVISIONING") out.provisioningMs = ms;
|
|
554
|
+
}
|
|
555
|
+
return out.queuedMs === void 0 && out.provisioningMs === void 0 ? null : out;
|
|
556
|
+
}
|
|
557
|
+
var MAX_FILTER_PAGES = 10;
|
|
558
|
+
var loader = loadSdk;
|
|
559
|
+
var clients = /* @__PURE__ */ new Map();
|
|
560
|
+
async function client(kind, region) {
|
|
561
|
+
const mod = kind === "codebuild" ? await loader("@aws-sdk/client-codebuild") : await loader("@aws-sdk/client-cloudwatch-logs");
|
|
562
|
+
const key = `${kind}:${region}`;
|
|
563
|
+
let c = clients.get(key);
|
|
564
|
+
if (!c) {
|
|
565
|
+
c = kind === "codebuild" ? new mod.CodeBuildClient({ region }) : new mod.CloudWatchLogsClient({ region });
|
|
566
|
+
clients.set(key, c);
|
|
567
|
+
}
|
|
568
|
+
return { client: c, mod };
|
|
569
|
+
}
|
|
570
|
+
var BUILD_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{1,254}:[0-9a-f-]{36}$/;
|
|
571
|
+
function codeBuildIdOf(detail) {
|
|
572
|
+
const type = detail.type;
|
|
573
|
+
if (type?.provider !== void 0 && type.provider !== "CodeBuild") return null;
|
|
574
|
+
const result = detail["execution-result"];
|
|
575
|
+
const id = result?.["external-execution-id"];
|
|
576
|
+
return typeof id === "string" && BUILD_ID_RE.test(id) ? id : null;
|
|
577
|
+
}
|
|
578
|
+
async function readBuildCompute(region, buildId) {
|
|
579
|
+
try {
|
|
580
|
+
const cb = await client("codebuild", region);
|
|
581
|
+
const out = await cb.client.send(
|
|
582
|
+
new cb.mod.BatchGetBuildsCommand({ ids: [buildId] })
|
|
583
|
+
);
|
|
584
|
+
const build = out.builds?.[0];
|
|
585
|
+
return { computeType: build?.environment?.computeType ?? null, phases: buildPhasesOf(build?.phases) };
|
|
586
|
+
} catch (err) {
|
|
587
|
+
log.warn("Could not read the build's compute size (forwarding without it)", {
|
|
588
|
+
buildId,
|
|
589
|
+
error: String(err)
|
|
590
|
+
});
|
|
591
|
+
return { computeType: null, phases: null };
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
async function readSynthFailure(region, buildId) {
|
|
595
|
+
try {
|
|
596
|
+
const cb = await client("codebuild", region);
|
|
597
|
+
const out = await cb.client.send(
|
|
598
|
+
new cb.mod.BatchGetBuildsCommand({ ids: [buildId] })
|
|
599
|
+
);
|
|
600
|
+
const logs = out.builds?.[0]?.logs;
|
|
601
|
+
if (!logs?.groupName || !logs.streamName) return null;
|
|
602
|
+
const cw = await client("logs", region);
|
|
603
|
+
let nextToken;
|
|
604
|
+
for (let page = 0; page < MAX_FILTER_PAGES; page++) {
|
|
605
|
+
const res = await cw.client.send(new cw.mod.FilterLogEventsCommand({
|
|
606
|
+
logGroupName: logs.groupName,
|
|
607
|
+
logStreamNames: [logs.streamName],
|
|
608
|
+
filterPattern: `"${SYNTH_FAILURE_MARKER}"`,
|
|
609
|
+
limit: 5,
|
|
610
|
+
...nextToken ? { nextToken } : {}
|
|
611
|
+
}));
|
|
612
|
+
for (const event of res.events ?? []) {
|
|
613
|
+
const failure = typeof event.message === "string" ? parseSynthFailure(event.message) : null;
|
|
614
|
+
if (failure) return failure;
|
|
615
|
+
}
|
|
616
|
+
if (!res.nextToken || res.nextToken === nextToken) return null;
|
|
617
|
+
nextToken = res.nextToken;
|
|
618
|
+
}
|
|
619
|
+
return null;
|
|
620
|
+
} catch (err) {
|
|
621
|
+
log.warn("Could not read the failed build's structured failure reason (forwarding without it)", {
|
|
622
|
+
buildId,
|
|
623
|
+
error: err instanceof Error ? err.message : String(err)
|
|
624
|
+
});
|
|
625
|
+
return null;
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
// ../pipeline-events/src/scm.ts
|
|
630
|
+
import { GetSecretValueCommand as GetSecretValueCommand2, SecretsManagerClient as SecretsManagerClient2 } from "@aws-sdk/client-secrets-manager";
|
|
631
|
+
|
|
632
|
+
// ../api-core/lib/types/pipeline-runners.js
|
|
633
|
+
var DEPLOY_CAPABILITY = "deploy:1";
|
|
634
|
+
var SOURCES_CAPABILITY = "sources:1";
|
|
635
|
+
var INSPECT_CAPABILITY = "inspect:1";
|
|
636
|
+
var INSPECT_CONNECTION_CAPABILITY = "inspect_connection:1";
|
|
637
|
+
var DEPLOY_ACTION_CAPABILITY = {
|
|
638
|
+
deploy: DEPLOY_CAPABILITY,
|
|
639
|
+
deploy_status: DEPLOY_CAPABILITY,
|
|
640
|
+
deploy_cancel: DEPLOY_CAPABILITY,
|
|
641
|
+
undeploy: DEPLOY_CAPABILITY
|
|
642
|
+
};
|
|
643
|
+
var SOURCE_ACTION_CAPABILITY = {
|
|
644
|
+
list_sources: SOURCES_CAPABILITY,
|
|
645
|
+
check_source: SOURCES_CAPABILITY
|
|
646
|
+
};
|
|
647
|
+
var INSPECT_ACTION_CAPABILITY = {
|
|
648
|
+
inspect_repository: INSPECT_CAPABILITY
|
|
649
|
+
};
|
|
650
|
+
var INSPECT_CONNECTION_ACTION_CAPABILITY = {
|
|
651
|
+
inspect_connection_start: INSPECT_CONNECTION_CAPABILITY,
|
|
652
|
+
inspect_connection_status: INSPECT_CONNECTION_CAPABILITY
|
|
653
|
+
};
|
|
654
|
+
var ACTION_CAPABILITY = {
|
|
655
|
+
...DEPLOY_ACTION_CAPABILITY,
|
|
656
|
+
...SOURCE_ACTION_CAPABILITY,
|
|
657
|
+
...INSPECT_ACTION_CAPABILITY,
|
|
658
|
+
...INSPECT_CONNECTION_ACTION_CAPABILITY
|
|
659
|
+
};
|
|
660
|
+
var RUNNER_ERRORS = {
|
|
661
|
+
// -- The pipeline service's answers --
|
|
662
|
+
RUNNERS_UNAVAILABLE: { httpStatus: 409, retryable: false, category: "platform" },
|
|
663
|
+
NO_RUNNER: { httpStatus: 409, retryable: false, category: "platform" },
|
|
664
|
+
RUNNER_UNREACHABLE: { httpStatus: 409, retryable: false, category: "platform" },
|
|
665
|
+
PIPELINE_NOT_FOUND_IN_RUNNERS: { httpStatus: 404, retryable: false, category: "platform" },
|
|
666
|
+
AMBIGUOUS_RUNNER: { httpStatus: 409, retryable: false, category: "platform" },
|
|
667
|
+
RUNNER_PING_FAILED: { httpStatus: 422, retryable: false, category: "platform" },
|
|
668
|
+
RUNNER_REVOKED: { httpStatus: 409, retryable: false, category: "platform" },
|
|
669
|
+
RUNNER_LIMIT: { httpStatus: 409, retryable: false, category: "platform" },
|
|
670
|
+
/** Another non-revoked runner of the org already has this label (labels are how the CLI finds a runner). */
|
|
671
|
+
RUNNER_LABEL_TAKEN: { httpStatus: 409, retryable: false, category: "platform" },
|
|
672
|
+
/**
|
|
673
|
+
* The connector answered from a different AWS account than the one it was
|
|
674
|
+
* pinned to: nothing is delivered to it until an admin confirms the new
|
|
675
|
+
* account (POST …/runners/:id/confirm-account).
|
|
676
|
+
*/
|
|
677
|
+
RUNNER_ACCOUNT_CHANGED: { httpStatus: 409, retryable: false, category: "platform" },
|
|
678
|
+
RUN_REQUEST_RATE_LIMITED: { httpStatus: 429, retryable: false, category: "platform" },
|
|
679
|
+
TOO_MANY_PENDING: { httpStatus: 429, retryable: false, category: "platform" },
|
|
680
|
+
RUNNER_UPDATE_REQUIRED: { httpStatus: 409, retryable: false, category: "platform" },
|
|
681
|
+
RUNNER_PENDING: { httpStatus: 409, retryable: false, category: "platform" },
|
|
682
|
+
/** The org's effective signing key exists but cannot be decrypted (wrong master, rotated KMS key). That org only. */
|
|
683
|
+
RUNNER_KEY_UNREADABLE: { httpStatus: 409, retryable: false, category: "platform" },
|
|
684
|
+
/** The org has no effective signing key (no shared key to fall back to). */
|
|
685
|
+
RUNNER_KEY_MISSING: { httpStatus: 409, retryable: false, category: "platform" },
|
|
686
|
+
/** Generate: the org already has a key. */
|
|
687
|
+
RUNNER_KEY_EXISTS: { httpStatus: 409, retryable: false, category: "platform" },
|
|
688
|
+
/** Rotate / mode switch / revoke while a rotation (a next or retiring key) or a mode switch is in progress. */
|
|
689
|
+
RUNNER_KEY_TRANSITION_IN_PROGRESS: { httpStatus: 409, retryable: false, category: "platform" },
|
|
690
|
+
/** Cancel with no next key, or finish with no retiring key. */
|
|
691
|
+
RUNNER_KEY_NO_ROTATION: { httpStatus: 409, retryable: false, category: "platform" },
|
|
692
|
+
/** Finish before the retiring key's retire_after. */
|
|
693
|
+
RUNNER_KEY_RETIRE_TOO_EARLY: { httpStatus: 409, retryable: false, category: "platform" },
|
|
694
|
+
/** A key write (generate / rotate / finish / cancel / revoke) on an org in inherit mode. */
|
|
695
|
+
RUNNER_KEY_INHERITED: { httpStatus: 409, retryable: false, category: "platform" },
|
|
696
|
+
/** A key-mode change on a root org (root orgs are always `own`). */
|
|
697
|
+
RUNNER_KEY_MODE_ROOT_ORG: { httpStatus: 409, retryable: false, category: "platform" },
|
|
698
|
+
/** Revoke: the typed confirmation is not the last {@link RUNNER_KEY_REVOKE_CONFIRM_CHARS} characters of the active kid. */
|
|
699
|
+
RUNNER_KEY_CONFIRMATION_MISMATCH: { httpStatus: 400, retryable: false, category: "platform" },
|
|
700
|
+
// -- Deploys through a runner (the pipeline service's answers) --
|
|
701
|
+
/** The runner does not list the `deploy:1` capability (an old bundle, or a stack without --deploy): update it with {@link DEPLOY_SETUP_COMMAND}. */
|
|
702
|
+
RUNNER_DEPLOY_UNSUPPORTED: { httpStatus: 409, retryable: false, category: "platform" },
|
|
703
|
+
/** Several runners can deploy this pipeline and none was named (`details.runners`: the deployable ones). */
|
|
704
|
+
DEPLOY_RUNNER_REQUIRED: { httpStatus: 409, retryable: false, category: "platform" },
|
|
705
|
+
/** The runner named (or the only one) cannot deploy this pipeline (`details.reason`: a {@link DeployTargetReason}). */
|
|
706
|
+
RUNNER_NOT_DEPLOYABLE: { httpStatus: 409, retryable: false, category: "platform" },
|
|
707
|
+
/** The pipeline already has a registry row: deploys through a runner are for a never-deployed pipeline only. */
|
|
708
|
+
ALREADY_DEPLOYED: { httpStatus: 409, retryable: false, category: "platform" },
|
|
709
|
+
/**
|
|
710
|
+
* Another deploy of this pipeline is active (`details.requestId`). Also what a
|
|
711
|
+
* runner answers when its project already builds this pipeline for another
|
|
712
|
+
* request id (the one platform code a runner may send: final, like any 4xx).
|
|
713
|
+
*/
|
|
714
|
+
DEPLOY_IN_PROGRESS: { httpStatus: 409, retryable: false, category: "platform" },
|
|
715
|
+
/** The region asked for is not one of the runner's allowed regions (or several are and none was named). */
|
|
716
|
+
DEPLOY_REGION_NOT_ALLOWED: { httpStatus: 409, retryable: false, category: "platform" },
|
|
717
|
+
/** The pipeline's pinned toolchain release ships no cdk-synth image speaking {@link DEPLOY_JOB_PROTOCOL_VERSION}. */
|
|
718
|
+
TOOLCHAIN_TOO_OLD_FOR_DEPLOY: { httpStatus: 409, retryable: false, category: "platform" },
|
|
719
|
+
/** Cancel of a deploy that already finished. */
|
|
720
|
+
DEPLOY_NOT_CANCELLABLE: { httpStatus: 409, retryable: false, category: "platform" },
|
|
721
|
+
/** DEPLOY_REQUESTS_PER_HOUR for the org. */
|
|
722
|
+
DEPLOY_RATE_LIMITED: { httpStatus: 429, retryable: false, category: "platform" },
|
|
723
|
+
/** MAX_ACTIVE_DEPLOYS_PER_RUNNER deploys already active on the runner. */
|
|
724
|
+
TOO_MANY_DEPLOYS: { httpStatus: 429, retryable: false, category: "platform" },
|
|
725
|
+
/** The deploy job's grant (or session) was refused (`details.reason`: a {@link DeployGrantRejectionReason}). */
|
|
726
|
+
DEPLOY_GRANT_INVALID: { httpStatus: 401, retryable: false, category: "platform" },
|
|
727
|
+
// -- A runner's answers --
|
|
728
|
+
SIGNATURE_INVALID: { httpStatus: 401, retryable: false, category: "runner" },
|
|
729
|
+
RUNNER_REFUSED: { httpStatus: 403, retryable: false, category: "runner" },
|
|
730
|
+
RUNNER_PERMISSION_DENIED: { httpStatus: 403, retryable: false, category: "runner" },
|
|
731
|
+
PIPELINE_NOT_FOUND: { httpStatus: 404, retryable: false, category: "runner" },
|
|
732
|
+
AMBIGUOUS_PIPELINE: { httpStatus: 409, retryable: false, category: "runner" },
|
|
733
|
+
PIPELINE_NOT_TAGGED: { httpStatus: 409, retryable: false, category: "runner" },
|
|
734
|
+
PIPELINE_IDENTITY_MISMATCH: { httpStatus: 409, retryable: false, category: "runner" },
|
|
735
|
+
/** The tagging index has not caught up with a fresh deploy (retried briefly). */
|
|
736
|
+
NOT_YET_VISIBLE: { httpStatus: 409, retryable: true, category: "runner" },
|
|
737
|
+
/** The runner holds this request in flight with no final result yet. */
|
|
738
|
+
DUPLICATE: { httpStatus: 409, retryable: true, category: "runner" },
|
|
739
|
+
/**
|
|
740
|
+
* Anything unexpected inside the runner, or a reply the platform can't use
|
|
741
|
+
* (an unknown code, a non-JSON 4xx). Final: a runner's own 4xx reply fails
|
|
742
|
+
* the request. The runner answers it with a bare 500, which — like every
|
|
743
|
+
* 5xx — the dispatcher retries as a transport failure (`http_5xx`), not by
|
|
744
|
+
* this code.
|
|
745
|
+
*/
|
|
746
|
+
RUNNER_ERROR: { httpStatus: 500, retryable: false, category: "runner" },
|
|
747
|
+
// -- A runner's answers to the deploy actions --
|
|
748
|
+
/** The stack was not set up with --deploy (the platform clears the runner's stored capabilities). */
|
|
749
|
+
DEPLOY_NOT_ENABLED: { httpStatus: 403, retryable: false, category: "runner" },
|
|
750
|
+
/** A pipeline tagged with this pipeline id already exists in the account (the platform links it instead). */
|
|
751
|
+
PIPELINE_ALREADY_DEPLOYED: { httpStatus: 409, retryable: false, category: "runner" },
|
|
752
|
+
/** The deploy project is at its concurrent build limit (delivered again). */
|
|
753
|
+
DEPLOY_BUSY: { httpStatus: 409, retryable: true, category: "runner" },
|
|
754
|
+
/** deploy_status / deploy_cancel: no such build in the runner's own deploy project. */
|
|
755
|
+
DEPLOY_BUILD_NOT_FOUND: { httpStatus: 404, retryable: false, category: "runner" },
|
|
756
|
+
// -- A runner's answers to the source actions (check_source's refusals; list_sources uses only the first) --
|
|
757
|
+
/** The region asked about is not one of the runner's allowed regions. */
|
|
758
|
+
SOURCE_REGION_NOT_ALLOWED: { httpStatus: 403, retryable: false, category: "runner" },
|
|
759
|
+
/** No such CodeConnections connection in the account. */
|
|
760
|
+
SOURCE_CONNECTION_NOT_FOUND: { httpStatus: 404, retryable: false, category: "runner" },
|
|
761
|
+
/** The connection exists but is not AVAILABLE (its handshake is pending, or it is in error). */
|
|
762
|
+
SOURCE_CONNECTION_NOT_AVAILABLE: { httpStatus: 409, retryable: false, category: "runner" },
|
|
763
|
+
/** The connection ARN names another AWS account than the runner's. */
|
|
764
|
+
SOURCE_CONNECTION_WRONG_ACCOUNT: { httpStatus: 409, retryable: false, category: "runner" },
|
|
765
|
+
/** The connection ARN names another region than the deploy's. */
|
|
766
|
+
SOURCE_CONNECTION_WRONG_REGION: { httpStatus: 409, retryable: false, category: "runner" },
|
|
767
|
+
/** The connection is for another Git provider or server than the repository's host. */
|
|
768
|
+
SOURCE_CONNECTION_WRONG_PROVIDER: { httpStatus: 409, retryable: false, category: "runner" },
|
|
769
|
+
/** A token-less GitHub source, and neither the owner's nor the org's GitHub token secret exists in the region. */
|
|
770
|
+
GITHUB_TOKEN_MISSING: { httpStatus: 409, retryable: false, category: "runner" },
|
|
771
|
+
// -- A runner's answers to the connection inspection (its start also answers the source refusals above) --
|
|
772
|
+
/** inspect_connection_status: no such build in the runner's own inspect project. */
|
|
773
|
+
INSPECT_BUILD_NOT_FOUND: { httpStatus: 404, retryable: false, category: "runner" },
|
|
774
|
+
/** The inspect project lives in the runner stack's own region; the connection must be there too. */
|
|
775
|
+
INSPECT_REGION_UNSUPPORTED: { httpStatus: 409, retryable: false, category: "runner" },
|
|
776
|
+
/** The inspect project is at its concurrent build limit. */
|
|
777
|
+
INSPECT_BUSY: { httpStatus: 409, retryable: false, category: "runner" },
|
|
778
|
+
// -- Recorded by the platform --
|
|
779
|
+
/** Not delivered within the request's lifetime. */
|
|
780
|
+
/** A reply whose echoed connector id or request id is not the request's (or an identity:1 reply without one). */
|
|
781
|
+
RUNNER_IDENTITY_MISMATCH: { httpStatus: null, retryable: false, category: "recorded" },
|
|
782
|
+
RUN_REQUEST_EXPIRED: { httpStatus: null, retryable: false, category: "recorded" },
|
|
783
|
+
/** A discovery probe that found nothing (probe rows only). */
|
|
784
|
+
NO_MATCH: { httpStatus: null, retryable: false, category: "recorded" },
|
|
785
|
+
/**
|
|
786
|
+
* The runner a queued request was routed to is no longer one its org may use
|
|
787
|
+
* (an ancestor's runner un-shared from teams, or the team moved under another
|
|
788
|
+
* parent): re-checked just before delivery, the request fails instead of
|
|
789
|
+
* being sent, and the pipeline's stale link is cleared (the next run
|
|
790
|
+
* rediscovers).
|
|
791
|
+
*/
|
|
792
|
+
RUNNER_NOT_ELIGIBLE: { httpStatus: null, retryable: false, category: "recorded" }
|
|
793
|
+
};
|
|
794
|
+
var RUNNER_ERROR_CODES = Object.keys(RUNNER_ERRORS);
|
|
795
|
+
var codesIn = (c) => RUNNER_ERROR_CODES.filter((k) => RUNNER_ERRORS[k].category === c);
|
|
796
|
+
var RUNNER_API_ERROR_CODES = codesIn("platform");
|
|
797
|
+
var RUNNER_REPLY_ERROR_CODES = codesIn("runner");
|
|
798
|
+
var STOPPED_EXECUTION_STATUSES = ["stopped", "canceled", "cancelled"];
|
|
799
|
+
var TERMINAL_EXECUTION_STATUSES = ["succeeded", "failed", ...STOPPED_EXECUTION_STATUSES, "superseded"];
|
|
800
|
+
var RUN_REQUEST_TTL_MS = 6e5;
|
|
801
|
+
var RUN_REQUEST_MAX_LIFETIME_SECONDS = RUN_REQUEST_TTL_MS / 1e3;
|
|
802
|
+
var INSPECT_MAX_READ_BYTES = 128 * 1024;
|
|
803
|
+
var INSPECT_MAX_REPLY_BYTES = 1024 * 1024;
|
|
804
|
+
var INSPECT_CONNECTION_DEADLINE_MS = 6 * 6e4;
|
|
805
|
+
var RUNNER_KEY_ACTIVATION_DELAY_MS = 10 * 6e4;
|
|
806
|
+
var RUNNER_KEY_RETIRE_WINDOW_MS = 60 * 6e4;
|
|
807
|
+
var RUNNER_TUNABLE_DEFAULTS = {
|
|
808
|
+
RUN_REQUESTS_PER_MINUTE: "6",
|
|
809
|
+
MAX_PENDING_PER_ORG: "500",
|
|
810
|
+
MAX_IN_FLIGHT_PER_RUNNER: "8",
|
|
811
|
+
RUNNER_HEALTH_PING_INTERVAL_SECONDS: "60",
|
|
812
|
+
RUNNER_UNHEALTHY_AFTER_PINGS: "2",
|
|
813
|
+
RUNNER_KEY_MAX_AGE_DAYS: "365",
|
|
814
|
+
DEPLOY_REQUESTS_PER_HOUR: "20",
|
|
815
|
+
MAX_ACTIVE_DEPLOYS_PER_RUNNER: "2",
|
|
816
|
+
RUNNER_DEPLOY_DEADLINE_MINUTES: "120",
|
|
817
|
+
RUNNER_DEPLOY_STATUS_POLL_SECONDS: "30",
|
|
818
|
+
SOURCE_OPTIONS_REQUESTS_PER_MINUTE: "30",
|
|
819
|
+
SOURCE_OPTIONS_CACHE_SECONDS: "60"
|
|
820
|
+
};
|
|
821
|
+
var RUNNER_DEPLOY_ERRORS = {
|
|
822
|
+
/** The job's grant exchange was refused (reused, unknown, wrong state). */
|
|
823
|
+
DEPLOY_GRANT_REJECTED: { class: "platform", retryable: false, title: "The deploy job's one-time credential was refused." },
|
|
824
|
+
/** The grant expired before the job exchanged it ({@link DEPLOY_GRANT_TTL_MS}): the build queued too long. */
|
|
825
|
+
DEPLOY_GRANT_EXPIRED: { class: "platform", retryable: true, title: "The deploy job started too late to use its credential." },
|
|
826
|
+
/** The job could not read the pipeline through its session. */
|
|
827
|
+
PIPELINE_FETCH_FAILED: { class: "platform", retryable: true, title: "The deploy job could not read this pipeline from the platform." },
|
|
828
|
+
/** A plugin of the pipeline did not resolve (lookup through the session). */
|
|
829
|
+
PLUGIN_RESOLUTION_FAILED: { class: "definition", retryable: false, title: "A plugin this pipeline uses could not be resolved." },
|
|
830
|
+
/** The synthesized pipeline / stack names or region are not the ones the request named. */
|
|
831
|
+
DEPLOY_TARGET_MISMATCH: { class: "definition", retryable: false, title: "The synthesized pipeline is not the one this deploy named." },
|
|
832
|
+
/** A stack of that name exists and is not this pipeline's (tagged for another pipeline, or untagged). */
|
|
833
|
+
STACK_OWNED_BY_OTHER_PIPELINE: { class: "definition", retryable: false, title: "A stack with this pipeline's name already belongs to something else." },
|
|
834
|
+
/** The target region has no CDK bootstrap (`pipeline-manager bootstrap --region <r>`). */
|
|
835
|
+
CDK_NOT_BOOTSTRAPPED: { class: "account_setup", retryable: true, title: "The target region has no CDK bootstrap." },
|
|
836
|
+
/** The region's CDK bootstrap is older than the toolchain needs. */
|
|
837
|
+
CDK_BOOTSTRAP_OUTDATED: { class: "account_setup", retryable: true, title: "The target region's CDK bootstrap is too old for this pipeline." },
|
|
838
|
+
/** Secrets the pipeline needs are not in the account's Secrets Manager. */
|
|
839
|
+
ACCOUNT_SECRETS_MISSING: { class: "account_setup", retryable: true, title: "Secrets this pipeline needs are not in the runner's AWS account." },
|
|
840
|
+
/** A bootstrap role refused an AWS call (or the permissions boundary did). */
|
|
841
|
+
DEPLOY_PERMISSION_DENIED: { class: "aws_permission", retryable: true, title: "AWS refused an action the deploy needed." },
|
|
842
|
+
/** `cdk deploy` failed in CloudFormation. */
|
|
843
|
+
CFN_DEPLOY_FAILED: { class: "cloudformation", retryable: true, title: "CloudFormation could not deploy the pipeline's stack." },
|
|
844
|
+
/** Deleting this pipeline's stack (cleaning a failed first deploy, or an undeploy) did not reach DELETE_COMPLETE. */
|
|
845
|
+
STACK_DELETE_FAILED: { class: "cloudformation", retryable: true, title: "This pipeline's old stack could not be deleted." },
|
|
846
|
+
/** CodeBuild could not pull the cdk-synth image (registry credential or host). */
|
|
847
|
+
DEPLOY_IMAGE_PULL_FAILED: { class: "image", retryable: true, title: "The runner's deploy project could not pull the deploy image." },
|
|
848
|
+
/** The image's deploy-job protocol is not the claim's ({@link DEPLOY_JOB_PROTOCOL_VERSION}). */
|
|
849
|
+
DEPLOY_JOB_PROTOCOL_MISMATCH: { class: "image", retryable: false, title: "The deploy image speaks a different deploy protocol than the platform." },
|
|
850
|
+
/**
|
|
851
|
+
* The synthesized stack has Docker image assets: the deploy build is never
|
|
852
|
+
* privileged (no such mode exists on the runner), so a retry fails the same
|
|
853
|
+
* way. A runtime guard — the stacks this product synthesizes carry none.
|
|
854
|
+
*/
|
|
855
|
+
DEPLOY_NEEDS_PRIVILEGED: { class: "image", retryable: false, title: "This pipeline's stack carries a Docker image asset, which a runner cannot deploy." },
|
|
856
|
+
/** Past RUNNER_DEPLOY_DEADLINE_MINUTES, or CodeBuild's own timeout. */
|
|
857
|
+
DEPLOY_TIMED_OUT: { class: "timeout", retryable: true, title: "The deploy did not finish in time." },
|
|
858
|
+
/** A person cancelled it. */
|
|
859
|
+
DEPLOY_CANCELLED: { class: "cancelled", retryable: true, title: "The deploy was cancelled." },
|
|
860
|
+
/** Anything else inside the job. */
|
|
861
|
+
DEPLOY_JOB_ERROR: { class: "unknown", retryable: true, title: "The deploy job failed." }
|
|
862
|
+
};
|
|
863
|
+
var RUNNER_DEPLOY_ERROR_CODES = Object.keys(RUNNER_DEPLOY_ERRORS);
|
|
864
|
+
var DEPLOY_RESULT_OK = "OK";
|
|
865
|
+
var DEPLOY_JOB_RESULT_CODES = [DEPLOY_RESULT_OK, ...RUNNER_DEPLOY_ERROR_CODES];
|
|
866
|
+
var DEPLOY_BUILD_QUEUED_TIMEOUT_MINUTES = 30;
|
|
867
|
+
var DEPLOY_GRANT_PROVISIONING_MARGIN_MS = 15 * 6e4;
|
|
868
|
+
function deployGrantTtlMs(queuedTimeoutMinutes = DEPLOY_BUILD_QUEUED_TIMEOUT_MINUTES) {
|
|
869
|
+
return Math.max(RUN_REQUEST_TTL_MS, queuedTimeoutMinutes * 6e4 + DEPLOY_GRANT_PROVISIONING_MARGIN_MS);
|
|
870
|
+
}
|
|
871
|
+
var DEPLOY_GRANT_TTL_MS = deployGrantTtlMs();
|
|
872
|
+
var DEPLOY_BUILD_TIMEOUT_MINUTES = {
|
|
873
|
+
default: 60,
|
|
874
|
+
min: 10,
|
|
875
|
+
max: Number(RUNNER_TUNABLE_DEFAULTS.RUNNER_DEPLOY_DEADLINE_MINUTES)
|
|
876
|
+
};
|
|
877
|
+
var DEPLOY_JOB_ENV = {
|
|
878
|
+
requestId: "PB_REQUEST_ID",
|
|
879
|
+
pipelineId: "PB_PIPELINE_ID",
|
|
880
|
+
region: "PB_TARGET_REGION",
|
|
881
|
+
pipelineName: "PB_PIPELINE_NAME",
|
|
882
|
+
stackName: "PB_STACK_NAME",
|
|
883
|
+
grantCiphertext: "PB_DEPLOY_GRANT_CIPHERTEXT",
|
|
884
|
+
toolchainRelease: "PB_TOOLCHAIN_RELEASE",
|
|
885
|
+
protocol: "PB_DEPLOY_PROTOCOL",
|
|
886
|
+
mode: "PB_JOB_MODE",
|
|
887
|
+
result: "PB_DEPLOY_RESULT",
|
|
888
|
+
stage: "PB_DEPLOY_STAGE"
|
|
889
|
+
};
|
|
890
|
+
var DEPLOY_JOB_EXPORTED_VARIABLES = [DEPLOY_JOB_ENV.result, DEPLOY_JOB_ENV.stage];
|
|
891
|
+
var DEPLOY_JOB_OVERRIDE_ENV = [
|
|
892
|
+
DEPLOY_JOB_ENV.requestId,
|
|
893
|
+
DEPLOY_JOB_ENV.pipelineId,
|
|
894
|
+
DEPLOY_JOB_ENV.region,
|
|
895
|
+
DEPLOY_JOB_ENV.pipelineName,
|
|
896
|
+
DEPLOY_JOB_ENV.stackName,
|
|
897
|
+
DEPLOY_JOB_ENV.grantCiphertext,
|
|
898
|
+
DEPLOY_JOB_ENV.toolchainRelease,
|
|
899
|
+
DEPLOY_JOB_ENV.protocol,
|
|
900
|
+
DEPLOY_JOB_ENV.mode
|
|
901
|
+
];
|
|
902
|
+
|
|
903
|
+
// ../api-core/lib/types/pipeline-source.js
|
|
904
|
+
var GITHUB_OWNER_PATTERN = /^[A-Za-z0-9](?:[A-Za-z0-9]|-(?=[A-Za-z0-9])){0,38}$/;
|
|
905
|
+
function githubOwnerProblem(owner) {
|
|
906
|
+
return GITHUB_OWNER_PATTERN.test(owner) ? null : "A GitHub owner is 1-39 letters, digits or single hyphens, not starting or ending with a hyphen.";
|
|
907
|
+
}
|
|
908
|
+
var DEFAULT_SECRETS_PATH_PREFIX = "pipeline-builder";
|
|
909
|
+
function githubTokenSecretName(orgId, owner, prefix = DEFAULT_SECRETS_PATH_PREFIX) {
|
|
910
|
+
const base = `${prefix}/${orgId}/github-token`;
|
|
911
|
+
if (owner === void 0)
|
|
912
|
+
return base;
|
|
913
|
+
const problem = githubOwnerProblem(owner);
|
|
914
|
+
if (problem)
|
|
915
|
+
throw new Error(`Invalid GitHub owner "${owner}": ${problem}`);
|
|
916
|
+
return `${base}/${owner.toLowerCase()}`;
|
|
917
|
+
}
|
|
918
|
+
function githubTokenStoreCommand(owner, region = "<region>") {
|
|
919
|
+
return `pipeline-manager infra store-github-token --region ${region}${owner ? ` --owner ${owner.toLowerCase()}` : ""}`;
|
|
920
|
+
}
|
|
921
|
+
var GITHUB_TOKEN_STORE_COMMAND = githubTokenStoreCommand();
|
|
922
|
+
|
|
923
|
+
// ../pipeline-events/src/scm.ts
|
|
924
|
+
var commitResultCache = new BoundedMap(CACHE_MAX_ENTRIES);
|
|
925
|
+
var lastShaByPipeline = new BoundedMap(CACHE_MAX_ENTRIES);
|
|
926
|
+
var NO_RECORDED_DEPLOY_MAX = 1e3;
|
|
927
|
+
var noRecordedDeploy = new BoundedMap(NO_RECORDED_DEPLOY_MAX);
|
|
928
|
+
var commitMetaCache = new BoundedMap(CACHE_MAX_ENTRIES);
|
|
929
|
+
var scmCooldownUntil = 0;
|
|
930
|
+
var SCM_COOLDOWN_MS = 2 * 60 * 1e3;
|
|
931
|
+
var MAX_COMMIT_WALK = 50;
|
|
932
|
+
var githubTokenByOrg = new BoundedMap(CACHE_MAX_ENTRIES);
|
|
933
|
+
var githubTokenMissUntil = new BoundedMap(CACHE_MAX_ENTRIES);
|
|
934
|
+
var GITHUB_TOKEN_MISS_TTL_MS = 6e4;
|
|
935
|
+
function githubTokenSecretNames(orgId, owner) {
|
|
936
|
+
const name = loadEventsConfig().platformSecretName;
|
|
937
|
+
if (!name || !name.endsWith("/platform")) return [];
|
|
938
|
+
const base = name.slice(0, -"/platform".length);
|
|
939
|
+
const slash = base.lastIndexOf("/");
|
|
940
|
+
if (slash <= 0) return [];
|
|
941
|
+
const prefix = base.slice(0, slash);
|
|
942
|
+
const org = orgId ?? base.slice(slash + 1);
|
|
943
|
+
const orgDefault = githubTokenSecretName(org, void 0, prefix);
|
|
944
|
+
return owner && !githubOwnerProblem(owner) ? [githubTokenSecretName(org, owner, prefix), orgDefault] : [orgDefault];
|
|
945
|
+
}
|
|
946
|
+
async function readTokenSecret(secretName, orgId) {
|
|
947
|
+
try {
|
|
948
|
+
const client2 = new SecretsManagerClient2({});
|
|
949
|
+
const res = await client2.send(new GetSecretValueCommand2({ SecretId: secretName }));
|
|
950
|
+
return res.SecretString && res.SecretString.length > 0 ? res.SecretString.trim() || null : null;
|
|
951
|
+
} catch (err) {
|
|
952
|
+
const error = err?.name;
|
|
953
|
+
if (error !== "ResourceNotFoundException") log.warn("github-token secret could not be read", { orgId, secretName, error });
|
|
954
|
+
return null;
|
|
955
|
+
}
|
|
956
|
+
}
|
|
957
|
+
async function getGitHubToken(orgId, owner) {
|
|
958
|
+
const ownerKey = owner?.toLowerCase();
|
|
959
|
+
const key = `${orgId ?? ""}|${ownerKey ?? ""}`;
|
|
960
|
+
const cached = githubTokenByOrg.get(key);
|
|
961
|
+
if (cached !== void 0) return cached;
|
|
962
|
+
const missUntil = githubTokenMissUntil.get(key);
|
|
963
|
+
if (missUntil !== void 0 && Date.now() < missUntil) return null;
|
|
964
|
+
const names = githubTokenSecretNames(orgId, ownerKey);
|
|
965
|
+
if (names.length === 0) return null;
|
|
966
|
+
let token = null;
|
|
967
|
+
for (const secretName of names) {
|
|
968
|
+
token = await readTokenSecret(secretName, orgId);
|
|
969
|
+
if (token) break;
|
|
970
|
+
}
|
|
971
|
+
if (token) {
|
|
972
|
+
githubTokenByOrg.set(key, token);
|
|
973
|
+
githubTokenMissUntil.delete(key);
|
|
974
|
+
} else {
|
|
975
|
+
log.warn("No github-token secret (owner or org default) \u2014 GitHub commit resolution will be unauthenticated", { orgId, secretNames: names });
|
|
976
|
+
githubTokenMissUntil.set(key, Date.now() + GITHUB_TOKEN_MISS_TTL_MS);
|
|
977
|
+
}
|
|
978
|
+
return token;
|
|
979
|
+
}
|
|
980
|
+
function toIso(value) {
|
|
981
|
+
if (typeof value !== "string" || value.length === 0) return void 0;
|
|
982
|
+
const epoch = /^(\d{9,})\b/.exec(value.trim());
|
|
983
|
+
if (epoch) {
|
|
984
|
+
const d2 = new Date(Number(epoch[1]) * 1e3);
|
|
985
|
+
return Number.isNaN(d2.getTime()) ? void 0 : d2.toISOString();
|
|
986
|
+
}
|
|
987
|
+
const d = new Date(value);
|
|
988
|
+
return Number.isNaN(d.getTime()) ? void 0 : d.toISOString();
|
|
989
|
+
}
|
|
990
|
+
function classifySource(url) {
|
|
991
|
+
if (!url) return { provider: "unknown" };
|
|
992
|
+
try {
|
|
993
|
+
const u = new URL(url);
|
|
994
|
+
const host = u.hostname.toLowerCase();
|
|
995
|
+
if (host === "github.com" || host.endsWith(".github.com")) {
|
|
996
|
+
const parts = u.pathname.split("/").filter(Boolean);
|
|
997
|
+
if (parts.length >= 2) return { provider: "github", owner: parts[0], repo: parts[1].replace(/\.git$/, "") };
|
|
998
|
+
}
|
|
999
|
+
if (host === "bitbucket.org") {
|
|
1000
|
+
const parts = u.pathname.split("/").filter(Boolean);
|
|
1001
|
+
if (parts.length >= 2) return { provider: "bitbucket", owner: parts[0], repo: parts[1].replace(/\.git$/, "") };
|
|
1002
|
+
}
|
|
1003
|
+
if (u.pathname.toLowerCase().includes("codecommit") || u.hash.toLowerCase().includes("codecommit") || u.pathname.includes("/repositories/")) {
|
|
1004
|
+
const m = /repositor(?:y|ies)\/([^/#?]+)/.exec(u.pathname + u.hash);
|
|
1005
|
+
if (m) return { provider: "codecommit", repositoryName: decodeURIComponent(m[1]) };
|
|
1006
|
+
}
|
|
1007
|
+
} catch {
|
|
1008
|
+
}
|
|
1009
|
+
return { provider: "unknown" };
|
|
1010
|
+
}
|
|
1011
|
+
var codecommitClientsByRegion;
|
|
1012
|
+
var codecommitMod;
|
|
1013
|
+
async function codeCommitClient(region) {
|
|
1014
|
+
if (!codecommitMod) codecommitMod = await loadSdk("@aws-sdk/client-codecommit");
|
|
1015
|
+
if (!codecommitClientsByRegion) codecommitClientsByRegion = /* @__PURE__ */ new Map();
|
|
1016
|
+
let client2 = codecommitClientsByRegion.get(region);
|
|
1017
|
+
if (!client2) {
|
|
1018
|
+
client2 = new codecommitMod.CodeCommitClient({ region });
|
|
1019
|
+
codecommitClientsByRegion.set(region, client2);
|
|
1020
|
+
}
|
|
1021
|
+
return client2;
|
|
1022
|
+
}
|
|
1023
|
+
async function codeCommitMeta(region, repositoryName, commitId) {
|
|
1024
|
+
const cached = commitMetaCache.get(commitId);
|
|
1025
|
+
if (cached) return cached;
|
|
1026
|
+
if (!codecommitMod) codecommitMod = await loadSdk("@aws-sdk/client-codecommit");
|
|
1027
|
+
const client2 = await codeCommitClient(region);
|
|
1028
|
+
const out = await client2.send(new codecommitMod.GetCommitCommand({ repositoryName, commitId }));
|
|
1029
|
+
const commit = out.commit;
|
|
1030
|
+
const meta = { date: toIso(commit?.committer?.date ?? commit?.author?.date), parents: commit?.parents };
|
|
1031
|
+
commitMetaCache.set(commitId, meta);
|
|
1032
|
+
return meta;
|
|
1033
|
+
}
|
|
1034
|
+
async function resolveCodeCommit(region, repositoryName, sha, sinceSha) {
|
|
1035
|
+
let cur = sha;
|
|
1036
|
+
let count = 0;
|
|
1037
|
+
let oldest;
|
|
1038
|
+
let truncated = false;
|
|
1039
|
+
for (let i = 0; ; i++) {
|
|
1040
|
+
if (!cur) break;
|
|
1041
|
+
if (sinceSha && cur === sinceSha) break;
|
|
1042
|
+
if (i >= MAX_COMMIT_WALK) {
|
|
1043
|
+
truncated = true;
|
|
1044
|
+
break;
|
|
1045
|
+
}
|
|
1046
|
+
const meta = await codeCommitMeta(region, repositoryName, cur);
|
|
1047
|
+
if (!meta?.date) break;
|
|
1048
|
+
count++;
|
|
1049
|
+
oldest = meta.date;
|
|
1050
|
+
if (!sinceSha) break;
|
|
1051
|
+
cur = meta.parents?.[0];
|
|
1052
|
+
}
|
|
1053
|
+
if (truncated) return {};
|
|
1054
|
+
return oldest ? { commitTimestamp: oldest, commitCount: count } : {};
|
|
1055
|
+
}
|
|
1056
|
+
async function resolveGitHub(owner, repo, sha, sinceSha, orgId) {
|
|
1057
|
+
const token = await getGitHubToken(orgId, owner);
|
|
1058
|
+
const headers = {
|
|
1059
|
+
"Accept": "application/vnd.github+json",
|
|
1060
|
+
"User-Agent": "pipeline-builder-forwarder",
|
|
1061
|
+
"X-GitHub-Api-Version": "2022-11-28"
|
|
1062
|
+
};
|
|
1063
|
+
if (token) headers.Authorization = `Bearer ${token}`;
|
|
1064
|
+
const rateLimited = (r) => r.status === 403 || r.status === 429;
|
|
1065
|
+
const base = `https://api.github.com/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}`;
|
|
1066
|
+
if (sinceSha) {
|
|
1067
|
+
const r = await fetchWithTimeout(`${base}/compare/${encodeURIComponent(sinceSha)}...${encodeURIComponent(sha)}`, { headers }, loadEventsConfig().scmFetchTimeoutMs);
|
|
1068
|
+
if (rateLimited(r)) {
|
|
1069
|
+
scmCooldownUntil = Date.now() + SCM_COOLDOWN_MS;
|
|
1070
|
+
return {};
|
|
1071
|
+
}
|
|
1072
|
+
if (r.ok) {
|
|
1073
|
+
const j = await r.json();
|
|
1074
|
+
const commits = Array.isArray(j.commits) ? j.commits : [];
|
|
1075
|
+
if (typeof j.total_commits === "number" && j.total_commits > commits.length) return {};
|
|
1076
|
+
if (commits.length > 0) {
|
|
1077
|
+
const oldest = toIso(commits[0]?.commit?.committer?.date ?? commits[0]?.commit?.author?.date);
|
|
1078
|
+
if (oldest) return { commitTimestamp: oldest, commitCount: commits.length };
|
|
1079
|
+
}
|
|
1080
|
+
}
|
|
1081
|
+
}
|
|
1082
|
+
const r2 = await fetchWithTimeout(`${base}/commits/${encodeURIComponent(sha)}`, { headers }, loadEventsConfig().scmFetchTimeoutMs);
|
|
1083
|
+
if (rateLimited(r2)) {
|
|
1084
|
+
scmCooldownUntil = Date.now() + SCM_COOLDOWN_MS;
|
|
1085
|
+
return {};
|
|
1086
|
+
}
|
|
1087
|
+
if (r2.ok) {
|
|
1088
|
+
const j = await r2.json();
|
|
1089
|
+
const d = toIso(j.commit?.committer?.date ?? j.commit?.author?.date);
|
|
1090
|
+
if (d) return { commitTimestamp: d, commitCount: 1 };
|
|
1091
|
+
}
|
|
1092
|
+
return {};
|
|
1093
|
+
}
|
|
1094
|
+
async function resolveBitbucket(owner, repo, sha) {
|
|
1095
|
+
const r = await fetchWithTimeout(`https://api.bitbucket.org/2.0/repositories/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/commit/${encodeURIComponent(sha)}`, {
|
|
1096
|
+
headers: { "User-Agent": "pipeline-builder-forwarder", "Accept": "application/json" }
|
|
1097
|
+
}, loadEventsConfig().scmFetchTimeoutMs);
|
|
1098
|
+
if (r.status === 429) {
|
|
1099
|
+
scmCooldownUntil = Date.now() + SCM_COOLDOWN_MS;
|
|
1100
|
+
return {};
|
|
1101
|
+
}
|
|
1102
|
+
if (r.ok) {
|
|
1103
|
+
const j = await r.json();
|
|
1104
|
+
const d = toIso(j.date);
|
|
1105
|
+
if (d) return { commitTimestamp: d, commitCount: 1 };
|
|
1106
|
+
}
|
|
1107
|
+
return {};
|
|
1108
|
+
}
|
|
1109
|
+
async function resolveCommitInfo(pipelineId, orgId, region, src, opts = {}) {
|
|
1110
|
+
if (src.provider === "unknown") return {};
|
|
1111
|
+
const rkey = `${pipelineId}|${src.sha}`;
|
|
1112
|
+
const cached = commitResultCache.get(rkey);
|
|
1113
|
+
if (cached) {
|
|
1114
|
+
if (opts.successfulDeploy) markDeployed(pipelineId, src.sha);
|
|
1115
|
+
return cached;
|
|
1116
|
+
}
|
|
1117
|
+
const prev = lastShaByPipeline.get(pipelineId) ?? await fetchLastDeployedSha(pipelineId);
|
|
1118
|
+
const sinceSha = prev && prev !== src.sha ? prev : void 0;
|
|
1119
|
+
let info = {};
|
|
1120
|
+
try {
|
|
1121
|
+
if (src.provider === "codecommit" && src.repositoryName) {
|
|
1122
|
+
info = await resolveCodeCommit(region, src.repositoryName, src.sha, sinceSha);
|
|
1123
|
+
} else if (src.provider === "github" && src.owner && src.repo) {
|
|
1124
|
+
if (Date.now() >= scmCooldownUntil) info = await resolveGitHub(src.owner, src.repo, src.sha, sinceSha, orgId);
|
|
1125
|
+
} else if (src.provider === "bitbucket" && src.owner && src.repo) {
|
|
1126
|
+
if (Date.now() >= scmCooldownUntil) info = await resolveBitbucket(src.owner, src.repo, src.sha);
|
|
1127
|
+
}
|
|
1128
|
+
} catch (err) {
|
|
1129
|
+
log.warn("Commit resolution failed (omitting commitTimestamp/commitCount)", { provider: src.provider, error: err?.name ?? String(err) });
|
|
1130
|
+
info = {};
|
|
1131
|
+
}
|
|
1132
|
+
if (info.commitTimestamp) commitResultCache.set(rkey, info);
|
|
1133
|
+
if (opts.successfulDeploy) markDeployed(pipelineId, src.sha);
|
|
1134
|
+
return info;
|
|
1135
|
+
}
|
|
1136
|
+
function markDeployed(pipelineId, sha) {
|
|
1137
|
+
lastShaByPipeline.set(pipelineId, sha);
|
|
1138
|
+
noRecordedDeploy.delete(pipelineId);
|
|
1139
|
+
}
|
|
1140
|
+
async function fetchLastDeployedSha(pipelineId) {
|
|
1141
|
+
const baseUrl2 = loadEventsConfig().platformBaseUrl;
|
|
1142
|
+
if (!baseUrl2 || noRecordedDeploy.has(pipelineId)) return void 0;
|
|
1143
|
+
try {
|
|
1144
|
+
const res = await fetchWithTimeout(
|
|
1145
|
+
`${baseUrl2}/api/reports/events/last-deploy-commit?pipelineId=${encodeURIComponent(pipelineId)}`,
|
|
1146
|
+
{ headers: { Authorization: `Bearer ${await getAuthToken()}`, Accept: "application/json" } }
|
|
1147
|
+
);
|
|
1148
|
+
if (!res.ok) {
|
|
1149
|
+
log.warn("Last-deploy-commit lookup failed; resolving a single commit", { status: res.status });
|
|
1150
|
+
return void 0;
|
|
1151
|
+
}
|
|
1152
|
+
const body = await res.json();
|
|
1153
|
+
const sha = body.data?.commitSha ?? void 0;
|
|
1154
|
+
if (!sha) {
|
|
1155
|
+
noRecordedDeploy.set(pipelineId, true);
|
|
1156
|
+
return void 0;
|
|
1157
|
+
}
|
|
1158
|
+
lastShaByPipeline.set(pipelineId, sha);
|
|
1159
|
+
return sha;
|
|
1160
|
+
} catch (err) {
|
|
1161
|
+
log.warn("Last-deploy-commit lookup errored; resolving a single commit", {
|
|
1162
|
+
error: err?.name ?? String(err)
|
|
1163
|
+
});
|
|
1164
|
+
return void 0;
|
|
1165
|
+
}
|
|
1166
|
+
}
|
|
1167
|
+
function _resetScmForTests() {
|
|
1168
|
+
commitResultCache.clear();
|
|
1169
|
+
lastShaByPipeline.clear();
|
|
1170
|
+
noRecordedDeploy.clear();
|
|
1171
|
+
commitMetaCache.clear();
|
|
1172
|
+
scmCooldownUntil = 0;
|
|
1173
|
+
githubTokenByOrg.clear();
|
|
1174
|
+
githubTokenMissUntil.clear();
|
|
1175
|
+
}
|
|
1176
|
+
|
|
1177
|
+
// ../pipeline-events/src/tags.ts
|
|
1178
|
+
var codepipelineMod;
|
|
1179
|
+
async function loadCodePipeline() {
|
|
1180
|
+
if (!codepipelineMod) codepipelineMod = await import("@aws-sdk/client-codepipeline");
|
|
1181
|
+
return codepipelineMod;
|
|
1182
|
+
}
|
|
1183
|
+
var PIPELINE_ID_TAG = "pb.pipeline-id";
|
|
1184
|
+
var DEPLOYS_TAG = "pb.deploys";
|
|
1185
|
+
var ORG_ID_TAG = "OrgId";
|
|
1186
|
+
var clientsByRegion = /* @__PURE__ */ new Map();
|
|
1187
|
+
var resolvedByArn = new BoundedMap(CACHE_MAX_ENTRIES);
|
|
1188
|
+
var MAX_ATTR = 255;
|
|
1189
|
+
function parseDeploys(value) {
|
|
1190
|
+
const map = /* @__PURE__ */ new Map();
|
|
1191
|
+
if (!value) return map;
|
|
1192
|
+
for (const pair of value.split("+")) {
|
|
1193
|
+
const idx = pair.indexOf(":");
|
|
1194
|
+
if (idx <= 0) continue;
|
|
1195
|
+
const stage = pair.slice(0, idx).trim();
|
|
1196
|
+
const env = pair.slice(idx + 1).trim();
|
|
1197
|
+
if (stage && env) map.set(stage, env.slice(0, MAX_ATTR));
|
|
1198
|
+
}
|
|
1199
|
+
return map;
|
|
1200
|
+
}
|
|
1201
|
+
async function pipelineClient(region) {
|
|
1202
|
+
let client2 = clientsByRegion.get(region);
|
|
1203
|
+
if (!client2) {
|
|
1204
|
+
const { CodePipelineClient } = await loadCodePipeline();
|
|
1205
|
+
client2 = new CodePipelineClient({ region });
|
|
1206
|
+
clientsByRegion.set(region, client2);
|
|
1207
|
+
}
|
|
1208
|
+
return client2;
|
|
1209
|
+
}
|
|
1210
|
+
async function resolvePipeline(arn, region) {
|
|
1211
|
+
const cached = resolvedByArn.get(arn);
|
|
1212
|
+
const { tagCacheTtlMs, tagMissCacheTtlMs } = loadEventsConfig();
|
|
1213
|
+
if (cached && Date.now() - cached.ts < (cached.pipelineId !== null ? tagCacheTtlMs : tagMissCacheTtlMs)) {
|
|
1214
|
+
return { pipelineId: cached.pipelineId, orgId: cached.orgId, deploys: cached.deploys };
|
|
1215
|
+
}
|
|
1216
|
+
try {
|
|
1217
|
+
const client2 = await pipelineClient(region);
|
|
1218
|
+
const { ListTagsForResourceCommand } = await loadCodePipeline();
|
|
1219
|
+
const out = await client2.send(new ListTagsForResourceCommand({ resourceArn: arn }));
|
|
1220
|
+
const pipelineId = out.tags?.find((t) => t.key === PIPELINE_ID_TAG)?.value ?? null;
|
|
1221
|
+
const orgId = out.tags?.find((t) => t.key === ORG_ID_TAG)?.value ?? null;
|
|
1222
|
+
const deploys = parseDeploys(out.tags?.find((t) => t.key === DEPLOYS_TAG)?.value);
|
|
1223
|
+
if (!pipelineId) log.warn("Pipeline missing pb.pipeline-id tag \u2014 skipping (register it?)", { pipeline: arnRef(arn) });
|
|
1224
|
+
resolvedByArn.set(arn, { pipelineId, orgId, deploys, ts: Date.now() });
|
|
1225
|
+
return { pipelineId, orgId, deploys };
|
|
1226
|
+
} catch (err) {
|
|
1227
|
+
const name = err?.name;
|
|
1228
|
+
if (name === "AccessDeniedException") {
|
|
1229
|
+
log.error("AccessDenied calling codepipeline:ListTagsForResource \u2014 grant it to the Lambda role", { pipeline: arnRef(arn), error: name });
|
|
1230
|
+
throw err;
|
|
1231
|
+
}
|
|
1232
|
+
if (!isDefinitiveTagAnswer(err)) {
|
|
1233
|
+
log.error("Error resolving pb.pipeline-id tag \u2014 will retry the record", { pipeline: arnRef(arn), error: name ?? String(err) });
|
|
1234
|
+
throw err;
|
|
1235
|
+
}
|
|
1236
|
+
log.error("Failed to resolve pb.pipeline-id tag", { pipeline: arnRef(arn), error: name ?? String(err) });
|
|
1237
|
+
return { pipelineId: null, orgId: null, deploys: /* @__PURE__ */ new Map() };
|
|
1238
|
+
}
|
|
1239
|
+
}
|
|
1240
|
+
var DEFINITIVE_TAG_ERRORS = /* @__PURE__ */ new Set(["ResourceNotFoundException", "InvalidArnException", "ValidationException"]);
|
|
1241
|
+
function isDefinitiveTagAnswer(err) {
|
|
1242
|
+
const e = err;
|
|
1243
|
+
return e?.$retryable == null && typeof e?.name === "string" && DEFINITIVE_TAG_ERRORS.has(e.name);
|
|
1244
|
+
}
|
|
1245
|
+
function _resetTagsForTests() {
|
|
1246
|
+
resolvedByArn.clear();
|
|
1247
|
+
}
|
|
1248
|
+
|
|
1249
|
+
// ../pipeline-events/src/parse.ts
|
|
1250
|
+
var MAX_SOURCE_ID = 128;
|
|
1251
|
+
function sourceId(v) {
|
|
1252
|
+
return typeof v === "string" && v.length > 0 ? v.slice(0, MAX_SOURCE_ID) : void 0;
|
|
1253
|
+
}
|
|
1254
|
+
var MAX_ERROR_MESSAGE = 4e3;
|
|
1255
|
+
var MAX_DETAIL_BYTES = 7500;
|
|
1256
|
+
var DEPLOY_SUCCEEDED_STATES = /* @__PURE__ */ new Set(["SUCCEEDED", "SUCCESS"]);
|
|
1257
|
+
var TERMINAL_STATES = /* @__PURE__ */ new Set(["SUCCEEDED", "FAILED", "CANCELED", "STOPPED", "SUPERSEDED", "ABANDONED"]);
|
|
1258
|
+
function firstAttr(...vals) {
|
|
1259
|
+
for (const v of vals) {
|
|
1260
|
+
if (typeof v === "string" && v.length > 0) return v.slice(0, MAX_ATTR);
|
|
1261
|
+
}
|
|
1262
|
+
return void 0;
|
|
1263
|
+
}
|
|
1264
|
+
function extractCommit(detail) {
|
|
1265
|
+
const revs = detail["source-revisions"] ?? detail.sourceRevisions;
|
|
1266
|
+
const firstRev = Array.isArray(revs) ? revs[0] : void 0;
|
|
1267
|
+
const execResult = detail["execution-result"];
|
|
1268
|
+
const commitSha = firstAttr(
|
|
1269
|
+
detail.commitId,
|
|
1270
|
+
detail.revisionId,
|
|
1271
|
+
firstRev?.revisionId,
|
|
1272
|
+
execResult?.revisionId
|
|
1273
|
+
);
|
|
1274
|
+
const commitRef = firstAttr(
|
|
1275
|
+
detail.commitRef,
|
|
1276
|
+
detail.branch,
|
|
1277
|
+
detail.sourceBranch,
|
|
1278
|
+
firstRev?.branchName,
|
|
1279
|
+
firstRev?.branch
|
|
1280
|
+
);
|
|
1281
|
+
const revisionUrl = typeof firstRev?.revisionUrl === "string" ? firstRev.revisionUrl : void 0;
|
|
1282
|
+
return { ...commitSha && { commitSha }, ...commitRef && { commitRef }, ...revisionUrl && { revisionUrl } };
|
|
1283
|
+
}
|
|
1284
|
+
function classifyEvent(detailType) {
|
|
1285
|
+
if (detailType.includes("Pipeline Execution")) return { eventType: "PIPELINE", eventSource: "codepipeline" };
|
|
1286
|
+
if (detailType.includes("Stage Execution")) return { eventType: "STAGE", eventSource: "codepipeline" };
|
|
1287
|
+
if (detailType.includes("Action Execution")) return { eventType: "ACTION", eventSource: "codepipeline" };
|
|
1288
|
+
if (detailType.includes("Build State")) return { eventType: "BUILD", eventSource: "codebuild" };
|
|
1289
|
+
return { eventType: "PIPELINE", eventSource: "codepipeline" };
|
|
1290
|
+
}
|
|
1291
|
+
async function parseRecord(record) {
|
|
1292
|
+
let event;
|
|
1293
|
+
let parsed;
|
|
1294
|
+
try {
|
|
1295
|
+
parsed = JSON.parse(record.body);
|
|
1296
|
+
} catch (err) {
|
|
1297
|
+
log.warn("Skipping SQS record with unparseable body", { messageId: record.messageId, error: String(err) });
|
|
1298
|
+
return null;
|
|
1299
|
+
}
|
|
1300
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed) || typeof parsed["detail-type"] !== "string") {
|
|
1301
|
+
log.warn("Skipping SQS record that is not an EventBridge event (no string detail-type)", { messageId: record.messageId });
|
|
1302
|
+
return null;
|
|
1303
|
+
}
|
|
1304
|
+
event = parsed;
|
|
1305
|
+
const rawDetail = parsed.detail;
|
|
1306
|
+
if (rawDetail !== void 0 && (rawDetail === null || typeof rawDetail !== "object" || Array.isArray(rawDetail))) {
|
|
1307
|
+
log.warn("Skipping SQS record whose event detail is not an object", { messageId: record.messageId });
|
|
1308
|
+
return null;
|
|
1309
|
+
}
|
|
1310
|
+
const { eventType, eventSource } = classifyEvent(event["detail-type"]);
|
|
1311
|
+
const detail = { ...event.detail };
|
|
1312
|
+
delete detail.account;
|
|
1313
|
+
if (eventSource !== "codepipeline") {
|
|
1314
|
+
log.warn("Skipping non-CodePipeline event (no pipeline tag to resolve)", { detailType: event["detail-type"] });
|
|
1315
|
+
return null;
|
|
1316
|
+
}
|
|
1317
|
+
const pipelineName = detail.pipeline;
|
|
1318
|
+
if (!pipelineName) {
|
|
1319
|
+
log.warn("CodePipeline event missing pipeline name \u2014 skipping");
|
|
1320
|
+
return null;
|
|
1321
|
+
}
|
|
1322
|
+
const arn = `arn:${partitionForRegion(event.region)}:codepipeline:${event.region}:${event.account}:${pipelineName}`;
|
|
1323
|
+
const { pipelineId, orgId, deploys } = await resolvePipeline(arn, event.region);
|
|
1324
|
+
if (!pipelineId) return null;
|
|
1325
|
+
const declaredStart = detail["start-time"];
|
|
1326
|
+
const state = detail.state;
|
|
1327
|
+
const startedAt = state === "RESUMED" ? event.time : declaredStart || event.time;
|
|
1328
|
+
let durationMs;
|
|
1329
|
+
let completedAt;
|
|
1330
|
+
if (TERMINAL_STATES.has(state)) {
|
|
1331
|
+
completedAt = event.time;
|
|
1332
|
+
if (declaredStart) {
|
|
1333
|
+
const ms = new Date(completedAt).getTime() - new Date(declaredStart).getTime();
|
|
1334
|
+
if (Number.isFinite(ms) && ms >= 0) durationMs = ms;
|
|
1335
|
+
}
|
|
1336
|
+
}
|
|
1337
|
+
const result = detail["execution-result"];
|
|
1338
|
+
const summary = result?.["external-execution-summary"];
|
|
1339
|
+
let errorMessage = typeof summary === "string" && summary.length > 0 ? summary.slice(0, MAX_ERROR_MESSAGE) : void 0;
|
|
1340
|
+
let computeType;
|
|
1341
|
+
let buildPhases;
|
|
1342
|
+
if (eventType === "ACTION" && TERMINAL_STATES.has(state)) {
|
|
1343
|
+
const cbId = codeBuildIdOf(detail);
|
|
1344
|
+
const facts = cbId ? await readBuildCompute(event.region, cbId) : null;
|
|
1345
|
+
computeType = facts?.computeType ?? void 0;
|
|
1346
|
+
buildPhases = facts?.phases ?? void 0;
|
|
1347
|
+
}
|
|
1348
|
+
if (eventType === "ACTION" && state === "FAILED") {
|
|
1349
|
+
const buildId = codeBuildIdOf(detail);
|
|
1350
|
+
const failure = buildId ? await readSynthFailure(event.region, buildId) : null;
|
|
1351
|
+
if (failure) {
|
|
1352
|
+
detail.pbFailure = failure;
|
|
1353
|
+
if (JSON.stringify(detail).length >= MAX_DETAIL_BYTES) {
|
|
1354
|
+
detail.pbFailure = { ...failure, plugins: failure.plugins.map(({ plugin, code }) => ({ plugin, code })) };
|
|
1355
|
+
}
|
|
1356
|
+
errorMessage = `${failure.code}: ${failure.message}`.slice(0, MAX_ERROR_MESSAGE);
|
|
1357
|
+
}
|
|
1358
|
+
}
|
|
1359
|
+
const sourceEventId = sourceId(event.id);
|
|
1360
|
+
const sourceMessageId = sourceId(record.messageId);
|
|
1361
|
+
const { commitSha, commitRef, revisionUrl } = extractCommit(detail);
|
|
1362
|
+
const executionId = detail["execution-id"];
|
|
1363
|
+
const stageName = detail.stage;
|
|
1364
|
+
const actionName = detail.action;
|
|
1365
|
+
const environment = stageName ? deploys.get(stageName) : void 0;
|
|
1366
|
+
let commitTimestamp;
|
|
1367
|
+
let commitCount;
|
|
1368
|
+
if (commitSha && loadEventsConfig().doraEnabled) {
|
|
1369
|
+
const src = classifySource(revisionUrl);
|
|
1370
|
+
const successfulDeploy = eventType === "STAGE" && !!environment && DEPLOY_SUCCEEDED_STATES.has(state);
|
|
1371
|
+
const info = await resolveCommitInfo(pipelineId, orgId, event.region, { sha: commitSha, ...src }, { successfulDeploy });
|
|
1372
|
+
commitTimestamp = info.commitTimestamp;
|
|
1373
|
+
commitCount = info.commitCount;
|
|
1374
|
+
}
|
|
1375
|
+
return {
|
|
1376
|
+
orgId,
|
|
1377
|
+
pipelineId,
|
|
1378
|
+
...event.region && { region: event.region },
|
|
1379
|
+
pipelineName,
|
|
1380
|
+
eventSource,
|
|
1381
|
+
eventType,
|
|
1382
|
+
status: state,
|
|
1383
|
+
executionId,
|
|
1384
|
+
stageName,
|
|
1385
|
+
actionName,
|
|
1386
|
+
errorMessage,
|
|
1387
|
+
startedAt,
|
|
1388
|
+
completedAt,
|
|
1389
|
+
durationMs,
|
|
1390
|
+
...commitSha && { commitSha },
|
|
1391
|
+
...commitRef && { commitRef },
|
|
1392
|
+
...commitTimestamp && { commitTimestamp },
|
|
1393
|
+
...commitCount && { commitCount },
|
|
1394
|
+
...environment && { environment },
|
|
1395
|
+
...computeType && { computeType },
|
|
1396
|
+
...buildPhases && { buildPhases },
|
|
1397
|
+
...sourceEventId && { sourceEventId },
|
|
1398
|
+
...sourceMessageId && { sourceMessageId },
|
|
1399
|
+
detail
|
|
1400
|
+
};
|
|
1401
|
+
}
|
|
1402
|
+
|
|
1403
|
+
// ../pipeline-events/src/index.ts
|
|
1404
|
+
var handler = async (event, context) => {
|
|
1405
|
+
const baseUrl2 = loadEventsConfig().platformBaseUrl;
|
|
1406
|
+
if (!baseUrl2) throw new Error("PLATFORM_BASE_URL environment variable is required");
|
|
1407
|
+
const requestId = context?.awsRequestId || randomUUID();
|
|
1408
|
+
const settled = await Promise.all(event.Records.map(async (record) => {
|
|
1409
|
+
try {
|
|
1410
|
+
return { record, parsed: await parseRecord(record) };
|
|
1411
|
+
} catch (err) {
|
|
1412
|
+
log.warn("Record resolution failed; reporting it as a batch item failure", {
|
|
1413
|
+
messageId: record.messageId,
|
|
1414
|
+
error: err instanceof Error ? err.message : String(err)
|
|
1415
|
+
});
|
|
1416
|
+
return { record, failed: true };
|
|
1417
|
+
}
|
|
1418
|
+
}));
|
|
1419
|
+
const failures = settled.filter((r) => "failed" in r).map((r) => r.record);
|
|
1420
|
+
const resolved = settled.filter((r) => !("failed" in r));
|
|
1421
|
+
const events = resolved.map((r) => r.parsed).filter((e) => e !== null);
|
|
1422
|
+
if (events.length === 0) {
|
|
1423
|
+
log.info("No resolvable CodePipeline events in batch", { itemFailures: failures.length });
|
|
1424
|
+
return batchResponse(failures);
|
|
1425
|
+
}
|
|
1426
|
+
const carried = resolved.filter((r) => r.parsed !== null);
|
|
1427
|
+
const send = async (batch) => {
|
|
1428
|
+
const body = JSON.stringify({ events: batch.map(({ orgId: _orgId, ...rest }) => rest) });
|
|
1429
|
+
const post = (token) => fetchWithTimeout(`${baseUrl2}/api/reports/events`, {
|
|
1430
|
+
method: "POST",
|
|
1431
|
+
headers: { "Content-Type": "application/json", "Authorization": `Bearer ${token}`, ...correlationHeaders({ requestId }) },
|
|
1432
|
+
body
|
|
1433
|
+
}).catch((err) => {
|
|
1434
|
+
throw new IngestUnreachableError(err);
|
|
1435
|
+
});
|
|
1436
|
+
let res2 = await post(await getAuthToken());
|
|
1437
|
+
if (res2.status === 401 || res2.status === 403) {
|
|
1438
|
+
log.warn("Reporting API auth failed; re-reading the stored key and retrying once", { status: res2.status });
|
|
1439
|
+
invalidateCredential();
|
|
1440
|
+
res2 = await post(await getAuthToken());
|
|
1441
|
+
}
|
|
1442
|
+
return res2;
|
|
1443
|
+
};
|
|
1444
|
+
let res;
|
|
1445
|
+
try {
|
|
1446
|
+
res = await send(events);
|
|
1447
|
+
} catch (err) {
|
|
1448
|
+
if (!(err instanceof IngestUnreachableError)) throw err;
|
|
1449
|
+
log.error("Reporting API call failed", { error: err.message });
|
|
1450
|
+
return batchResponse([...failures, ...carried.map((r) => r.record)]);
|
|
1451
|
+
}
|
|
1452
|
+
let delivered = events;
|
|
1453
|
+
if (!res.ok) {
|
|
1454
|
+
const body = await res.text().catch(() => "");
|
|
1455
|
+
if (!isRefusal(res.status)) {
|
|
1456
|
+
log.error(`Reporting API returned ${res.status}`, { body });
|
|
1457
|
+
return batchResponse([...failures, ...carried.map((r) => r.record)]);
|
|
1458
|
+
}
|
|
1459
|
+
delivered = [];
|
|
1460
|
+
if (carried.length === 1) {
|
|
1461
|
+
logRefused(carried[0], res.status, body);
|
|
1462
|
+
} else {
|
|
1463
|
+
log.warn("Reporting API refused the batch; delivering its events one at a time", { status: res.status, count: carried.length });
|
|
1464
|
+
const outcomes = await Promise.all(carried.map(async (pair) => {
|
|
1465
|
+
try {
|
|
1466
|
+
const one = await send([pair.parsed]);
|
|
1467
|
+
if (one.ok) return "delivered";
|
|
1468
|
+
const oneBody = await one.text().catch(() => "");
|
|
1469
|
+
if (isRefusal(one.status)) {
|
|
1470
|
+
logRefused(pair, one.status, oneBody);
|
|
1471
|
+
return "refused";
|
|
1472
|
+
}
|
|
1473
|
+
log.error(`Reporting API returned ${one.status} for one event`, { messageId: pair.record.messageId, body: oneBody });
|
|
1474
|
+
} catch (err) {
|
|
1475
|
+
log.error("Reporting API call failed for one event", { messageId: pair.record.messageId, error: err instanceof Error ? err.message : String(err) });
|
|
1476
|
+
}
|
|
1477
|
+
return "retry";
|
|
1478
|
+
}));
|
|
1479
|
+
carried.forEach((pair, i) => {
|
|
1480
|
+
if (outcomes[i] === "delivered") delivered.push(pair.parsed);
|
|
1481
|
+
else if (outcomes[i] === "retry") failures.push(pair.record);
|
|
1482
|
+
});
|
|
1483
|
+
}
|
|
1484
|
+
if (delivered.length === 0) return batchResponse(failures);
|
|
1485
|
+
log.info(`Ingested ${delivered.length} of ${carried.length} events one at a time`);
|
|
1486
|
+
} else {
|
|
1487
|
+
const result = await res.json().catch(() => ({}));
|
|
1488
|
+
log.info(`Ingested ${events.length} events`, { inserted: result.data });
|
|
1489
|
+
}
|
|
1490
|
+
recordForwarded(delivered);
|
|
1491
|
+
await reportHealthAndRedrive(baseUrl2, event.Records[0]?.eventSourceARN, requestId);
|
|
1492
|
+
await stampLastEvent();
|
|
1493
|
+
return batchResponse(failures);
|
|
1494
|
+
};
|
|
1495
|
+
var IngestUnreachableError = class extends Error {
|
|
1496
|
+
constructor(cause) {
|
|
1497
|
+
super(cause instanceof Error ? cause.message : String(cause));
|
|
1498
|
+
this.name = "IngestUnreachableError";
|
|
1499
|
+
}
|
|
1500
|
+
};
|
|
1501
|
+
function isRefusal(status) {
|
|
1502
|
+
return status === 400 || status === 413 || status === 422;
|
|
1503
|
+
}
|
|
1504
|
+
function logRefused(pair, status, body) {
|
|
1505
|
+
log.error("Reporting ingest refused an event; dropping it", {
|
|
1506
|
+
messageId: pair.record.messageId,
|
|
1507
|
+
status,
|
|
1508
|
+
body: body.slice(0, 1e3),
|
|
1509
|
+
pipelineId: pair.parsed.pipelineId,
|
|
1510
|
+
eventType: pair.parsed.eventType,
|
|
1511
|
+
executionId: pair.parsed.executionId
|
|
1512
|
+
});
|
|
1513
|
+
}
|
|
1514
|
+
function batchResponse(failed) {
|
|
1515
|
+
if (failed.length > 0) {
|
|
1516
|
+
log.warn("Returning batch item failures for redelivery", { count: failed.length });
|
|
1517
|
+
}
|
|
1518
|
+
return { batchItemFailures: failed.map((r) => ({ itemIdentifier: r.messageId })) };
|
|
1519
|
+
}
|
|
1520
|
+
function _resetForTests() {
|
|
1521
|
+
_resetTagsForTests();
|
|
1522
|
+
_resetScmForTests();
|
|
1523
|
+
_resetHealthForTests();
|
|
1524
|
+
_resetAuthForTests();
|
|
1525
|
+
}
|
|
1526
|
+
export {
|
|
1527
|
+
_resetForTests,
|
|
1528
|
+
handler
|
|
1529
|
+
};
|