@pipeline-builder/pipeline-events 6.3.4 → 6.4.1
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 +7 -4
- package/lib/auth.js +10 -32
- package/lib/config.d.ts +42 -0
- package/lib/config.js +79 -0
- package/lib/health.js +12 -12
- package/lib/index.d.ts +3 -7
- package/lib/index.js +230 -70
- package/lib/parse.d.ts +9 -0
- package/lib/parse.js +4 -2
- package/lib/scm.js +64 -45
- package/lib/tags.js +19 -16
- package/lib/util.d.ts +4 -13
- package/lib/util.js +7 -15
- package/package.json +3 -2
package/lib/index.js
CHANGED
|
@@ -14,7 +14,16 @@ async function readCredentialSecret(secretName, client2 = new SecretsManagerClie
|
|
|
14
14
|
const response = await client2.send(new GetSecretValueCommand({ SecretId: secretName }));
|
|
15
15
|
if (!response.SecretString)
|
|
16
16
|
throw new Error(`Secret "${secretName}" is empty`);
|
|
17
|
-
|
|
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;
|
|
18
27
|
}
|
|
19
28
|
async function readAccessKeyFromSecret(secretName) {
|
|
20
29
|
const secret = await readCredentialSecret(secretName);
|
|
@@ -117,6 +126,128 @@ function parseSynthFailure(line) {
|
|
|
117
126
|
}
|
|
118
127
|
}
|
|
119
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
|
+
// 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
|
+
|
|
120
251
|
// src/util.ts
|
|
121
252
|
import { createHash } from "node:crypto";
|
|
122
253
|
var log = {
|
|
@@ -165,30 +296,28 @@ var CACHE_MAX_ENTRIES = 5e3;
|
|
|
165
296
|
async function loadSdk(pkg) {
|
|
166
297
|
return await import(pkg);
|
|
167
298
|
}
|
|
168
|
-
|
|
169
|
-
function fetchWithTimeout(url, init = {}, timeoutMs = FETCH_TIMEOUT_MS) {
|
|
299
|
+
function fetchWithTimeout(url, init = {}, timeoutMs = loadEventsConfig().reportingFetchTimeoutMs) {
|
|
170
300
|
return fetch(url, { ...init, signal: AbortSignal.timeout(timeoutMs) });
|
|
171
301
|
}
|
|
172
302
|
|
|
173
303
|
// src/auth.ts
|
|
174
304
|
var TOKEN_REFRESH_FRACTION = 0.8;
|
|
175
|
-
var EXCHANGE_TIMEOUT_MS = 5e3;
|
|
176
305
|
var credential = createPlatformCredential({
|
|
177
|
-
secretName: () =>
|
|
178
|
-
envKeyVar:
|
|
306
|
+
secretName: () => loadEventsConfig().platformSecretName,
|
|
307
|
+
envKeyVar: PLATFORM_ACCESS_KEY_ENV
|
|
179
308
|
});
|
|
180
309
|
var cachedToken = null;
|
|
181
310
|
var cachedTokenExpiresAt = 0;
|
|
182
311
|
async function getAuthToken() {
|
|
183
312
|
if (cachedToken && Date.now() < cachedTokenExpiresAt) return cachedToken;
|
|
184
|
-
const
|
|
185
|
-
if (!
|
|
313
|
+
const baseUrl2 = loadEventsConfig().platformBaseUrl;
|
|
314
|
+
if (!baseUrl2) throw new Error("PLATFORM_BASE_URL environment variable is required");
|
|
186
315
|
const key = await credential.getKey();
|
|
187
|
-
const res = await fetchWithTimeout(`${
|
|
316
|
+
const res = await fetchWithTimeout(`${baseUrl2}/api/auth/token/exchange`, {
|
|
188
317
|
method: "POST",
|
|
189
318
|
headers: { "Content-Type": "application/json", "Accept": "application/json" },
|
|
190
319
|
body: JSON.stringify({ key })
|
|
191
|
-
}
|
|
320
|
+
});
|
|
192
321
|
if (!res.ok) {
|
|
193
322
|
if (res.status === 401 || res.status === 403) {
|
|
194
323
|
credential.invalidate();
|
|
@@ -247,18 +376,15 @@ var forwardedByOrg = new BoundedMap(CACHE_MAX_ENTRIES);
|
|
|
247
376
|
var lastEventAtByOrg = new BoundedMap(CACHE_MAX_ENTRIES);
|
|
248
377
|
var lastHealthAt = 0;
|
|
249
378
|
var lastRedriveAt = 0;
|
|
250
|
-
var HEALTH_THROTTLE_MS = 60 * 1e3;
|
|
251
|
-
var REDRIVE_THROTTLE_MS = 5 * 60 * 1e3;
|
|
252
|
-
var MAX_DLQ_REDRIVE_AGE_SEC = 6 * 60 * 60;
|
|
253
379
|
function deriveQueues(mainQueueArn) {
|
|
254
380
|
if (!mainQueueArn) return void 0;
|
|
255
381
|
const parts = mainQueueArn.split(":");
|
|
256
382
|
if (parts.length < 6 || parts[0] !== "arn" || parts[2] !== "sqs") return void 0;
|
|
257
383
|
const [, partition, , region, account, name] = parts;
|
|
258
|
-
const
|
|
259
|
-
const dlqName =
|
|
384
|
+
const dlqArn2 = loadEventsConfig().dlqArn || `arn:${partition}:sqs:${region}:${account}:${name}-dlq`;
|
|
385
|
+
const dlqName = dlqArn2.split(":").pop() ?? `${name}-dlq`;
|
|
260
386
|
const dlqUrl = `https://sqs.${region}.${dnsSuffixForPartition(partition)}/${account}/${dlqName}`;
|
|
261
|
-
return { region, mainArn: mainQueueArn, dlqArn, dlqName, dlqUrl };
|
|
387
|
+
return { region, mainArn: mainQueueArn, dlqArn: dlqArn2, dlqName, dlqUrl };
|
|
262
388
|
}
|
|
263
389
|
async function dlqDepth(region, dlqUrl) {
|
|
264
390
|
if (!sqsMod) sqsMod = await loadSdk("@aws-sdk/client-sqs");
|
|
@@ -286,21 +412,21 @@ async function dlqOldestAgeSec(region, dlqName) {
|
|
|
286
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];
|
|
287
413
|
return latest?.Maximum;
|
|
288
414
|
}
|
|
289
|
-
async function hasActiveMoveTask(region,
|
|
415
|
+
async function hasActiveMoveTask(region, dlqArn2) {
|
|
290
416
|
if (!sqsMod) sqsMod = await loadSdk("@aws-sdk/client-sqs");
|
|
291
417
|
const client2 = await sqsClient(region);
|
|
292
|
-
const out = await client2.send(new sqsMod.ListMessageMoveTasksCommand({ SourceArn:
|
|
418
|
+
const out = await client2.send(new sqsMod.ListMessageMoveTasksCommand({ SourceArn: dlqArn2 }));
|
|
293
419
|
return (out.Results ?? []).some((t) => t.Status === "RUNNING");
|
|
294
420
|
}
|
|
295
|
-
async function startMoveTask(region,
|
|
421
|
+
async function startMoveTask(region, dlqArn2, mainArn) {
|
|
296
422
|
if (!sqsMod) sqsMod = await loadSdk("@aws-sdk/client-sqs");
|
|
297
423
|
const client2 = await sqsClient(region);
|
|
298
|
-
await client2.send(new sqsMod.StartMessageMoveTaskCommand({ SourceArn:
|
|
424
|
+
await client2.send(new sqsMod.StartMessageMoveTaskCommand({ SourceArn: dlqArn2, DestinationArn: mainArn }));
|
|
299
425
|
}
|
|
300
|
-
async function postIngestHealth(
|
|
426
|
+
async function postIngestHealth(baseUrl2, body, requestId) {
|
|
301
427
|
try {
|
|
302
428
|
const token = await getAuthToken();
|
|
303
|
-
const res = await fetchWithTimeout(`${
|
|
429
|
+
const res = await fetchWithTimeout(`${baseUrl2}/api/reports/ingest-health`, {
|
|
304
430
|
method: "POST",
|
|
305
431
|
headers: { "Content-Type": "application/json", "Authorization": `Bearer ${token}`, ...correlationHeaders({ requestId }) },
|
|
306
432
|
body: JSON.stringify(body)
|
|
@@ -315,9 +441,10 @@ async function postIngestHealth(baseUrl, body, requestId) {
|
|
|
315
441
|
return false;
|
|
316
442
|
}
|
|
317
443
|
}
|
|
318
|
-
async function reportHealthAndRedrive(
|
|
444
|
+
async function reportHealthAndRedrive(baseUrl2, mainQueueArn, requestId) {
|
|
445
|
+
const { healthIntervalMs, redriveIntervalMs, redriveMaxAgeSec } = loadEventsConfig();
|
|
319
446
|
const now = Date.now();
|
|
320
|
-
if (now - lastHealthAt <
|
|
447
|
+
if (now - lastHealthAt < healthIntervalMs) return;
|
|
321
448
|
lastHealthAt = now;
|
|
322
449
|
try {
|
|
323
450
|
const q = deriveQueues(mainQueueArn);
|
|
@@ -334,7 +461,7 @@ async function reportHealthAndRedrive(baseUrl, mainQueueArn, requestId) {
|
|
|
334
461
|
for (const key of orgKeys) {
|
|
335
462
|
const forwarded = forwardedByOrg.get(key) ?? 0;
|
|
336
463
|
const lastEventAt = lastEventAtByOrg.get(key);
|
|
337
|
-
const ok = await postIngestHealth(
|
|
464
|
+
const ok = await postIngestHealth(baseUrl2, {
|
|
338
465
|
...key ? { orgId: key } : {},
|
|
339
466
|
forwarded,
|
|
340
467
|
dropped: depth,
|
|
@@ -342,7 +469,7 @@ async function reportHealthAndRedrive(baseUrl, mainQueueArn, requestId) {
|
|
|
342
469
|
}, requestId);
|
|
343
470
|
if (ok) forwardedByOrg.set(key, 0);
|
|
344
471
|
}
|
|
345
|
-
if (q && depth > 0 && now - lastRedriveAt >=
|
|
472
|
+
if (q && depth > 0 && now - lastRedriveAt >= redriveIntervalMs) {
|
|
346
473
|
let oldestAgeSec;
|
|
347
474
|
try {
|
|
348
475
|
oldestAgeSec = await dlqOldestAgeSec(q.region, q.dlqName);
|
|
@@ -351,12 +478,12 @@ async function reportHealthAndRedrive(baseUrl, mainQueueArn, requestId) {
|
|
|
351
478
|
}
|
|
352
479
|
if (oldestAgeSec === void 0) {
|
|
353
480
|
log.info("DLQ oldest-message age not available yet \u2014 redrive deferred", { dlq: arnRef(q.dlqArn), dropped: depth });
|
|
354
|
-
} else if (oldestAgeSec >
|
|
481
|
+
} else if (oldestAgeSec > redriveMaxAgeSec) {
|
|
355
482
|
log.warn("DLQ oldest message exceeds poison-age ceiling \u2014 skipping redrive (needs manual attention)", {
|
|
356
483
|
dlq: arnRef(q.dlqArn),
|
|
357
484
|
dropped: depth,
|
|
358
485
|
oldestAgeSec,
|
|
359
|
-
ceilingSec:
|
|
486
|
+
ceilingSec: redriveMaxAgeSec
|
|
360
487
|
});
|
|
361
488
|
} else {
|
|
362
489
|
try {
|
|
@@ -485,6 +612,28 @@ async function readSynthFailure(region, buildId) {
|
|
|
485
612
|
|
|
486
613
|
// src/scm.ts
|
|
487
614
|
import { GetSecretValueCommand as GetSecretValueCommand2, SecretsManagerClient as SecretsManagerClient2 } from "@aws-sdk/client-secrets-manager";
|
|
615
|
+
|
|
616
|
+
// ../api-core/lib/types/pipeline-source.js
|
|
617
|
+
var GITHUB_OWNER_PATTERN = /^[A-Za-z0-9](?:[A-Za-z0-9]|-(?=[A-Za-z0-9])){0,38}$/;
|
|
618
|
+
function githubOwnerProblem(owner) {
|
|
619
|
+
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.";
|
|
620
|
+
}
|
|
621
|
+
var DEFAULT_SECRETS_PATH_PREFIX = "pipeline-builder";
|
|
622
|
+
function githubTokenSecretName(orgId, owner, prefix = DEFAULT_SECRETS_PATH_PREFIX) {
|
|
623
|
+
const base = `${prefix}/${orgId}/github-token`;
|
|
624
|
+
if (owner === void 0)
|
|
625
|
+
return base;
|
|
626
|
+
const problem = githubOwnerProblem(owner);
|
|
627
|
+
if (problem)
|
|
628
|
+
throw new Error(`Invalid GitHub owner "${owner}": ${problem}`);
|
|
629
|
+
return `${base}/${owner.toLowerCase()}`;
|
|
630
|
+
}
|
|
631
|
+
function githubTokenStoreCommand(owner, region = "<region>") {
|
|
632
|
+
return `pipeline-manager infra store-github-token --region ${region}${owner ? ` --owner ${owner.toLowerCase()}` : ""}`;
|
|
633
|
+
}
|
|
634
|
+
var GITHUB_TOKEN_STORE_COMMAND = githubTokenStoreCommand();
|
|
635
|
+
|
|
636
|
+
// src/scm.ts
|
|
488
637
|
var commitResultCache = new BoundedMap(CACHE_MAX_ENTRIES);
|
|
489
638
|
var lastShaByPipeline = new BoundedMap(CACHE_MAX_ENTRIES);
|
|
490
639
|
var NO_RECORDED_DEPLOY_MAX = 1e3;
|
|
@@ -493,42 +642,50 @@ var commitMetaCache = new BoundedMap(CACHE_MAX_ENTRIES);
|
|
|
493
642
|
var scmCooldownUntil = 0;
|
|
494
643
|
var SCM_COOLDOWN_MS = 2 * 60 * 1e3;
|
|
495
644
|
var MAX_COMMIT_WALK = 50;
|
|
496
|
-
var SCM_FETCH_TIMEOUT_MS = 3e3;
|
|
497
645
|
var githubTokenByOrg = new BoundedMap(CACHE_MAX_ENTRIES);
|
|
498
646
|
var githubTokenMissUntil = new BoundedMap(CACHE_MAX_ENTRIES);
|
|
499
647
|
var GITHUB_TOKEN_MISS_TTL_MS = 6e4;
|
|
500
|
-
function
|
|
501
|
-
const name =
|
|
502
|
-
if (!name || !name.endsWith("/platform")) return
|
|
648
|
+
function githubTokenSecretNames(orgId, owner) {
|
|
649
|
+
const name = loadEventsConfig().platformSecretName;
|
|
650
|
+
if (!name || !name.endsWith("/platform")) return [];
|
|
503
651
|
const base = name.slice(0, -"/platform".length);
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
652
|
+
const slash = base.lastIndexOf("/");
|
|
653
|
+
if (slash <= 0) return [];
|
|
654
|
+
const prefix = base.slice(0, slash);
|
|
655
|
+
const org = orgId ?? base.slice(slash + 1);
|
|
656
|
+
const orgDefault = githubTokenSecretName(org, void 0, prefix);
|
|
657
|
+
return owner && !githubOwnerProblem(owner) ? [githubTokenSecretName(org, owner, prefix), orgDefault] : [orgDefault];
|
|
658
|
+
}
|
|
659
|
+
async function readTokenSecret(secretName, orgId) {
|
|
660
|
+
try {
|
|
661
|
+
const client2 = new SecretsManagerClient2({});
|
|
662
|
+
const res = await client2.send(new GetSecretValueCommand2({ SecretId: secretName }));
|
|
663
|
+
return res.SecretString && res.SecretString.length > 0 ? res.SecretString.trim() || null : null;
|
|
664
|
+
} catch (err) {
|
|
665
|
+
const error = err?.name;
|
|
666
|
+
if (error !== "ResourceNotFoundException") log.warn("github-token secret could not be read", { orgId, secretName, error });
|
|
667
|
+
return null;
|
|
508
668
|
}
|
|
509
|
-
return `${base}/github-token`;
|
|
510
669
|
}
|
|
511
|
-
async function getGitHubToken(orgId) {
|
|
512
|
-
const
|
|
670
|
+
async function getGitHubToken(orgId, owner) {
|
|
671
|
+
const ownerKey = owner?.toLowerCase();
|
|
672
|
+
const key = `${orgId ?? ""}|${ownerKey ?? ""}`;
|
|
513
673
|
const cached = githubTokenByOrg.get(key);
|
|
514
674
|
if (cached !== void 0) return cached;
|
|
515
675
|
const missUntil = githubTokenMissUntil.get(key);
|
|
516
676
|
if (missUntil !== void 0 && Date.now() < missUntil) return null;
|
|
517
|
-
const
|
|
518
|
-
if (
|
|
519
|
-
let token;
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
token = res.SecretString && res.SecretString.length > 0 ? res.SecretString.trim() : null;
|
|
524
|
-
} catch (err) {
|
|
525
|
-
log.warn("No github-token secret \u2014 GitHub commit resolution will be unauthenticated", { orgId, error: err?.name });
|
|
526
|
-
token = null;
|
|
677
|
+
const names = githubTokenSecretNames(orgId, ownerKey);
|
|
678
|
+
if (names.length === 0) return null;
|
|
679
|
+
let token = null;
|
|
680
|
+
for (const secretName of names) {
|
|
681
|
+
token = await readTokenSecret(secretName, orgId);
|
|
682
|
+
if (token) break;
|
|
527
683
|
}
|
|
528
684
|
if (token) {
|
|
529
685
|
githubTokenByOrg.set(key, token);
|
|
530
686
|
githubTokenMissUntil.delete(key);
|
|
531
687
|
} else {
|
|
688
|
+
log.warn("No github-token secret (owner or org default) \u2014 GitHub commit resolution will be unauthenticated", { orgId, secretNames: names });
|
|
532
689
|
githubTokenMissUntil.set(key, Date.now() + GITHUB_TOKEN_MISS_TTL_MS);
|
|
533
690
|
}
|
|
534
691
|
return token;
|
|
@@ -610,7 +767,7 @@ async function resolveCodeCommit(region, repositoryName, sha, sinceSha) {
|
|
|
610
767
|
return oldest ? { commitTimestamp: oldest, commitCount: count } : {};
|
|
611
768
|
}
|
|
612
769
|
async function resolveGitHub(owner, repo, sha, sinceSha, orgId) {
|
|
613
|
-
const token = await getGitHubToken(orgId);
|
|
770
|
+
const token = await getGitHubToken(orgId, owner);
|
|
614
771
|
const headers = {
|
|
615
772
|
"Accept": "application/vnd.github+json",
|
|
616
773
|
"User-Agent": "pipeline-builder-forwarder",
|
|
@@ -618,8 +775,9 @@ async function resolveGitHub(owner, repo, sha, sinceSha, orgId) {
|
|
|
618
775
|
};
|
|
619
776
|
if (token) headers.Authorization = `Bearer ${token}`;
|
|
620
777
|
const rateLimited = (r) => r.status === 403 || r.status === 429;
|
|
778
|
+
const base = `https://api.github.com/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}`;
|
|
621
779
|
if (sinceSha) {
|
|
622
|
-
const r = await fetchWithTimeout(
|
|
780
|
+
const r = await fetchWithTimeout(`${base}/compare/${encodeURIComponent(sinceSha)}...${encodeURIComponent(sha)}`, { headers }, loadEventsConfig().scmFetchTimeoutMs);
|
|
623
781
|
if (rateLimited(r)) {
|
|
624
782
|
scmCooldownUntil = Date.now() + SCM_COOLDOWN_MS;
|
|
625
783
|
return {};
|
|
@@ -634,7 +792,7 @@ async function resolveGitHub(owner, repo, sha, sinceSha, orgId) {
|
|
|
634
792
|
}
|
|
635
793
|
}
|
|
636
794
|
}
|
|
637
|
-
const r2 = await fetchWithTimeout(
|
|
795
|
+
const r2 = await fetchWithTimeout(`${base}/commits/${encodeURIComponent(sha)}`, { headers }, loadEventsConfig().scmFetchTimeoutMs);
|
|
638
796
|
if (rateLimited(r2)) {
|
|
639
797
|
scmCooldownUntil = Date.now() + SCM_COOLDOWN_MS;
|
|
640
798
|
return {};
|
|
@@ -647,9 +805,9 @@ async function resolveGitHub(owner, repo, sha, sinceSha, orgId) {
|
|
|
647
805
|
return {};
|
|
648
806
|
}
|
|
649
807
|
async function resolveBitbucket(owner, repo, sha) {
|
|
650
|
-
const r = await fetchWithTimeout(`https://api.bitbucket.org/2.0/repositories/${owner}/${repo}/commit/${sha}`, {
|
|
808
|
+
const r = await fetchWithTimeout(`https://api.bitbucket.org/2.0/repositories/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/commit/${encodeURIComponent(sha)}`, {
|
|
651
809
|
headers: { "User-Agent": "pipeline-builder-forwarder", "Accept": "application/json" }
|
|
652
|
-
},
|
|
810
|
+
}, loadEventsConfig().scmFetchTimeoutMs);
|
|
653
811
|
if (r.status === 429) {
|
|
654
812
|
scmCooldownUntil = Date.now() + SCM_COOLDOWN_MS;
|
|
655
813
|
return {};
|
|
@@ -693,11 +851,11 @@ function markDeployed(pipelineId, sha) {
|
|
|
693
851
|
noRecordedDeploy.delete(pipelineId);
|
|
694
852
|
}
|
|
695
853
|
async function fetchLastDeployedSha(pipelineId) {
|
|
696
|
-
const
|
|
697
|
-
if (!
|
|
854
|
+
const baseUrl2 = loadEventsConfig().platformBaseUrl;
|
|
855
|
+
if (!baseUrl2 || noRecordedDeploy.has(pipelineId)) return void 0;
|
|
698
856
|
try {
|
|
699
857
|
const res = await fetchWithTimeout(
|
|
700
|
-
`${
|
|
858
|
+
`${baseUrl2}/api/reports/events/last-deploy-commit?pipelineId=${encodeURIComponent(pipelineId)}`,
|
|
701
859
|
{ headers: { Authorization: `Bearer ${await getAuthToken()}`, Accept: "application/json" } }
|
|
702
860
|
);
|
|
703
861
|
if (!res.ok) {
|
|
@@ -740,8 +898,6 @@ var DEPLOYS_TAG = "pb.deploys";
|
|
|
740
898
|
var ORG_ID_TAG = "OrgId";
|
|
741
899
|
var clientsByRegion = /* @__PURE__ */ new Map();
|
|
742
900
|
var resolvedByArn = new BoundedMap(CACHE_MAX_ENTRIES);
|
|
743
|
-
var NEG_CACHE_TTL_MS = 5 * 60 * 1e3;
|
|
744
|
-
var POS_CACHE_TTL_MS = 15 * 60 * 1e3;
|
|
745
901
|
var MAX_ATTR = 255;
|
|
746
902
|
function parseDeploys(value) {
|
|
747
903
|
const map = /* @__PURE__ */ new Map();
|
|
@@ -766,7 +922,8 @@ async function pipelineClient(region) {
|
|
|
766
922
|
}
|
|
767
923
|
async function resolvePipeline(arn, region) {
|
|
768
924
|
const cached = resolvedByArn.get(arn);
|
|
769
|
-
|
|
925
|
+
const { tagCacheTtlMs, tagMissCacheTtlMs } = loadEventsConfig();
|
|
926
|
+
if (cached && Date.now() - cached.ts < (cached.pipelineId !== null ? tagCacheTtlMs : tagMissCacheTtlMs)) {
|
|
770
927
|
return { pipelineId: cached.pipelineId, orgId: cached.orgId, deploys: cached.deploys };
|
|
771
928
|
}
|
|
772
929
|
try {
|
|
@@ -785,17 +942,19 @@ async function resolvePipeline(arn, region) {
|
|
|
785
942
|
log.error("AccessDenied calling codepipeline:ListTagsForResource \u2014 grant it to the Lambda role", { pipeline: arnRef(arn), error: name });
|
|
786
943
|
throw err;
|
|
787
944
|
}
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
const retryable = e.$retryable != null || typeof status === "number" && status >= 500 || /throttl|timeout|toomanyrequests|serviceunavailable|econnreset|networkingerror/i.test(name ?? "");
|
|
791
|
-
if (retryable) {
|
|
792
|
-
log.error("Transient error resolving pb.pipeline-id tag \u2014 will retry the batch", { pipeline: arnRef(arn), error: name ?? String(err) });
|
|
945
|
+
if (!isDefinitiveTagAnswer(err)) {
|
|
946
|
+
log.error("Error resolving pb.pipeline-id tag \u2014 will retry the record", { pipeline: arnRef(arn), error: name ?? String(err) });
|
|
793
947
|
throw err;
|
|
794
948
|
}
|
|
795
949
|
log.error("Failed to resolve pb.pipeline-id tag", { pipeline: arnRef(arn), error: name ?? String(err) });
|
|
796
950
|
return { pipelineId: null, orgId: null, deploys: /* @__PURE__ */ new Map() };
|
|
797
951
|
}
|
|
798
952
|
}
|
|
953
|
+
var DEFINITIVE_TAG_ERRORS = /* @__PURE__ */ new Set(["ResourceNotFoundException", "InvalidArnException", "ValidationException"]);
|
|
954
|
+
function isDefinitiveTagAnswer(err) {
|
|
955
|
+
const e = err;
|
|
956
|
+
return e?.$retryable == null && typeof e?.name === "string" && DEFINITIVE_TAG_ERRORS.has(e.name);
|
|
957
|
+
}
|
|
799
958
|
function _resetTagsForTests() {
|
|
800
959
|
resolvedByArn.clear();
|
|
801
960
|
}
|
|
@@ -919,7 +1078,7 @@ async function parseRecord(record) {
|
|
|
919
1078
|
const environment = stageName ? deploys.get(stageName) : void 0;
|
|
920
1079
|
let commitTimestamp;
|
|
921
1080
|
let commitCount;
|
|
922
|
-
if (commitSha &&
|
|
1081
|
+
if (commitSha && loadEventsConfig().doraEnabled) {
|
|
923
1082
|
const src = classifySource(revisionUrl);
|
|
924
1083
|
const successfulDeploy = eventType === "STAGE" && !!environment && DEPLOY_SUCCEEDED_STATES.has(state);
|
|
925
1084
|
const info = await resolveCommitInfo(pipelineId, orgId, event.region, { sha: commitSha, ...src }, { successfulDeploy });
|
|
@@ -930,6 +1089,7 @@ async function parseRecord(record) {
|
|
|
930
1089
|
orgId,
|
|
931
1090
|
pipelineId,
|
|
932
1091
|
...event.region && { region: event.region },
|
|
1092
|
+
pipelineName,
|
|
933
1093
|
eventSource,
|
|
934
1094
|
eventType,
|
|
935
1095
|
status: state,
|
|
@@ -955,8 +1115,8 @@ async function parseRecord(record) {
|
|
|
955
1115
|
|
|
956
1116
|
// src/index.ts
|
|
957
1117
|
var handler = async (event, context) => {
|
|
958
|
-
const
|
|
959
|
-
if (!
|
|
1118
|
+
const baseUrl2 = loadEventsConfig().platformBaseUrl;
|
|
1119
|
+
if (!baseUrl2) throw new Error("PLATFORM_BASE_URL environment variable is required");
|
|
960
1120
|
const requestId = context?.awsRequestId || randomUUID();
|
|
961
1121
|
const settled = await Promise.all(event.Records.map(async (record) => {
|
|
962
1122
|
try {
|
|
@@ -979,7 +1139,7 @@ var handler = async (event, context) => {
|
|
|
979
1139
|
const carried = resolved.filter((r) => r.parsed !== null);
|
|
980
1140
|
const send = async (batch) => {
|
|
981
1141
|
const body = JSON.stringify({ events: batch.map(({ orgId: _orgId, ...rest }) => rest) });
|
|
982
|
-
const post = (token) => fetchWithTimeout(`${
|
|
1142
|
+
const post = (token) => fetchWithTimeout(`${baseUrl2}/api/reports/events`, {
|
|
983
1143
|
method: "POST",
|
|
984
1144
|
headers: { "Content-Type": "application/json", "Authorization": `Bearer ${token}`, ...correlationHeaders({ requestId }) },
|
|
985
1145
|
body
|
|
@@ -1041,7 +1201,7 @@ var handler = async (event, context) => {
|
|
|
1041
1201
|
log.info(`Ingested ${events.length} events`, { inserted: result.data });
|
|
1042
1202
|
}
|
|
1043
1203
|
recordForwarded(delivered);
|
|
1044
|
-
await reportHealthAndRedrive(
|
|
1204
|
+
await reportHealthAndRedrive(baseUrl2, event.Records[0]?.eventSourceARN, requestId);
|
|
1045
1205
|
return batchResponse(failures);
|
|
1046
1206
|
};
|
|
1047
1207
|
var IngestUnreachableError = class extends Error {
|
package/lib/parse.d.ts
CHANGED
|
@@ -13,6 +13,15 @@ export interface ParsedEvent {
|
|
|
13
13
|
* stored on the event: it is the region a first-event self-registration
|
|
14
14
|
* records for a pipeline the platform has no registry row for. */
|
|
15
15
|
region?: string;
|
|
16
|
+
/**
|
|
17
|
+
* The CodePipeline name the event carried (`detail.pipeline`) — the name the
|
|
18
|
+
* pipeline ACTUALLY deployed as. Not stored on the event: a first-event
|
|
19
|
+
* self-registration records it in place of the name derived from the
|
|
20
|
+
* pipeline record. There is no stack-name counterpart: the event does not
|
|
21
|
+
* carry one, and CodePipeline's ListTagsForResource does not return the
|
|
22
|
+
* `aws:cloudformation:stack-name` system tag, so none is forwarded.
|
|
23
|
+
*/
|
|
24
|
+
pipelineName?: string;
|
|
16
25
|
eventSource: string;
|
|
17
26
|
eventType: string;
|
|
18
27
|
status: string;
|