@pipeline-builder/pipeline-events 6.4.0 → 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/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
- return JSON.parse(response.SecretString);
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,33 +296,28 @@ var CACHE_MAX_ENTRIES = 5e3;
165
296
  async function loadSdk(pkg) {
166
297
  return await import(pkg);
167
298
  }
168
- var FETCH_TIMEOUT_MS = (() => {
169
- const raw = Number(process.env.REPORTING_FETCH_TIMEOUT_MS);
170
- return Number.isFinite(raw) && raw > 0 ? raw : 5e3;
171
- })();
172
- function fetchWithTimeout(url, init = {}, timeoutMs = FETCH_TIMEOUT_MS) {
299
+ function fetchWithTimeout(url, init = {}, timeoutMs = loadEventsConfig().reportingFetchTimeoutMs) {
173
300
  return fetch(url, { ...init, signal: AbortSignal.timeout(timeoutMs) });
174
301
  }
175
302
 
176
303
  // src/auth.ts
177
304
  var TOKEN_REFRESH_FRACTION = 0.8;
178
- var EXCHANGE_TIMEOUT_MS = 5e3;
179
305
  var credential = createPlatformCredential({
180
- secretName: () => process.env.PLATFORM_SECRET_NAME,
181
- envKeyVar: "PLATFORM_ACCESS_KEY"
306
+ secretName: () => loadEventsConfig().platformSecretName,
307
+ envKeyVar: PLATFORM_ACCESS_KEY_ENV
182
308
  });
183
309
  var cachedToken = null;
184
310
  var cachedTokenExpiresAt = 0;
185
311
  async function getAuthToken() {
186
312
  if (cachedToken && Date.now() < cachedTokenExpiresAt) return cachedToken;
187
- const baseUrl = (process.env.PLATFORM_BASE_URL || "").replace(/\/+$/, "");
188
- if (!baseUrl) throw new Error("PLATFORM_BASE_URL environment variable is required");
313
+ const baseUrl2 = loadEventsConfig().platformBaseUrl;
314
+ if (!baseUrl2) throw new Error("PLATFORM_BASE_URL environment variable is required");
189
315
  const key = await credential.getKey();
190
- const res = await fetchWithTimeout(`${baseUrl}/api/auth/token/exchange`, {
316
+ const res = await fetchWithTimeout(`${baseUrl2}/api/auth/token/exchange`, {
191
317
  method: "POST",
192
318
  headers: { "Content-Type": "application/json", "Accept": "application/json" },
193
319
  body: JSON.stringify({ key })
194
- }, EXCHANGE_TIMEOUT_MS);
320
+ });
195
321
  if (!res.ok) {
196
322
  if (res.status === 401 || res.status === 403) {
197
323
  credential.invalidate();
@@ -250,18 +376,15 @@ var forwardedByOrg = new BoundedMap(CACHE_MAX_ENTRIES);
250
376
  var lastEventAtByOrg = new BoundedMap(CACHE_MAX_ENTRIES);
251
377
  var lastHealthAt = 0;
252
378
  var lastRedriveAt = 0;
253
- var HEALTH_THROTTLE_MS = 60 * 1e3;
254
- var REDRIVE_THROTTLE_MS = 5 * 60 * 1e3;
255
- var MAX_DLQ_REDRIVE_AGE_SEC = 6 * 60 * 60;
256
379
  function deriveQueues(mainQueueArn) {
257
380
  if (!mainQueueArn) return void 0;
258
381
  const parts = mainQueueArn.split(":");
259
382
  if (parts.length < 6 || parts[0] !== "arn" || parts[2] !== "sqs") return void 0;
260
383
  const [, partition, , region, account, name] = parts;
261
- const dlqArn = process.env.EVENT_DLQ_ARN || `arn:${partition}:sqs:${region}:${account}:${name}-dlq`;
262
- const dlqName = dlqArn.split(":").pop() ?? `${name}-dlq`;
384
+ const dlqArn2 = loadEventsConfig().dlqArn || `arn:${partition}:sqs:${region}:${account}:${name}-dlq`;
385
+ const dlqName = dlqArn2.split(":").pop() ?? `${name}-dlq`;
263
386
  const dlqUrl = `https://sqs.${region}.${dnsSuffixForPartition(partition)}/${account}/${dlqName}`;
264
- return { region, mainArn: mainQueueArn, dlqArn, dlqName, dlqUrl };
387
+ return { region, mainArn: mainQueueArn, dlqArn: dlqArn2, dlqName, dlqUrl };
265
388
  }
266
389
  async function dlqDepth(region, dlqUrl) {
267
390
  if (!sqsMod) sqsMod = await loadSdk("@aws-sdk/client-sqs");
@@ -289,21 +412,21 @@ async function dlqOldestAgeSec(region, dlqName) {
289
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];
290
413
  return latest?.Maximum;
291
414
  }
292
- async function hasActiveMoveTask(region, dlqArn) {
415
+ async function hasActiveMoveTask(region, dlqArn2) {
293
416
  if (!sqsMod) sqsMod = await loadSdk("@aws-sdk/client-sqs");
294
417
  const client2 = await sqsClient(region);
295
- const out = await client2.send(new sqsMod.ListMessageMoveTasksCommand({ SourceArn: dlqArn }));
418
+ const out = await client2.send(new sqsMod.ListMessageMoveTasksCommand({ SourceArn: dlqArn2 }));
296
419
  return (out.Results ?? []).some((t) => t.Status === "RUNNING");
297
420
  }
298
- async function startMoveTask(region, dlqArn, mainArn) {
421
+ async function startMoveTask(region, dlqArn2, mainArn) {
299
422
  if (!sqsMod) sqsMod = await loadSdk("@aws-sdk/client-sqs");
300
423
  const client2 = await sqsClient(region);
301
- await client2.send(new sqsMod.StartMessageMoveTaskCommand({ SourceArn: dlqArn, DestinationArn: mainArn }));
424
+ await client2.send(new sqsMod.StartMessageMoveTaskCommand({ SourceArn: dlqArn2, DestinationArn: mainArn }));
302
425
  }
303
- async function postIngestHealth(baseUrl, body, requestId) {
426
+ async function postIngestHealth(baseUrl2, body, requestId) {
304
427
  try {
305
428
  const token = await getAuthToken();
306
- const res = await fetchWithTimeout(`${baseUrl}/api/reports/ingest-health`, {
429
+ const res = await fetchWithTimeout(`${baseUrl2}/api/reports/ingest-health`, {
307
430
  method: "POST",
308
431
  headers: { "Content-Type": "application/json", "Authorization": `Bearer ${token}`, ...correlationHeaders({ requestId }) },
309
432
  body: JSON.stringify(body)
@@ -318,9 +441,10 @@ async function postIngestHealth(baseUrl, body, requestId) {
318
441
  return false;
319
442
  }
320
443
  }
321
- async function reportHealthAndRedrive(baseUrl, mainQueueArn, requestId) {
444
+ async function reportHealthAndRedrive(baseUrl2, mainQueueArn, requestId) {
445
+ const { healthIntervalMs, redriveIntervalMs, redriveMaxAgeSec } = loadEventsConfig();
322
446
  const now = Date.now();
323
- if (now - lastHealthAt < HEALTH_THROTTLE_MS) return;
447
+ if (now - lastHealthAt < healthIntervalMs) return;
324
448
  lastHealthAt = now;
325
449
  try {
326
450
  const q = deriveQueues(mainQueueArn);
@@ -337,7 +461,7 @@ async function reportHealthAndRedrive(baseUrl, mainQueueArn, requestId) {
337
461
  for (const key of orgKeys) {
338
462
  const forwarded = forwardedByOrg.get(key) ?? 0;
339
463
  const lastEventAt = lastEventAtByOrg.get(key);
340
- const ok = await postIngestHealth(baseUrl, {
464
+ const ok = await postIngestHealth(baseUrl2, {
341
465
  ...key ? { orgId: key } : {},
342
466
  forwarded,
343
467
  dropped: depth,
@@ -345,7 +469,7 @@ async function reportHealthAndRedrive(baseUrl, mainQueueArn, requestId) {
345
469
  }, requestId);
346
470
  if (ok) forwardedByOrg.set(key, 0);
347
471
  }
348
- if (q && depth > 0 && now - lastRedriveAt >= REDRIVE_THROTTLE_MS) {
472
+ if (q && depth > 0 && now - lastRedriveAt >= redriveIntervalMs) {
349
473
  let oldestAgeSec;
350
474
  try {
351
475
  oldestAgeSec = await dlqOldestAgeSec(q.region, q.dlqName);
@@ -354,12 +478,12 @@ async function reportHealthAndRedrive(baseUrl, mainQueueArn, requestId) {
354
478
  }
355
479
  if (oldestAgeSec === void 0) {
356
480
  log.info("DLQ oldest-message age not available yet \u2014 redrive deferred", { dlq: arnRef(q.dlqArn), dropped: depth });
357
- } else if (oldestAgeSec > MAX_DLQ_REDRIVE_AGE_SEC) {
481
+ } else if (oldestAgeSec > redriveMaxAgeSec) {
358
482
  log.warn("DLQ oldest message exceeds poison-age ceiling \u2014 skipping redrive (needs manual attention)", {
359
483
  dlq: arnRef(q.dlqArn),
360
484
  dropped: depth,
361
485
  oldestAgeSec,
362
- ceilingSec: MAX_DLQ_REDRIVE_AGE_SEC
486
+ ceilingSec: redriveMaxAgeSec
363
487
  });
364
488
  } else {
365
489
  try {
@@ -488,6 +612,28 @@ async function readSynthFailure(region, buildId) {
488
612
 
489
613
  // src/scm.ts
490
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
491
637
  var commitResultCache = new BoundedMap(CACHE_MAX_ENTRIES);
492
638
  var lastShaByPipeline = new BoundedMap(CACHE_MAX_ENTRIES);
493
639
  var NO_RECORDED_DEPLOY_MAX = 1e3;
@@ -496,42 +642,50 @@ var commitMetaCache = new BoundedMap(CACHE_MAX_ENTRIES);
496
642
  var scmCooldownUntil = 0;
497
643
  var SCM_COOLDOWN_MS = 2 * 60 * 1e3;
498
644
  var MAX_COMMIT_WALK = 50;
499
- var SCM_FETCH_TIMEOUT_MS = 3e3;
500
645
  var githubTokenByOrg = new BoundedMap(CACHE_MAX_ENTRIES);
501
646
  var githubTokenMissUntil = new BoundedMap(CACHE_MAX_ENTRIES);
502
647
  var GITHUB_TOKEN_MISS_TTL_MS = 6e4;
503
- function githubTokenSecretName(orgId) {
504
- const name = process.env.PLATFORM_SECRET_NAME;
505
- if (!name || !name.endsWith("/platform")) return void 0;
648
+ function githubTokenSecretNames(orgId, owner) {
649
+ const name = loadEventsConfig().platformSecretName;
650
+ if (!name || !name.endsWith("/platform")) return [];
506
651
  const base = name.slice(0, -"/platform".length);
507
- if (orgId) {
508
- const slash = base.lastIndexOf("/");
509
- const prefix = slash > 0 ? base.slice(0, slash) : base;
510
- return `${prefix}/${orgId}/github-token`;
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;
511
668
  }
512
- return `${base}/github-token`;
513
669
  }
514
- async function getGitHubToken(orgId) {
515
- const key = orgId ?? "";
670
+ async function getGitHubToken(orgId, owner) {
671
+ const ownerKey = owner?.toLowerCase();
672
+ const key = `${orgId ?? ""}|${ownerKey ?? ""}`;
516
673
  const cached = githubTokenByOrg.get(key);
517
674
  if (cached !== void 0) return cached;
518
675
  const missUntil = githubTokenMissUntil.get(key);
519
676
  if (missUntil !== void 0 && Date.now() < missUntil) return null;
520
- const secretName = githubTokenSecretName(orgId);
521
- if (!secretName) return null;
522
- let token;
523
- try {
524
- const client2 = new SecretsManagerClient2({});
525
- const res = await client2.send(new GetSecretValueCommand2({ SecretId: secretName }));
526
- token = res.SecretString && res.SecretString.length > 0 ? res.SecretString.trim() : null;
527
- } catch (err) {
528
- log.warn("No github-token secret \u2014 GitHub commit resolution will be unauthenticated", { orgId, error: err?.name });
529
- 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;
530
683
  }
531
684
  if (token) {
532
685
  githubTokenByOrg.set(key, token);
533
686
  githubTokenMissUntil.delete(key);
534
687
  } else {
688
+ log.warn("No github-token secret (owner or org default) \u2014 GitHub commit resolution will be unauthenticated", { orgId, secretNames: names });
535
689
  githubTokenMissUntil.set(key, Date.now() + GITHUB_TOKEN_MISS_TTL_MS);
536
690
  }
537
691
  return token;
@@ -613,7 +767,7 @@ async function resolveCodeCommit(region, repositoryName, sha, sinceSha) {
613
767
  return oldest ? { commitTimestamp: oldest, commitCount: count } : {};
614
768
  }
615
769
  async function resolveGitHub(owner, repo, sha, sinceSha, orgId) {
616
- const token = await getGitHubToken(orgId);
770
+ const token = await getGitHubToken(orgId, owner);
617
771
  const headers = {
618
772
  "Accept": "application/vnd.github+json",
619
773
  "User-Agent": "pipeline-builder-forwarder",
@@ -621,8 +775,9 @@ async function resolveGitHub(owner, repo, sha, sinceSha, orgId) {
621
775
  };
622
776
  if (token) headers.Authorization = `Bearer ${token}`;
623
777
  const rateLimited = (r) => r.status === 403 || r.status === 429;
778
+ const base = `https://api.github.com/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}`;
624
779
  if (sinceSha) {
625
- const r = await fetchWithTimeout(`https://api.github.com/repos/${owner}/${repo}/compare/${sinceSha}...${sha}`, { headers }, SCM_FETCH_TIMEOUT_MS);
780
+ const r = await fetchWithTimeout(`${base}/compare/${encodeURIComponent(sinceSha)}...${encodeURIComponent(sha)}`, { headers }, loadEventsConfig().scmFetchTimeoutMs);
626
781
  if (rateLimited(r)) {
627
782
  scmCooldownUntil = Date.now() + SCM_COOLDOWN_MS;
628
783
  return {};
@@ -637,7 +792,7 @@ async function resolveGitHub(owner, repo, sha, sinceSha, orgId) {
637
792
  }
638
793
  }
639
794
  }
640
- const r2 = await fetchWithTimeout(`https://api.github.com/repos/${owner}/${repo}/commits/${sha}`, { headers }, SCM_FETCH_TIMEOUT_MS);
795
+ const r2 = await fetchWithTimeout(`${base}/commits/${encodeURIComponent(sha)}`, { headers }, loadEventsConfig().scmFetchTimeoutMs);
641
796
  if (rateLimited(r2)) {
642
797
  scmCooldownUntil = Date.now() + SCM_COOLDOWN_MS;
643
798
  return {};
@@ -650,9 +805,9 @@ async function resolveGitHub(owner, repo, sha, sinceSha, orgId) {
650
805
  return {};
651
806
  }
652
807
  async function resolveBitbucket(owner, repo, sha) {
653
- 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)}`, {
654
809
  headers: { "User-Agent": "pipeline-builder-forwarder", "Accept": "application/json" }
655
- }, SCM_FETCH_TIMEOUT_MS);
810
+ }, loadEventsConfig().scmFetchTimeoutMs);
656
811
  if (r.status === 429) {
657
812
  scmCooldownUntil = Date.now() + SCM_COOLDOWN_MS;
658
813
  return {};
@@ -696,11 +851,11 @@ function markDeployed(pipelineId, sha) {
696
851
  noRecordedDeploy.delete(pipelineId);
697
852
  }
698
853
  async function fetchLastDeployedSha(pipelineId) {
699
- const baseUrl = process.env.PLATFORM_BASE_URL;
700
- if (!baseUrl || noRecordedDeploy.has(pipelineId)) return void 0;
854
+ const baseUrl2 = loadEventsConfig().platformBaseUrl;
855
+ if (!baseUrl2 || noRecordedDeploy.has(pipelineId)) return void 0;
701
856
  try {
702
857
  const res = await fetchWithTimeout(
703
- `${baseUrl}/api/reports/events/last-deploy-commit?pipelineId=${encodeURIComponent(pipelineId)}`,
858
+ `${baseUrl2}/api/reports/events/last-deploy-commit?pipelineId=${encodeURIComponent(pipelineId)}`,
704
859
  { headers: { Authorization: `Bearer ${await getAuthToken()}`, Accept: "application/json" } }
705
860
  );
706
861
  if (!res.ok) {
@@ -743,8 +898,6 @@ var DEPLOYS_TAG = "pb.deploys";
743
898
  var ORG_ID_TAG = "OrgId";
744
899
  var clientsByRegion = /* @__PURE__ */ new Map();
745
900
  var resolvedByArn = new BoundedMap(CACHE_MAX_ENTRIES);
746
- var NEG_CACHE_TTL_MS = 5 * 60 * 1e3;
747
- var POS_CACHE_TTL_MS = 15 * 60 * 1e3;
748
901
  var MAX_ATTR = 255;
749
902
  function parseDeploys(value) {
750
903
  const map = /* @__PURE__ */ new Map();
@@ -769,7 +922,8 @@ async function pipelineClient(region) {
769
922
  }
770
923
  async function resolvePipeline(arn, region) {
771
924
  const cached = resolvedByArn.get(arn);
772
- if (cached && Date.now() - cached.ts < (cached.pipelineId !== null ? POS_CACHE_TTL_MS : NEG_CACHE_TTL_MS)) {
925
+ const { tagCacheTtlMs, tagMissCacheTtlMs } = loadEventsConfig();
926
+ if (cached && Date.now() - cached.ts < (cached.pipelineId !== null ? tagCacheTtlMs : tagMissCacheTtlMs)) {
773
927
  return { pipelineId: cached.pipelineId, orgId: cached.orgId, deploys: cached.deploys };
774
928
  }
775
929
  try {
@@ -788,17 +942,19 @@ async function resolvePipeline(arn, region) {
788
942
  log.error("AccessDenied calling codepipeline:ListTagsForResource \u2014 grant it to the Lambda role", { pipeline: arnRef(arn), error: name });
789
943
  throw err;
790
944
  }
791
- const e = err;
792
- const status = e.$metadata?.httpStatusCode;
793
- const retryable = e.$retryable != null || typeof status === "number" && status >= 500 || /throttl|timeout|toomanyrequests|serviceunavailable|econnreset|networkingerror/i.test(name ?? "");
794
- if (retryable) {
795
- 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) });
796
947
  throw err;
797
948
  }
798
949
  log.error("Failed to resolve pb.pipeline-id tag", { pipeline: arnRef(arn), error: name ?? String(err) });
799
950
  return { pipelineId: null, orgId: null, deploys: /* @__PURE__ */ new Map() };
800
951
  }
801
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
+ }
802
958
  function _resetTagsForTests() {
803
959
  resolvedByArn.clear();
804
960
  }
@@ -922,7 +1078,7 @@ async function parseRecord(record) {
922
1078
  const environment = stageName ? deploys.get(stageName) : void 0;
923
1079
  let commitTimestamp;
924
1080
  let commitCount;
925
- if (commitSha && process.env.DORA_ENABLED === "true") {
1081
+ if (commitSha && loadEventsConfig().doraEnabled) {
926
1082
  const src = classifySource(revisionUrl);
927
1083
  const successfulDeploy = eventType === "STAGE" && !!environment && DEPLOY_SUCCEEDED_STATES.has(state);
928
1084
  const info = await resolveCommitInfo(pipelineId, orgId, event.region, { sha: commitSha, ...src }, { successfulDeploy });
@@ -933,6 +1089,7 @@ async function parseRecord(record) {
933
1089
  orgId,
934
1090
  pipelineId,
935
1091
  ...event.region && { region: event.region },
1092
+ pipelineName,
936
1093
  eventSource,
937
1094
  eventType,
938
1095
  status: state,
@@ -958,8 +1115,8 @@ async function parseRecord(record) {
958
1115
 
959
1116
  // src/index.ts
960
1117
  var handler = async (event, context) => {
961
- const baseUrl = process.env.PLATFORM_BASE_URL;
962
- if (!baseUrl) throw new Error("PLATFORM_BASE_URL environment variable is required");
1118
+ const baseUrl2 = loadEventsConfig().platformBaseUrl;
1119
+ if (!baseUrl2) throw new Error("PLATFORM_BASE_URL environment variable is required");
963
1120
  const requestId = context?.awsRequestId || randomUUID();
964
1121
  const settled = await Promise.all(event.Records.map(async (record) => {
965
1122
  try {
@@ -982,7 +1139,7 @@ var handler = async (event, context) => {
982
1139
  const carried = resolved.filter((r) => r.parsed !== null);
983
1140
  const send = async (batch) => {
984
1141
  const body = JSON.stringify({ events: batch.map(({ orgId: _orgId, ...rest }) => rest) });
985
- const post = (token) => fetchWithTimeout(`${baseUrl}/api/reports/events`, {
1142
+ const post = (token) => fetchWithTimeout(`${baseUrl2}/api/reports/events`, {
986
1143
  method: "POST",
987
1144
  headers: { "Content-Type": "application/json", "Authorization": `Bearer ${token}`, ...correlationHeaders({ requestId }) },
988
1145
  body
@@ -1044,7 +1201,7 @@ var handler = async (event, context) => {
1044
1201
  log.info(`Ingested ${events.length} events`, { inserted: result.data });
1045
1202
  }
1046
1203
  recordForwarded(delivered);
1047
- await reportHealthAndRedrive(baseUrl, event.Records[0]?.eventSourceARN, requestId);
1204
+ await reportHealthAndRedrive(baseUrl2, event.Records[0]?.eventSourceARN, requestId);
1048
1205
  return batchResponse(failures);
1049
1206
  };
1050
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;