@app-vitals/agent-admin 1.79.0 → 1.81.0

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.
@@ -0,0 +1,640 @@
1
+ /**
2
+ * admin/src/github-repo-refresher.ts
3
+ * GithubRepoRefresher (GLC-1.4): the background tick that keeps the GitHub
4
+ * repo/access cache current. Registered via setInterval in admin-boot.ts
5
+ * (never inside an app factory), like the other sweepers.
6
+ *
7
+ * A target is one cache snapshot: the lookup App's repos on an org (plus the
8
+ * access pairs of the agents bound to GitHub users), or one agent App's
9
+ * installation repos on an org. Each snapshot row carries its own lease,
10
+ * rateLimitResetAt and debug columns (GLC-1.1), so "per org" here means per
11
+ * snapshot row.
12
+ *
13
+ * Every tick:
14
+ * - Is a no-op while a previous tick in this process is still running.
15
+ * - Discovers targets (cached for discoveryIntervalMs).
16
+ * - Skips targets inside their rate-limit window (rateLimitResetAt is the
17
+ * resume time) and targets with nothing to do; works the rest with missing
18
+ * work first, least recently ticked first within a rank.
19
+ * - Per target: takes the snapshot lease (first worker wins; a held lease
20
+ * means skip), then runs steps chosen by planOrgWork, re-planning after
21
+ * each step from fresh state, and releases the lease.
22
+ * - Stops starting new targets or steps once the time budget is spent, and
23
+ * hands every crawl/backfill a shouldStop that turns true at the deadline.
24
+ * - Catches every per-target failure: one org failing never blocks another.
25
+ *
26
+ * Priority within a target (planOrgWork): forced refreshes past the
27
+ * staleness cap, then missing work (never-crawled or incomplete list, access
28
+ * pairs with no answer), then expired work (TTL passed) only when nothing is
29
+ * missing. Capped work is labeled stale_cap whether or not anything is
30
+ * missing, and ranks with missing work across targets, so an expired refresh
31
+ * is never starved by a long backfill in this org or another.
32
+ */
33
+
34
+ import { randomUUID } from "node:crypto";
35
+ import { hostname } from "node:os";
36
+ import { type Clock, SystemClock } from "./clock.ts";
37
+ import {
38
+ type AccessBackfillStore,
39
+ type AccessProbe,
40
+ type BackfillUser,
41
+ backfillAccess,
42
+ buildWorkList,
43
+ } from "./github-access-backfill.ts";
44
+ import type { SnapshotKey, SnapshotProgress } from "./github-repo-cache.ts";
45
+
46
+ // ─── Config ──────────────────────────────────────────────────────────────────
47
+
48
+ export interface RefreshConfig {
49
+ /** How often a tick starts. */
50
+ intervalMs: number;
51
+ /** A completed list or ok access answer older than this is expired. */
52
+ ttlMs: number;
53
+ /** Expired data older than this is refreshed even while missing work is pending. Never below ttlMs. */
54
+ stalenessCapMs: number;
55
+ /** A tick starts no new target or step after this long. */
56
+ timeBudgetMs: number;
57
+ }
58
+
59
+ export const DEFAULT_REFRESH_INTERVAL_MS = 60_000;
60
+ export const DEFAULT_REFRESH_TTL_MS = 3_600_000;
61
+ export const DEFAULT_REFRESH_STALENESS_CAP_MS = 6 * 3_600_000;
62
+ export const DEFAULT_REFRESH_TIME_BUDGET_MS = 45_000;
63
+ /** How long discovered targets are reused before discovery runs again. */
64
+ export const DEFAULT_REFRESH_DISCOVERY_INTERVAL_MS = 10 * 60_000;
65
+
66
+ function positiveMs(raw: string | undefined, fallback: number): number {
67
+ const v = raw?.trim();
68
+ if (!v) return fallback;
69
+ const n = Number(v);
70
+ return Number.isFinite(n) && n > 0 ? n : fallback;
71
+ }
72
+
73
+ /**
74
+ * Read the refresher config. Unset, blank, non-numeric and non-positive values
75
+ * fall back to the defaults; a staleness cap below the TTL is raised to it.
76
+ */
77
+ export function resolveRefreshConfig(
78
+ env: Record<string, string | undefined>,
79
+ ): RefreshConfig {
80
+ const ttlMs = positiveMs(
81
+ env.SHIPWRIGHT_ADMIN_GITHUB_REFRESH_TTL_MS,
82
+ DEFAULT_REFRESH_TTL_MS,
83
+ );
84
+ return {
85
+ intervalMs: positiveMs(
86
+ env.SHIPWRIGHT_ADMIN_GITHUB_REFRESH_INTERVAL_MS,
87
+ DEFAULT_REFRESH_INTERVAL_MS,
88
+ ),
89
+ ttlMs,
90
+ stalenessCapMs: Math.max(
91
+ ttlMs,
92
+ positiveMs(
93
+ env.SHIPWRIGHT_ADMIN_GITHUB_REFRESH_STALENESS_CAP_MS,
94
+ DEFAULT_REFRESH_STALENESS_CAP_MS,
95
+ ),
96
+ ),
97
+ timeBudgetMs: positiveMs(
98
+ env.SHIPWRIGHT_ADMIN_GITHUB_REFRESH_TIME_BUDGET_MS,
99
+ DEFAULT_REFRESH_TIME_BUDGET_MS,
100
+ ),
101
+ };
102
+ }
103
+
104
+ // ─── Ports ───────────────────────────────────────────────────────────────────
105
+
106
+ /** The snapshot fields the refresher reads. */
107
+ export interface RefreshSnapshot {
108
+ id: string;
109
+ completedAt: Date | null;
110
+ crawlStartedAt: Date | null;
111
+ nextAttemptAt: Date | null;
112
+ rateLimitResetAt: Date | null;
113
+ lastTickAt: Date | null;
114
+ lastError: string | null;
115
+ }
116
+
117
+ /** Port: GitHubRepoCacheService satisfies it. */
118
+ export interface RefreshStore extends AccessBackfillStore {
119
+ getSnapshot(key: SnapshotKey): Promise<RefreshSnapshot | null>;
120
+ upsertSnapshot(
121
+ key: SnapshotKey,
122
+ progress?: SnapshotProgress,
123
+ ): Promise<RefreshSnapshot>;
124
+ acquireLease(
125
+ snapshotId: string,
126
+ holder: string,
127
+ ttlMs: number,
128
+ ): Promise<boolean>;
129
+ releaseLease(snapshotId: string, holder: string): Promise<void>;
130
+ listRepoFullNames(snapshotId: string): Promise<string[]>;
131
+ }
132
+
133
+ /** What a crawl or backfill step reported. */
134
+ export interface StepOutcome {
135
+ outcome: string;
136
+ rateLimitResetAt?: Date;
137
+ error?: string;
138
+ }
139
+
140
+ /** One snapshot to keep current. */
141
+ export interface RefreshTarget {
142
+ key: SnapshotKey;
143
+ /** One resumable crawl run of this snapshot's repo list. */
144
+ crawl(ctx: { shouldStop: () => boolean }): Promise<StepOutcome>;
145
+ /** Present on lookup targets with GitHub-user-bound agents. */
146
+ access?: { probe: AccessProbe; users: BackfillUser[] };
147
+ }
148
+
149
+ export interface RefreshDiscovery {
150
+ listTargets(): Promise<RefreshTarget[]>;
151
+ }
152
+
153
+ // ─── Planning ────────────────────────────────────────────────────────────────
154
+
155
+ export type RefreshReason = "missing" | "expired" | "stale_cap";
156
+
157
+ export type RefreshStep =
158
+ | { kind: "crawl"; reason: RefreshReason }
159
+ /** repos: restrict the backfill to these (stale_cap only). */
160
+ | { kind: "access"; reason: RefreshReason; repos?: string[] };
161
+
162
+ export interface AccessSummary {
163
+ /** Pairs with no answer that can be checked now. */
164
+ missing: number;
165
+ /** Ok answers older than the TTL. */
166
+ expired: number;
167
+ /** Repo names with an ok answer older than the staleness cap. */
168
+ staleRepos: string[];
169
+ }
170
+
171
+ /**
172
+ * The steps for one target, in order. A crawl still backing off
173
+ * (nextAttemptAt in the future) is not runnable, so it neither runs nor holds
174
+ * expired work back; the same holds for access pairs backing off.
175
+ */
176
+ export function planOrgWork(args: {
177
+ snapshot: RefreshSnapshot;
178
+ access?: AccessSummary;
179
+ now: Date;
180
+ ttlMs: number;
181
+ stalenessCapMs: number;
182
+ }): RefreshStep[] {
183
+ const { snapshot: s, access, now } = args;
184
+ const t = now.getTime();
185
+ const crawlRunnable = !s.nextAttemptAt || s.nextAttemptAt.getTime() <= t;
186
+ const done = s.completedAt?.getTime();
187
+ const crawlMissing = crawlRunnable && done === undefined;
188
+ const crawlExpired =
189
+ crawlRunnable && done !== undefined && done <= t - args.ttlMs;
190
+ const crawlCapped =
191
+ crawlRunnable && done !== undefined && done <= t - args.stalenessCapMs;
192
+ const accessMissing = (access?.missing ?? 0) > 0;
193
+ const anyMissing = crawlMissing || accessMissing;
194
+
195
+ // Capped work is always labeled stale_cap, with or without missing work, so
196
+ // rank() puts it ahead of other orgs' expired-only work across targets.
197
+ const steps: RefreshStep[] = [];
198
+ if (crawlCapped) steps.push({ kind: "crawl", reason: "stale_cap" });
199
+ if (access && access.staleRepos.length > 0) {
200
+ steps.push({
201
+ kind: "access",
202
+ reason: "stale_cap",
203
+ repos: access.staleRepos,
204
+ });
205
+ }
206
+ if (anyMissing) {
207
+ if (crawlMissing) steps.push({ kind: "crawl", reason: "missing" });
208
+ if (accessMissing) steps.push({ kind: "access", reason: "missing" });
209
+ } else {
210
+ if (crawlExpired && !crawlCapped) {
211
+ steps.push({ kind: "crawl", reason: "expired" });
212
+ }
213
+ if ((access?.expired ?? 0) > 0) {
214
+ steps.push({ kind: "access", reason: "expired" });
215
+ }
216
+ }
217
+ return steps;
218
+ }
219
+
220
+ // ─── Status ──────────────────────────────────────────────────────────────────
221
+
222
+ export type RefreshTargetState =
223
+ /** Nothing to do this tick. */
224
+ | "idle"
225
+ /** At least one step ran. */
226
+ | "worked"
227
+ /** Inside the rate-limit window; resumeAt says when to try again. */
228
+ | "rate_limited"
229
+ /** Another worker holds the lease. */
230
+ | "leased_elsewhere"
231
+ /** The time budget ran out before this target was started. */
232
+ | "deferred"
233
+ | "error";
234
+
235
+ export interface RefreshTargetStatus {
236
+ key: SnapshotKey;
237
+ state: RefreshTargetState;
238
+ /** Steps run this tick, as kind:reason. */
239
+ steps: string[];
240
+ /** Outcome of the last step run. */
241
+ outcome?: string;
242
+ error?: string;
243
+ resumeAt?: Date;
244
+ at: Date;
245
+ }
246
+
247
+ export interface RefreshTickResult {
248
+ skipped?: "overlap";
249
+ /** Discovery failure, if any (previously discovered targets are reused). */
250
+ error?: string;
251
+ targets: RefreshTargetStatus[];
252
+ }
253
+
254
+ export interface RefreshStatus {
255
+ running: boolean;
256
+ /** Start of the last tick that ran. */
257
+ lastTickAt: Date | null;
258
+ lastTickDurationMs: number | null;
259
+ /** Latest status per target, keyed by snapshotKeyString. */
260
+ targets: Record<string, RefreshTargetStatus>;
261
+ }
262
+
263
+ export function snapshotKeyString(key: SnapshotKey): string {
264
+ return `${key.accountId}|${key.appKind}|${key.appRef}|${key.org}`;
265
+ }
266
+
267
+ // ─── Refresher ───────────────────────────────────────────────────────────────
268
+
269
+ export interface GithubRepoRefresherDeps {
270
+ discovery: RefreshDiscovery;
271
+ store: RefreshStore;
272
+ config: RefreshConfig;
273
+ clock?: Clock;
274
+ /** Lease holder id; default host:pid:random. */
275
+ holder?: string;
276
+ discoveryIntervalMs?: number;
277
+ log?: (line: string) => void;
278
+ }
279
+
280
+ /** Access-step maxAgeMs that treats no answer as expired (missing work only). */
281
+ const NEVER_EXPIRES_MS = Number.MAX_SAFE_INTEGER;
282
+ /** Slack on top of the time budget for one in-flight request to finish. */
283
+ const LEASE_SLACK_MS = 120_000;
284
+ const MAX_STEPS_PER_TARGET = 8;
285
+
286
+ interface Planned {
287
+ target: RefreshTarget;
288
+ snapshot: RefreshSnapshot;
289
+ steps: RefreshStep[];
290
+ }
291
+
292
+ export class GithubRepoRefresher {
293
+ private readonly clock: Clock;
294
+ private readonly holder: string;
295
+ private readonly log: (line: string) => void;
296
+ private readonly discoveryIntervalMs: number;
297
+ private running = false;
298
+ private cachedTargets: RefreshTarget[] = [];
299
+ private discoveredAt: number | null = null;
300
+ private readonly state: RefreshStatus = {
301
+ running: false,
302
+ lastTickAt: null,
303
+ lastTickDurationMs: null,
304
+ targets: {},
305
+ };
306
+
307
+ constructor(private readonly deps: GithubRepoRefresherDeps) {
308
+ this.clock = deps.clock ?? SystemClock();
309
+ this.holder =
310
+ deps.holder ?? `${hostname()}:${process.pid}:${randomUUID().slice(0, 8)}`;
311
+ this.log = deps.log ?? ((line) => console.log(line));
312
+ this.discoveryIntervalMs =
313
+ deps.discoveryIntervalMs ?? DEFAULT_REFRESH_DISCOVERY_INTERVAL_MS;
314
+ }
315
+
316
+ /** Debug snapshot of the last ticks (a copy). */
317
+ status(): RefreshStatus {
318
+ return {
319
+ ...this.state,
320
+ running: this.running,
321
+ targets: { ...this.state.targets },
322
+ };
323
+ }
324
+
325
+ /** One tick. Never throws; a tick while one is running is a no-op. */
326
+ async tick(): Promise<RefreshTickResult> {
327
+ if (this.running) return { skipped: "overlap", targets: [] };
328
+ this.running = true;
329
+ const started = this.clock.now();
330
+ this.state.lastTickAt = started;
331
+ try {
332
+ return await this.run(started);
333
+ } catch (err) {
334
+ // Defensive: run() catches per target; this covers the planning reads.
335
+ const error = messageOf(err);
336
+ console.error("[github-repo-refresher] tick failed:", error);
337
+ return { error, targets: [] };
338
+ } finally {
339
+ this.state.lastTickDurationMs =
340
+ this.clock.now().getTime() - started.getTime();
341
+ this.running = false;
342
+ }
343
+ }
344
+
345
+ private async run(started: Date): Promise<RefreshTickResult> {
346
+ const { config } = this.deps;
347
+ const deadline = started.getTime() + config.timeBudgetMs;
348
+ const shouldStop = () => this.clock.now().getTime() >= deadline;
349
+ const result: RefreshTickResult = { targets: [] };
350
+
351
+ let targets: RefreshTarget[];
352
+ try {
353
+ targets = await this.discover(started);
354
+ } catch (err) {
355
+ result.error = messageOf(err);
356
+ console.error("[github-repo-refresher] discovery failed:", result.error);
357
+ targets = this.cachedTargets;
358
+ }
359
+
360
+ const planned: Planned[] = [];
361
+ for (const target of targets) {
362
+ try {
363
+ const p = await this.plan(target);
364
+ const resetAt = p.snapshot.rateLimitResetAt;
365
+ if (resetAt && resetAt.getTime() > this.clock.now().getTime()) {
366
+ this.record(result, target, {
367
+ state: "rate_limited",
368
+ resumeAt: resetAt,
369
+ });
370
+ } else if (p.steps.length === 0) {
371
+ this.record(result, target, { state: "idle" });
372
+ } else {
373
+ planned.push(p);
374
+ }
375
+ } catch (err) {
376
+ this.record(result, target, { state: "error", error: messageOf(err) });
377
+ }
378
+ }
379
+
380
+ planned.sort(
381
+ (a, b) =>
382
+ rank(a.steps) - rank(b.steps) ||
383
+ (a.snapshot.lastTickAt?.getTime() ?? 0) -
384
+ (b.snapshot.lastTickAt?.getTime() ?? 0),
385
+ );
386
+
387
+ let worked = 0;
388
+ for (const p of planned) {
389
+ if (shouldStop()) {
390
+ this.record(result, p.target, { state: "deferred" });
391
+ continue;
392
+ }
393
+ const status = await this.work(p, shouldStop);
394
+ if (status.state === "worked") worked++;
395
+ this.record(result, p.target, status);
396
+ }
397
+
398
+ if (worked > 0 || result.error) {
399
+ this.log(
400
+ `[github-repo-refresher] targets=${targets.length} worked=${worked} ms=${this.clock.now().getTime() - started.getTime()}`,
401
+ );
402
+ }
403
+ return result;
404
+ }
405
+
406
+ private async discover(now: Date): Promise<RefreshTarget[]> {
407
+ if (
408
+ this.discoveredAt !== null &&
409
+ now.getTime() - this.discoveredAt < this.discoveryIntervalMs
410
+ ) {
411
+ return this.cachedTargets;
412
+ }
413
+ const targets = await this.deps.discovery.listTargets();
414
+ this.cachedTargets = targets;
415
+ this.discoveredAt = now.getTime();
416
+ return targets;
417
+ }
418
+
419
+ /** Read fresh state for a target and plan its steps. */
420
+ private async plan(target: RefreshTarget): Promise<Planned> {
421
+ const { store, config } = this.deps;
422
+ const snapshot =
423
+ (await store.getSnapshot(target.key)) ??
424
+ (await store.upsertSnapshot(target.key));
425
+ const now = this.clock.now();
426
+ const access = target.access
427
+ ? await this.summarizeAccess(target, snapshot.id, now)
428
+ : undefined;
429
+ const steps = planOrgWork({
430
+ snapshot,
431
+ ...(access ? { access } : {}),
432
+ now,
433
+ ttlMs: config.ttlMs,
434
+ stalenessCapMs: config.stalenessCapMs,
435
+ });
436
+ return { target, snapshot, steps };
437
+ }
438
+
439
+ private async repoNames(target: RefreshTarget, snapshotId: string) {
440
+ const prefix = `${target.key.org.toLowerCase()}/`;
441
+ return (await this.deps.store.listRepoFullNames(snapshotId))
442
+ .filter((n) => n.toLowerCase().startsWith(prefix))
443
+ .map((n) => n.slice(prefix.length));
444
+ }
445
+
446
+ private async summarizeAccess(
447
+ target: RefreshTarget,
448
+ snapshotId: string,
449
+ now: Date,
450
+ ): Promise<AccessSummary> {
451
+ const { store, config } = this.deps;
452
+ const repos = await this.repoNames(target, snapshotId);
453
+ const summary: AccessSummary = { missing: 0, expired: 0, staleRepos: [] };
454
+ if (repos.length === 0) return summary;
455
+ const stale = new Set<string>();
456
+ for (const [username, configured] of mergeUsers(
457
+ target.access?.users ?? [],
458
+ )) {
459
+ const rows = await store.getAccessRows({
460
+ accountId: target.key.accountId,
461
+ org: target.key.org,
462
+ username,
463
+ repos,
464
+ });
465
+ const base = { username, repos, configuredRepos: configured, rows, now };
466
+ for (const item of buildWorkList({ ...base, maxAgeMs: config.ttlMs })
467
+ .work) {
468
+ if (item.kind === "missing") summary.missing++;
469
+ else summary.expired++;
470
+ }
471
+ for (const item of buildWorkList({
472
+ ...base,
473
+ maxAgeMs: config.stalenessCapMs,
474
+ }).work) {
475
+ if (item.kind === "expired") stale.add(item.repo);
476
+ }
477
+ }
478
+ summary.staleRepos = repos.filter((r) => stale.has(r));
479
+ return summary;
480
+ }
481
+
482
+ /** Lease, run steps (re-planning after each), release. Never throws. */
483
+ private async work(
484
+ p: Planned,
485
+ shouldStop: () => boolean,
486
+ ): Promise<Omit<RefreshTargetStatus, "key" | "at">> {
487
+ const { store, config } = this.deps;
488
+ const { target } = p;
489
+ const leaseMs = config.timeBudgetMs + LEASE_SLACK_MS;
490
+ let leased = false;
491
+ const steps: string[] = [];
492
+ let outcome: string | undefined;
493
+ try {
494
+ leased = await store.acquireLease(p.snapshot.id, this.holder, leaseMs);
495
+ if (!leased) return { state: "leased_elsewhere", steps };
496
+ const done = new Set<string>();
497
+ for (let i = 0; i < MAX_STEPS_PER_TARGET; i++) {
498
+ // Fresh state every time: another worker may have run before we took
499
+ // the lease, and each step changes what is missing.
500
+ const next = await this.plan(target);
501
+ const step = next.steps.find((s) => !done.has(stepName(s)));
502
+ if (!step || (i > 0 && shouldStop())) break;
503
+ done.add(stepName(step));
504
+ steps.push(stepName(step));
505
+ const out = await this.runStep(target, next.snapshot.id, step, {
506
+ shouldStop,
507
+ });
508
+ outcome = out.outcome;
509
+ if (out.outcome === "rate_limited") {
510
+ return {
511
+ state: "rate_limited",
512
+ steps,
513
+ outcome,
514
+ ...(out.rateLimitResetAt ? { resumeAt: out.rateLimitResetAt } : {}),
515
+ };
516
+ }
517
+ }
518
+ // No steps: another worker finished the work before we took the lease.
519
+ return {
520
+ state: steps.length > 0 ? "worked" : "idle",
521
+ steps,
522
+ ...(outcome === undefined ? {} : { outcome }),
523
+ };
524
+ } catch (err) {
525
+ return {
526
+ state: "error",
527
+ steps,
528
+ error: messageOf(err),
529
+ ...(outcome === undefined ? {} : { outcome }),
530
+ };
531
+ } finally {
532
+ if (leased) {
533
+ try {
534
+ await store.upsertSnapshot(target.key, {
535
+ lastTickAt: this.clock.now(),
536
+ });
537
+ } catch (err) {
538
+ console.error(
539
+ "[github-repo-refresher] lastTickAt write failed:",
540
+ messageOf(err),
541
+ );
542
+ }
543
+ try {
544
+ await store.releaseLease(p.snapshot.id, this.holder);
545
+ } catch (err) {
546
+ // The lease expires on its own.
547
+ console.error(
548
+ "[github-repo-refresher] lease release failed:",
549
+ messageOf(err),
550
+ );
551
+ }
552
+ }
553
+ }
554
+ }
555
+
556
+ private async runStep(
557
+ target: RefreshTarget,
558
+ snapshotId: string,
559
+ step: RefreshStep,
560
+ ctx: { shouldStop: () => boolean },
561
+ ): Promise<StepOutcome> {
562
+ if (step.kind === "crawl") return target.crawl(ctx);
563
+ const access = target.access;
564
+ if (!access) return { outcome: "complete" };
565
+ const { config, store } = this.deps;
566
+ const maxAgeMs =
567
+ step.reason === "missing"
568
+ ? NEVER_EXPIRES_MS
569
+ : step.reason === "expired"
570
+ ? config.ttlMs
571
+ : config.stalenessCapMs;
572
+ const res = await backfillAccess({
573
+ accountId: target.key.accountId,
574
+ org: target.key.org,
575
+ snapshotKey: target.key,
576
+ repos: step.repos ?? (await this.repoNames(target, snapshotId)),
577
+ users: access.users,
578
+ probe: access.probe,
579
+ store,
580
+ clock: this.clock,
581
+ maxAgeMs,
582
+ shouldStop: ctx.shouldStop,
583
+ });
584
+ return {
585
+ outcome: res.outcome,
586
+ ...(res.rateLimitResetAt
587
+ ? { rateLimitResetAt: res.rateLimitResetAt }
588
+ : {}),
589
+ };
590
+ }
591
+
592
+ private record(
593
+ result: RefreshTickResult,
594
+ target: RefreshTarget,
595
+ status: Partial<Omit<RefreshTargetStatus, "key" | "at">> & {
596
+ state: RefreshTargetState;
597
+ },
598
+ ): void {
599
+ const full: RefreshTargetStatus = {
600
+ steps: [],
601
+ ...status,
602
+ key: target.key,
603
+ at: this.clock.now(),
604
+ };
605
+ if (full.state === "error") {
606
+ console.error(
607
+ `[github-repo-refresher] target ${snapshotKeyString(target.key)} failed:`,
608
+ full.error,
609
+ );
610
+ }
611
+ result.targets.push(full);
612
+ this.state.targets[snapshotKeyString(target.key)] = full;
613
+ }
614
+ }
615
+
616
+ function stepName(s: RefreshStep): string {
617
+ return `${s.kind}:${s.reason}`;
618
+ }
619
+
620
+ /** 0: forced or missing work; 1: expired only. */
621
+ function rank(steps: RefreshStep[]): number {
622
+ return steps.some((s) => s.reason !== "expired") ? 0 : 1;
623
+ }
624
+
625
+ /** Same merge as backfillAccess: lower-cased login, configured repos unioned. */
626
+ function mergeUsers(users: BackfillUser[]): Map<string, string[]> {
627
+ const out = new Map<string, Set<string>>();
628
+ for (const u of users) {
629
+ const name = u.username.trim().toLowerCase();
630
+ if (!name) continue;
631
+ const set = out.get(name) ?? new Set<string>();
632
+ for (const r of u.configuredRepos ?? []) set.add(r);
633
+ out.set(name, set);
634
+ }
635
+ return new Map([...out].map(([k, v]) => [k, [...v]]));
636
+ }
637
+
638
+ function messageOf(err: unknown): string {
639
+ return err instanceof Error ? err.message : String(err);
640
+ }