Skip to content

Commit 094262e

Browse files
authored
feat: add namespace metadata labels with pr info (#172)
* add namespace metadata labels * fix namespace label sanitization
1 parent 6a14f5d commit 094262e

3 files changed

Lines changed: 300 additions & 2 deletions

File tree

Lines changed: 222 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,222 @@
1+
/**
2+
* Copyright 2026 Contributors
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
var mockReadNamespace: jest.Mock;
18+
var mockCreateNamespace: jest.Mock;
19+
var mockPatchNamespace: jest.Mock;
20+
var mockGetAllConfigs: jest.Mock;
21+
22+
jest.mock('@kubernetes/client-node', () => {
23+
const actual = jest.requireActual('@kubernetes/client-node');
24+
25+
mockReadNamespace = jest.fn();
26+
mockCreateNamespace = jest.fn();
27+
mockPatchNamespace = jest.fn();
28+
29+
const coreClient = {
30+
readNamespace: mockReadNamespace,
31+
createNamespace: mockCreateNamespace,
32+
patchNamespace: mockPatchNamespace,
33+
};
34+
35+
return {
36+
...actual,
37+
KubeConfig: jest.fn().mockImplementation(() => ({
38+
loadFromDefault: jest.fn(),
39+
makeApiClient: jest.fn().mockImplementation((client: unknown) => {
40+
if (client === actual.CoreV1Api) {
41+
return coreClient;
42+
}
43+
44+
return {};
45+
}),
46+
})),
47+
};
48+
});
49+
50+
jest.mock('server/services/globalConfig', () => {
51+
mockGetAllConfigs = jest.fn();
52+
53+
return {
54+
__esModule: true,
55+
default: {
56+
getInstance: jest.fn(() => ({
57+
getAllConfigs: mockGetAllConfigs,
58+
})),
59+
},
60+
};
61+
});
62+
63+
jest.mock('server/lib/logger', () => ({
64+
getLogger: jest.fn(() => ({
65+
info: jest.fn(),
66+
debug: jest.fn(),
67+
warn: jest.fn(),
68+
error: jest.fn(),
69+
})),
70+
}));
71+
72+
import { createOrUpdateNamespace } from '../kubernetes';
73+
74+
describe('createOrUpdateNamespace metadata', () => {
75+
beforeEach(() => {
76+
jest.clearAllMocks();
77+
mockReadNamespace.mockReset();
78+
mockCreateNamespace.mockReset();
79+
mockPatchNamespace.mockReset();
80+
mockGetAllConfigs.mockReset();
81+
jest.useFakeTimers().setSystemTime(new Date('2026-04-16T12:00:00.000Z'));
82+
mockGetAllConfigs.mockResolvedValue({
83+
ttl_cleanup: {
84+
inactivityDays: 7,
85+
},
86+
});
87+
});
88+
89+
afterEach(() => {
90+
jest.useRealTimers();
91+
});
92+
93+
it('adds PR and repo labels when creating a namespace', async () => {
94+
mockReadNamespace.mockRejectedValueOnce({ response: { statusCode: 404 } });
95+
mockCreateNamespace.mockResolvedValue({});
96+
97+
await createOrUpdateNamespace({
98+
name: 'env-abc123',
99+
buildUUID: 'abc123',
100+
staticEnv: false,
101+
repo: 'example-org/example-repo',
102+
pullRequestNumber: 2487,
103+
author: 'example-author',
104+
});
105+
106+
expect(mockCreateNamespace).toHaveBeenCalledWith(
107+
expect.objectContaining({
108+
metadata: expect.objectContaining({
109+
name: 'env-abc123',
110+
labels: expect.objectContaining({
111+
'lfc/uuid': 'abc123',
112+
'lfc/type': 'ephemeral',
113+
'lfc/org': 'example-org',
114+
'lfc/repo': 'example-repo',
115+
'lfc/pull-request': '2487',
116+
'lfc/author': 'example-author',
117+
}),
118+
}),
119+
})
120+
);
121+
});
122+
123+
it('patches PR and repo labels onto an existing namespace', async () => {
124+
mockReadNamespace
125+
.mockResolvedValueOnce({ body: { metadata: { name: 'env-abc123', labels: {} } } })
126+
.mockResolvedValueOnce({ body: { metadata: { name: 'env-abc123', labels: {} } } });
127+
mockPatchNamespace.mockResolvedValue({});
128+
129+
await createOrUpdateNamespace({
130+
name: 'env-abc123',
131+
buildUUID: 'abc123',
132+
staticEnv: false,
133+
repo: 'example-org/example-repo',
134+
pullRequestNumber: 2487,
135+
author: 'example-author',
136+
});
137+
138+
expect(mockPatchNamespace).toHaveBeenCalledWith(
139+
'env-abc123',
140+
expect.arrayContaining([
141+
{
142+
op: 'add',
143+
path: '/metadata/labels/lfc~1org',
144+
value: 'example-org',
145+
},
146+
{
147+
op: 'add',
148+
path: '/metadata/labels/lfc~1repo',
149+
value: 'example-repo',
150+
},
151+
{
152+
op: 'add',
153+
path: '/metadata/labels/lfc~1pull-request',
154+
value: '2487',
155+
},
156+
{
157+
op: 'add',
158+
path: '/metadata/labels/lfc~1author',
159+
value: 'example-author',
160+
},
161+
]),
162+
undefined,
163+
undefined,
164+
undefined,
165+
undefined,
166+
undefined,
167+
{
168+
headers: { 'Content-Type': 'application/json-patch+json' },
169+
}
170+
);
171+
});
172+
173+
it('sanitizes bot authors before writing lfc/author', async () => {
174+
mockReadNamespace.mockRejectedValueOnce({ response: { statusCode: 404 } });
175+
mockCreateNamespace.mockResolvedValue({});
176+
177+
await createOrUpdateNamespace({
178+
name: 'env-bot123',
179+
buildUUID: 'bot123',
180+
staticEnv: false,
181+
repo: 'example-org/example-repo',
182+
pullRequestNumber: 77,
183+
author: 'automation[bot]',
184+
});
185+
186+
expect(mockCreateNamespace).toHaveBeenCalledWith(
187+
expect.objectContaining({
188+
metadata: expect.objectContaining({
189+
labels: expect.objectContaining({
190+
'lfc/author': 'automation-bot',
191+
}),
192+
}),
193+
})
194+
);
195+
});
196+
197+
it('truncates long repository names to a Kubernetes-safe lfc/repo label', async () => {
198+
mockReadNamespace.mockRejectedValueOnce({ response: { statusCode: 404 } });
199+
mockCreateNamespace.mockResolvedValue({});
200+
201+
const longRepoName = 'example-repository-name-that-exceeds-the-kubernetes-label-limit-by-a-lot';
202+
203+
await createOrUpdateNamespace({
204+
name: 'env-longrepo',
205+
buildUUID: 'longrepo',
206+
staticEnv: false,
207+
repo: `example-org/${longRepoName}`,
208+
pullRequestNumber: 91,
209+
author: 'example-author',
210+
});
211+
212+
expect(mockCreateNamespace).toHaveBeenCalledWith(
213+
expect.objectContaining({
214+
metadata: expect.objectContaining({
215+
labels: expect.objectContaining({
216+
'lfc/repo': 'example-repository-name-that-exceeds-the-kubernetes-label-limit',
217+
}),
218+
}),
219+
})
220+
);
221+
});
222+
});

‎src/server/lib/kubernetes.ts‎

Lines changed: 70 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ import { staticEnvTolerations } from './helm/constants';
3333
import { parseSecretRefsFromEnv, SecretRefWithEnvKey } from './secretRefs';
3434
import { generateSecretName } from './kubernetes/externalSecret';
3535
import { buildLifecycleLabels } from 'server/lib/kubernetes/labels';
36+
import { normalizeKubernetesLabelValue } from 'server/lib/kubernetes/utils';
3637

3738
interface VOLUME {
3839
name: string;
@@ -77,6 +78,42 @@ async function getTTLConfig(_buildUUID: string): Promise<{ daysToExpire: number
7778
return { daysToExpire };
7879
}
7980

81+
type NamespaceMetadata = {
82+
labels: Record<string, string>;
83+
};
84+
85+
function buildNamespacePrMetadata({
86+
repo,
87+
pullRequestNumber,
88+
author,
89+
}: {
90+
repo?: string | null;
91+
pullRequestNumber?: number | null;
92+
author?: string | null;
93+
} = {}): NamespaceMetadata {
94+
const labels: Record<string, string> = {};
95+
96+
if (repo) {
97+
const [org, repoName] = repo.split('/');
98+
if (org) {
99+
labels['lfc/org'] = normalizeKubernetesLabelValue(org);
100+
}
101+
if (repoName) {
102+
labels['lfc/repo'] = normalizeKubernetesLabelValue(repoName);
103+
}
104+
}
105+
106+
if (pullRequestNumber != null) {
107+
labels['lfc/pull-request'] = String(pullRequestNumber);
108+
}
109+
110+
if (author) {
111+
labels['lfc/author'] = normalizeKubernetesLabelValue(author);
112+
}
113+
114+
return { labels };
115+
}
116+
80117
/**
81118
* Generates TTL-related labels for namespace creation
82119
*/
@@ -85,16 +122,24 @@ async function generateTTLLabels({
85122
staticEnv,
86123
ttl,
87124
buildUUID,
125+
repo,
126+
pullRequestNumber,
127+
author,
88128
}: {
89129
uuid: string;
90130
staticEnv: boolean;
91131
ttl: boolean;
92132
buildUUID: string;
93-
}): Promise<{ labels: Record<string, string>; logMessage: string }> {
133+
repo?: string | null;
134+
pullRequestNumber?: number | null;
135+
author?: string | null;
136+
}): Promise<NamespaceMetadata & { logMessage: string }> {
137+
const metadata = buildNamespacePrMetadata({ repo, pullRequestNumber, author });
94138
const baseLabels: Record<string, string> = {
95139
'lfc/uuid': uuid,
96140
'lfc/type': staticEnv ? 'static' : 'ephemeral',
97141
'app.kubernetes.io/managed-by': 'lifecycle',
142+
...metadata.labels,
98143
};
99144

100145
// Static or TTL disabled - only set enable flag
@@ -134,16 +179,28 @@ async function generateTTLPatch({
134179
staticEnv,
135180
ttl,
136181
buildUUID,
182+
repo,
183+
pullRequestNumber,
184+
author,
137185
}: {
138186
uuid: string;
139187
staticEnv: boolean;
140188
ttl: boolean;
141189
buildUUID: string;
190+
repo?: string | null;
191+
pullRequestNumber?: number | null;
192+
author?: string | null;
142193
}): Promise<{ patch: any[]; logMessage: string }> {
194+
const metadata = buildNamespacePrMetadata({ repo, pullRequestNumber, author });
143195
const basePatch = [
144196
{ op: 'add', path: '/metadata/labels/lfc~1uuid', value: uuid },
145197
{ op: 'add', path: '/metadata/labels/lfc~1type', value: staticEnv ? 'static' : 'ephemeral' },
146198
{ op: 'add', path: '/metadata/labels/app.kubernetes.io~1managed-by', value: 'lifecycle' },
199+
...Object.entries(metadata.labels).map(([key, value]) => ({
200+
op: 'add',
201+
path: `/metadata/labels/${key.replace(/\//g, '~1')}`,
202+
value,
203+
})),
147204
];
148205

149206
// TTL disabled - only update enable flag
@@ -206,11 +263,17 @@ export async function createOrUpdateNamespace({
206263
buildUUID,
207264
staticEnv,
208265
ttl = true,
266+
repo,
267+
pullRequestNumber,
268+
author,
209269
}: {
210270
name: string;
211271
buildUUID: string;
212272
staticEnv: boolean;
213273
ttl?: boolean;
274+
repo?: string | null;
275+
pullRequestNumber?: number | null;
276+
author?: string | null;
214277
}) {
215278
const kc = new k8s.KubeConfig();
216279
kc.loadFromDefault();
@@ -224,6 +287,9 @@ export async function createOrUpdateNamespace({
224287
staticEnv,
225288
ttl,
226289
buildUUID,
290+
repo,
291+
pullRequestNumber,
292+
author,
227293
});
228294

229295
getLogger({ namespace: name }).info(`Deploy: creating namespace ${logMessage}`);
@@ -243,6 +309,9 @@ export async function createOrUpdateNamespace({
243309
staticEnv,
244310
ttl: staticEnv ? false : ttl,
245311
buildUUID,
312+
repo,
313+
pullRequestNumber,
314+
author,
246315
});
247316

248317
await client.patchNamespace(name, patch, undefined, undefined, undefined, undefined, undefined, {

‎src/server/services/build.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1443,7 +1443,14 @@ export default class BuildService extends BaseService {
14431443
const { serviceAccount } = await GlobalConfigService.getInstance().getAllConfigs();
14441444
const serviceAccountName = serviceAccount?.name || 'default';
14451445
// create namespace and annotate the service account
1446-
await k8s.createOrUpdateNamespace({ name: build.namespace, buildUUID: build.uuid, staticEnv: build.isStatic });
1446+
await k8s.createOrUpdateNamespace({
1447+
name: build.namespace,
1448+
buildUUID: build.uuid,
1449+
staticEnv: build.isStatic,
1450+
repo: build.pullRequest?.fullName,
1451+
pullRequestNumber: build.pullRequest?.pullRequestNumber,
1452+
author: build.pullRequest?.githubLogin,
1453+
});
14471454
await k8s.createOrUpdateServiceAccount({
14481455
namespace: build.namespace,
14491456
role: serviceAccount?.role,

0 commit comments

Comments
 (0)