Skip to content

Commit 35687d9

Browse files
committed
perf(registration-janitor): reuse clients and report discovery progress
1 parent 10ac022 commit 35687d9

5 files changed

Lines changed: 229 additions & 40 deletions

File tree

‎lambdas/functions/termination-watcher/src/github-app-client.test.ts‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,4 +158,51 @@ describe('multi-App installation clients', () => {
158158
random.mockRestore();
159159
}
160160
});
161+
it('reuses a selected App client within one invocation, while still switching exhausted Apps', async () => {
162+
mockGetCredentials.mockResolvedValue([
163+
{ appId: 1, privateKey: 'one' },
164+
{ appId: 2, privateKey: 'two' },
165+
]);
166+
mockApps.getOrgInstallation.mockResolvedValue({ data: { id: 222 } });
167+
const random = vi.spyOn(Math, 'random').mockReturnValue(0);
168+
const clients = new Map();
169+
try {
170+
const first = await createRunnerInstallationClient('test-org', 'Org', '', clients);
171+
// Unknown budgets tie; with the same selection, the client is reused.
172+
expect(await createRunnerInstallationClient('test-org', 'Org', '', clients)).toBe(first);
173+
expect(mockCreateAppAuth).toHaveBeenCalledTimes(2);
174+
mockHookAfter.mock.calls[0][1]({ headers: { 'x-ratelimit-remaining': '0' } });
175+
const second = await createRunnerInstallationClient('test-org', 'Org', '', clients);
176+
expect(await createRunnerInstallationClient('test-org', 'Org', '', clients)).toBe(second);
177+
expect(mockCreateAppAuth).toHaveBeenCalledTimes(4);
178+
expect(mockApps.getOrgInstallation).toHaveBeenCalledTimes(2);
179+
await createRunnerInstallationClient('test-org', 'Org', '', new Map());
180+
expect(mockCreateAppAuth).toHaveBeenCalledTimes(6);
181+
} finally {
182+
random.mockRestore();
183+
}
184+
});
185+
186+
it('separates cached clients by owner, runner type, and GHES endpoint', async () => {
187+
mockApps.getOrgInstallation.mockResolvedValue({ data: { id: 222 } });
188+
mockApps.getRepoInstallation.mockResolvedValue({ data: { id: 333 } });
189+
const clients = new Map();
190+
await createRunnerInstallationClient('owner', 'Org', '', clients);
191+
await createRunnerInstallationClient('other', 'Org', '', clients);
192+
await createRunnerInstallationClient('owner/repo', 'Repo', '', clients);
193+
await createRunnerInstallationClient('owner', 'Org', 'https://ghe.example/api/v3', clients);
194+
expect(clients.size).toBe(4);
195+
expect(mockCreateAppAuth).toHaveBeenCalledTimes(8);
196+
});
197+
198+
it('does not cache failed authentication', async () => {
199+
const clients = new Map();
200+
mockApps.getOrgInstallation
201+
.mockRejectedValueOnce(new Error('unavailable'))
202+
.mockResolvedValue({ data: { id: 222 } });
203+
await expect(createRunnerInstallationClient('owner', 'Org', '', clients)).rejects.toThrow('unavailable');
204+
expect(clients.size).toBe(0);
205+
await createRunnerInstallationClient('owner', 'Org', '', clients);
206+
expect(clients.size).toBe(1);
207+
});
161208
});

‎lambdas/functions/termination-watcher/src/github-app-client.ts‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -145,18 +145,29 @@ async function createInstallationClient(
145145
return createOctokitInstance(installationAuth.token, ghesApiUrl, appId);
146146
}
147147

148+
/** Kept by the caller for one invocation; never stores scan progress. */
149+
export type InstallationClientCache = Map<string, Octokit>;
150+
148151
export async function createRunnerInstallationClient(
149152
owner: string,
150153
runnerType: string,
151154
ghesApiUrl: string,
155+
clients?: InstallationClientCache,
152156
): Promise<Octokit> {
153157
const remaining = [...(await getAppCredentials())];
154158
while (remaining.length) {
155159
const credential = selectCredential(remaining);
156160
remaining.splice(remaining.indexOf(credential), 1);
161+
// Select against current quota before consulting the cache, so a reused
162+
// client never pins a batch to an exhausted or cooling-down App.
163+
const key = JSON.stringify([credential.appId, runnerType, owner, ghesApiUrl]);
164+
const cached = clients?.get(key);
165+
if (cached) return cached;
157166
try {
158167
const appClient = await createAuthenticatedClient(ghesApiUrl, credential);
159-
return await createInstallationClient(appClient, owner, runnerType, ghesApiUrl, credential);
168+
const client = await createInstallationClient(appClient, owner, runnerType, ghesApiUrl, credential);
169+
clients?.set(key, client);
170+
return client;
160171
} catch (error) {
161172
coolDown(credential.appId);
162173
if (!remaining.length) throw error;

‎lambdas/functions/termination-watcher/src/registration-janitor.test.ts‎

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,21 @@ import { beforeEach, afterEach, describe, expect, it, vi } from 'vitest';
66
import type { Context, SQSEvent } from 'aws-lambda';
77

88
import { registrationJanitor, type RegistrationJanitorConfig } from './registration-janitor';
9+
import { createRunnerInstallationClient } from './github-app-client';
10+
11+
const janitorLogs = vi.hoisted(() => ({ info: vi.fn(), setContext: vi.fn() }));
12+
vi.mock('@aws-github-runner/aws-powertools-util', async (importOriginal) => {
13+
const actual = await importOriginal<typeof import('@aws-github-runner/aws-powertools-util')>();
14+
return {
15+
...actual,
16+
setContext: janitorLogs.setContext,
17+
createChildLogger: (name: string) => {
18+
const child = actual.createChildLogger(name);
19+
if (name === 'registration-janitor') vi.spyOn(child, 'info').mockImplementation(janitorLogs.info);
20+
return child;
21+
},
22+
};
23+
});
924

1025
const github = vi.hoisted(() => ({
1126
request: vi.fn(),
@@ -432,3 +447,77 @@ describe('confirmation deadline guards', () => {
432447
},
433448
);
434449
});
450+
451+
describe('invocation reuse and discovery observability', () => {
452+
it('shares one client cache across discovery pages and resets it next invocation', async () => {
453+
github.request
454+
.mockResolvedValueOnce({
455+
data: { runners: Array.from({ length: 100 }, () => ({ ...runner, status: 'online' })) },
456+
})
457+
.mockResolvedValue({ data: { runners: [] } });
458+
await registrationJanitor({}, context);
459+
const calls = vi.mocked(createRunnerInstallationClient).mock.calls;
460+
expect(calls).toHaveLength(2);
461+
expect(calls[0][3]).toBe(calls[1][3]);
462+
await registrationJanitor({}, context);
463+
expect(calls[2][3]).not.toBe(calls[0][3]);
464+
});
465+
466+
it('shares one client cache within a confirmation batch and sets fresh invocation context', async () => {
467+
const event = await confirmationEvent();
468+
event.Records.push({ ...event.Records[0], messageId: 'second' });
469+
vi.mocked(createRunnerInstallationClient).mockClear();
470+
const batchContext = { ...context, awsRequestId: 'confirmation-request', functionName: 'janitor' } as Context;
471+
await registrationJanitor(event, batchContext);
472+
const calls = vi.mocked(createRunnerInstallationClient).mock.calls;
473+
expect(calls).toHaveLength(2);
474+
expect(calls[0][3]).toBe(calls[1][3]);
475+
expect(janitorLogs.setContext).toHaveBeenLastCalledWith(batchContext, 'registration-janitor');
476+
});
477+
478+
it('reports queued candidates and resources retained in live discovery', async () => {
479+
github.request.mockResolvedValue({ data: { runners: [runner, { ...runner, id: 11 }] } });
480+
ec2
481+
.on(DescribeInstancesCommand)
482+
.resolvesOnce({ Reservations: [] })
483+
.resolvesOnce({ Reservations: [] })
484+
.resolves({ Reservations: [{ Instances: [{ InstanceId: instanceId, State: { Name: 'stopped' } }] }] });
485+
await registrationJanitor({}, context);
486+
expect(janitorLogs.info).toHaveBeenCalledWith(
487+
'Registration discovery finished.',
488+
expect.objectContaining({
489+
pagesScanned: 1,
490+
candidatesQueued: 1,
491+
existingResources: 1,
492+
dryRunCandidates: 0,
493+
stopReason: 'completed',
494+
}),
495+
);
496+
});
497+
498+
it('reports dry-run candidates separately from queued work', async () => {
499+
configure({ dryRun: true });
500+
await registrationJanitor({}, context);
501+
expect(janitorLogs.info).toHaveBeenCalledWith(
502+
'Registration discovery finished.',
503+
expect.objectContaining({ candidatesQueued: 0, dryRunCandidates: 1, dryRun: true }),
504+
);
505+
});
506+
507+
it('reports failures without claiming failed queue sends succeeded', async () => {
508+
sqs.on(SendMessageCommand).rejects(new Error('queue unavailable'));
509+
await registrationJanitor({}, context);
510+
expect(janitorLogs.info).toHaveBeenCalledWith(
511+
'Registration discovery finished.',
512+
expect.objectContaining({ candidatesQueued: 0, candidateFailures: 1 }),
513+
);
514+
});
515+
516+
it('reports partial discovery when the deadline stops scanning', async () => {
517+
await registrationJanitor({}, { ...context, getRemainingTimeInMillis: () => 1000 });
518+
expect(janitorLogs.info).toHaveBeenCalledWith(
519+
'Registration discovery finished.',
520+
expect.objectContaining({ pagesScanned: 0, candidatesQueued: 0, stopReason: 'deadline' }),
521+
);
522+
});
523+
});

‎lambdas/functions/termination-watcher/src/registration-janitor.ts‎

Lines changed: 76 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,11 @@ import {
55
type RegistrationCleanupProviderConfig,
66
} from '@aws-github-runner/compute-providers/registration-cleanup';
77
import { SQSClient, SendMessageCommand } from '@aws-sdk/client-sqs';
8-
import { createChildLogger } from '@aws-github-runner/aws-powertools-util';
8+
import { createChildLogger, setContext } from '@aws-github-runner/aws-powertools-util';
99
import type { Context, SQSEvent, SQSBatchResponse } from 'aws-lambda';
1010
import type { Octokit } from '@octokit/rest';
1111

12-
import { createRunnerInstallationClient } from './github-app-client';
12+
import { createRunnerInstallationClient, type InstallationClientCache } from './github-app-client';
1313

1414
const logger = createChildLogger('registration-janitor');
1515
const confirmationSeconds = 900;
@@ -95,47 +95,83 @@ async function discover(
9595
config: RegistrationJanitorConfig,
9696
context: Context,
9797
provider: RegistrationCleanupProvider,
98+
clients: InstallationClientCache,
9899
): Promise<void> {
99100
let candidates = 0;
100-
for (const groupId of config.runnerGroupIds) {
101-
let failures = 0;
102-
for (let page = 1; ; page++) {
103-
if (context.getRemainingTimeInMillis() < 10000 || candidates >= config.maxCandidates) return;
104-
let runners;
105-
try {
106-
const client = await createRunnerInstallationClient(config.organization, 'Org', config.ghesApiUrl);
107-
runners = await groupPage(client, config, groupId, page);
108-
failures = 0;
109-
} catch (error) {
110-
logger.warn('Skipping unavailable discovery page', { error, groupId, page });
111-
// Isolate a broken group while still trying later pages after a transient failure.
112-
if (++failures >= 3) break;
113-
continue;
114-
}
115-
for (const runner of runners) {
116-
if (context.getRemainingTimeInMillis() < 10000 || candidates >= config.maxCandidates) return;
117-
if (runner.status !== 'offline' || runner.busy !== false) continue;
101+
const summary = {
102+
pagesScanned: 0,
103+
candidatesQueued: 0,
104+
dryRunCandidates: 0,
105+
existingResources: 0,
106+
pageFailures: 0,
107+
candidateFailures: 0,
108+
stopReason: 'completed',
109+
};
110+
const shouldStop = () => {
111+
if (context.getRemainingTimeInMillis() < 10000) {
112+
summary.stopReason = 'deadline';
113+
return true;
114+
}
115+
if (candidates >= config.maxCandidates) {
116+
summary.stopReason = 'candidate-limit';
117+
return true;
118+
}
119+
return false;
120+
};
121+
try {
122+
for (const groupId of config.runnerGroupIds) {
123+
let failures = 0;
124+
for (let page = 1; ; page++) {
125+
if (shouldStop()) return;
126+
let runners;
118127
try {
119-
const resourceId = provider.resourceIdFromRunnerName(runner.name);
120-
if (!resourceId) continue;
121-
if (await provider.exists(resourceId)) continue;
122-
const candidate: Candidate = {
123-
runnerId: runner.id,
124-
runnerName: runner.name,
125-
resourceId,
126-
groupId,
127-
observedAt: Date.now(),
128-
scope: scopeKey(config, provider),
129-
};
130-
if (config.dryRun) logger.info('Would confirm stale registration', { candidate });
131-
else await enqueue(candidate, confirmationSeconds);
132-
candidates++;
128+
const client = await createRunnerInstallationClient(config.organization, 'Org', config.ghesApiUrl, clients);
129+
runners = await groupPage(client, config, groupId, page);
130+
summary.pagesScanned++;
131+
failures = 0;
133132
} catch (error) {
134-
logger.warn('Skipping unverified candidate', { error, runnerId: runner.id });
133+
summary.pageFailures++;
134+
logger.warn('Skipping unavailable discovery page', { error, groupId, page });
135+
// Isolate a broken group while still trying later pages after a transient failure.
136+
if (++failures >= 3) break;
137+
continue;
138+
}
139+
for (const runner of runners) {
140+
if (shouldStop()) return;
141+
if (runner.status !== 'offline' || runner.busy !== false) continue;
142+
try {
143+
const resourceId = provider.resourceIdFromRunnerName(runner.name);
144+
if (!resourceId) continue;
145+
if (await provider.exists(resourceId)) {
146+
summary.existingResources++;
147+
continue;
148+
}
149+
const candidate: Candidate = {
150+
runnerId: runner.id,
151+
runnerName: runner.name,
152+
resourceId,
153+
groupId,
154+
observedAt: Date.now(),
155+
scope: scopeKey(config, provider),
156+
};
157+
if (config.dryRun) {
158+
logger.info('Would confirm stale registration', { candidate });
159+
summary.dryRunCandidates++;
160+
} else {
161+
await enqueue(candidate, confirmationSeconds);
162+
summary.candidatesQueued++;
163+
}
164+
candidates++;
165+
} catch (error) {
166+
summary.candidateFailures++;
167+
logger.warn('Skipping unverified candidate', { error, runnerId: runner.id });
168+
}
135169
}
170+
if (runners.length < 100) break;
136171
}
137-
if (runners.length < 100) break;
138172
}
173+
} finally {
174+
logger.info('Registration discovery finished.', { ...summary, dryRun: config.dryRun });
139175
}
140176
}
141177

@@ -207,14 +243,16 @@ export async function registrationJanitor(
207243
event: Partial<SQSEvent>,
208244
context: Context,
209245
): Promise<SQSBatchResponse | void> {
246+
setContext(context, 'registration-janitor');
247+
const clients: InstallationClientCache = new Map();
210248
const config = loadConfig();
211249
const provider = createRegistrationCleanupProvider(config.computeProvider, config.runnerNamePrefix);
212250
if (event.Records) {
213251
const batchItemFailures: SQSBatchResponse['batchItemFailures'] = [];
214252
for (const record of event.Records) {
215253
try {
216254
requireConfirmationTime(context);
217-
const client = await createRunnerInstallationClient(config.organization, 'Org', config.ghesApiUrl);
255+
const client = await createRunnerInstallationClient(config.organization, 'Org', config.ghesApiUrl, clients);
218256
await confirm(client, config, JSON.parse(record.body) as Candidate, context, provider);
219257
} catch (error) {
220258
logger.warn('Registration confirmation failed; leaving the runner registered', {
@@ -226,5 +264,5 @@ export async function registrationJanitor(
226264
}
227265
return { batchItemFailures };
228266
}
229-
await discover(config, context, provider);
267+
await discover(config, context, provider, clients);
230268
}

‎modules/registration-janitor/README.md‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ module "registration_janitor" {
3737

3838
Set `config.github_app_parameters.additional_apps_manifest` to the manifest's `{ name, arn }` reference and `additional_app_parameter_arns` to every ID, key, and optional installation-ID parameter ARN referenced by that manifest. The credential store uses the existing multi-App manifest format. All Apps must have the permissions and installation access required for the configured organization and runner groups. Include the corresponding KMS decryption access when using customer-managed keys.
3939

40-
Discovery selects an App for each group page; confirmation selects one for each candidate. Selection prefers the greatest observed remaining quota and skips Apps in a one-minute cooldown after throttling. Unobserved Apps begin with equal priority and use a random starting offset. App JWT and installation authentication use the same credential, with installation lookup scoped to the requested owner. Failed authentication tries another configured App. Rate-limit errors on an authenticated operation remain subject to the existing per-page or per-candidate retry behavior. With no manifest, the primary App remains the only choice.
40+
Discovery selects an App for each group page; confirmation selects one for each candidate. Within an invocation, clients are reused per App, owner, runner type, and GitHub endpoint, avoiding repeated JWT creation, installation lookup, and token minting. Selection still runs before cache lookup so quota and cooldown can move subsequent work to another App. Clients are discarded between invocations; failed authentication is not cached. Selection prefers the greatest observed remaining quota and skips Apps in a one-minute cooldown after throttling. Unobserved Apps begin with equal priority and use a random starting offset. App JWT and installation authentication use the same credential, with installation lookup scoped to the requested owner. Failed authentication tries another configured App. Rate-limit errors on an authenticated operation remain subject to the existing per-page or per-candidate retry behavior. With no manifest, the primary App remains the only choice.
4141

4242
## Confirmation and failures
4343

@@ -115,3 +115,7 @@ EC2 is the first bundled implementation, and this Terraform module configures it
115115
Use one janitor deployment per compute provider and ownership scope, with a distinct resource prefix and disjoint runner-name ownership. Multiple deployments can run concurrently for different providers without combining their IAM permissions, queues, or execution budgets. This module currently bundles EC2 only; additional providers require their implementation and Terraform configuration/permissions before deployment.
116116

117117
`compute-ec2.tf` owns the EC2 provider configuration and region-restricted inventory policy. The shared cleanup policy covers GitHub credential access and confirmation messages only. Both policies use `aws_iam_policy_document` and attach separately to the Lambda role.
118+
119+
### Discovery logs
120+
121+
Each discovery invocation emits `Registration discovery finished.` with `pagesScanned`, `candidatesQueued`, `existingResources`, `dryRunCandidates`, `pageFailures`, `candidateFailures`, and `stopReason` (`completed`, `deadline`, or `candidate-limit`). Queue counts increase only after successful sends; dry-run observations are counted separately. Summaries are also emitted for partial scans, and failure counters distinguish skipped work from successful traversal. The handler sets request context for discovery and confirmation logs on every invocation. These counters and the client cache are invocation-local, not persisted cleanup progress.

0 commit comments

Comments
 (0)