-
-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathciBuilds.ts
More file actions
328 lines (278 loc) · 9.56 KB
/
Copy pathciBuilds.ts
File metadata and controls
328 lines (278 loc) · 9.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
import { admin, db } from '../service/firebase';
import { logger } from 'firebase-functions/v2';
import { settings } from '../config/settings';
import { CiJobs } from './ciJobs';
import { BaseOs, ImageType } from './image';
import Timestamp = admin.firestore.Timestamp;
import FieldValue = admin.firestore.FieldValue;
export type BuildStatus = 'started' | 'failed' | 'published';
// Used in Start API
export interface BuildInfo {
baseOs: BaseOs;
repoVersion: string;
editorVersion: string;
targetPlatform: string;
}
// Used in Failure API
export interface BuildFailure {
reason: string;
}
// Used in Publish API
export interface DockerInfo {
imageRepo: string;
imageName: string;
friendlyTag: string;
specificTag: string;
digest: string;
// date with docker as source of truth?
}
interface MetaData {
lastBuildStart: Timestamp | null;
failureCount: number;
lastBuildFailure: Timestamp | null;
publishedDate: Timestamp | null;
recoveryCount?: number;
}
export interface CiBuild {
buildId: string;
relatedJobId: string;
status: BuildStatus;
imageType: ImageType;
meta: MetaData;
buildInfo: BuildInfo;
failure: BuildFailure | null;
dockerInfo: DockerInfo | null;
addedDate: Timestamp;
modifiedDate: Timestamp;
}
export type CiBuildQueueItem = { id: string; data: CiBuild };
export type CiBuildQueue = CiBuildQueueItem[];
/**
* A CI Build represents a single [baseOs-unityVersion-targetPlatform] build.
* These builds are reported in and run on GitHub Actions.
* Statuses (failures and publications) are also reported back on this level.
*/
export class CiBuilds {
public static get collection() {
return 'ciBuilds';
}
public static getAll = async (): Promise<CiBuild[]> => {
const snapshot = await db.collection(CiBuilds.collection).get();
return snapshot.docs.map((doc) => doc.data()) as CiBuild[];
};
public static getAllForRepoVersion = async (repoVersion: string): Promise<CiBuild[]> => {
const snapshot = await db
.collection(CiBuilds.collection)
.where('buildInfo.repoVersion', '==', repoVersion)
.get();
return snapshot.docs.map((doc) => doc.data()) as CiBuild[];
};
public static get = async (buildId: string): Promise<CiBuild | null> => {
const snapshot = await db.doc(`${CiBuilds.collection}/${buildId}`).get();
if (!snapshot.exists) {
return null;
}
return snapshot.data() as CiBuild;
};
public static getStartedBuilds = async (): Promise<CiBuild[]> => {
const realisticMaximumConcurrentBuilds = settings.maxConcurrentJobs * 10;
const snapshot = await db
.collection(CiBuilds.collection)
.where('status', '==', 'started')
.limit(realisticMaximumConcurrentBuilds)
.get();
return snapshot.docs.map((doc) => doc.data() as CiBuild);
};
public static getFailedBuildsQueue = async (jobId: string): Promise<CiBuildQueue> => {
const snapshot = await db
.collection(CiBuilds.collection)
.where('relatedJobId', '==', jobId)
.where('status', '==', 'failed')
.limit(settings.maxConcurrentJobs)
.get();
return snapshot.docs.map((doc) => ({
id: doc.id,
data: doc.data() as CiBuild,
}));
};
public static hasAnyBuildsForJob = async (jobId: string): Promise<boolean> => {
const snapshot = await db
.collection(CiBuilds.collection)
.where('relatedJobId', '==', jobId)
.limit(1)
.get();
return snapshot.docs.length > 0;
};
public static hasAnyStartedBuildsForJob = async (jobId: string): Promise<boolean> => {
const snapshot = await db
.collection(CiBuilds.collection)
.where('relatedJobId', '==', jobId)
.where('status', '==', 'started')
.limit(1)
.get();
return snapshot.docs.length > 0;
};
/**
* Registers a new build or handles duplicate dispatches gracefully.
* Returns the existing status if the build is already in progress or published,
* so the caller can respond appropriately without causing errors.
*/
public static registerNewBuild = async (
buildId: string,
relatedJobId: string,
imageType: ImageType,
buildInfo: BuildInfo,
): Promise<{ alreadyExists: boolean; existingStatus?: BuildStatus }> => {
const data: CiBuild = {
status: 'started',
buildId,
relatedJobId,
imageType,
buildInfo,
failure: null,
dockerInfo: null,
meta: {
lastBuildStart: Timestamp.now(),
failureCount: 0,
lastBuildFailure: null,
publishedDate: null,
},
addedDate: Timestamp.now(),
modifiedDate: Timestamp.now(),
};
const ref = await db.collection(CiBuilds.collection).doc(buildId);
const snapshot = await ref.get();
let result;
if (snapshot.exists) {
const existingStatus = snapshot.data()?.status as BuildStatus;
// Builds can be retried after a failure.
if (existingStatus === 'failed') {
// In case or reporting a new build during retry step, only overwrite these fields
result = await ref.set(data, {
mergeFields: ['status', 'meta.lastBuildStart', 'modifiedDate'],
});
} else {
// Build is already in progress or published — duplicate dispatch, not an error.
logger.info(
`Build "${buildId}" already exists with status "${existingStatus}". Ignoring duplicate dispatch.`,
);
return { alreadyExists: true, existingStatus };
}
} else {
result = await ref.create(data);
}
logger.debug('Build created', result);
return { alreadyExists: false };
};
public static async removeDryRunBuild(buildId: string) {
if (!buildId.startsWith('dryRun')) {
throw new Error('Unexpected behaviour, expected only dryRun builds to be deleted');
}
const ref = await db.collection(CiBuilds.collection).doc(buildId);
const doc = await ref.get();
logger.info('dryRun produced this build endResult', doc.data());
await ref.delete();
}
public static markBuildAsFailed = async (
buildId: string,
failure: BuildFailure,
): Promise<boolean> => {
const build = db.collection(CiBuilds.collection).doc(buildId);
const snapshot = await build.get();
// Never overwrite a published build — it was already successfully uploaded.
if (snapshot.exists && snapshot.data()?.status === 'published') {
logger.warn(`Ignoring failure report for "${buildId}" because it is already published.`);
return false;
}
await build.update({
status: 'failed',
failure,
modifiedDate: Timestamp.now(),
'meta.failureCount': FieldValue.increment(1),
'meta.lastBuildFailure': Timestamp.now(),
});
return true;
};
public static markBuildAsPublished = async (
buildId: string,
jobId: string,
dockerInfo: DockerInfo,
): Promise<boolean> => {
const build = await db.collection(CiBuilds.collection).doc(buildId);
await build.update({
status: 'published',
dockerInfo,
modifiedDate: Timestamp.now(),
'meta.publishedDate': Timestamp.now(),
});
const parentJobIsNowCompleted = await CiBuilds.haveAllBuildsForJobBeenPublished(jobId);
if (parentJobIsNowCompleted) {
await CiJobs.markJobAsCompleted(jobId);
}
return parentJobIsNowCompleted;
};
public static resetFailureCount = async (buildId: string): Promise<void> => {
const build = db.collection(CiBuilds.collection).doc(buildId);
// Use an epoch sentinel rather than null so the Ingeminator's backoff math
// (lastBuildFailure.toMillis() + backoffMs) never reads null at runtime.
await build.update({
'meta.failureCount': 0,
'meta.lastBuildFailure': Timestamp.fromMillis(0),
modifiedDate: Timestamp.now(),
});
};
public static incrementRecoveryCount = async (buildId: string): Promise<void> => {
const build = db.collection(CiBuilds.collection).doc(buildId);
await build.update({
'meta.recoveryCount': FieldValue.increment(1),
modifiedDate: Timestamp.now(),
});
};
public static getFailedBuilds = async (limit: number): Promise<CiBuild[]> => {
const snapshot = await db
.collection(CiBuilds.collection)
.where('status', '==', 'failed')
.limit(limit)
.get();
return snapshot.docs.map((doc) => doc.data() as CiBuild);
};
public static getMaxedOutFailedBuilds = async (): Promise<CiBuildQueue> => {
const snapshot = await db.collection(CiBuilds.collection).where('status', '==', 'failed').get();
return snapshot.docs
.filter((doc) => {
const data = doc.data() as CiBuild;
return (data.meta?.failureCount ?? 0) >= settings.maxFailuresPerBuild;
})
.map((doc) => ({
id: doc.id,
data: doc.data() as CiBuild,
}));
};
public static getMaxedOutFailedBuildsForRepoVersion = async (
repoVersion: string,
): Promise<CiBuildQueue> => {
const snapshot = await db
.collection(CiBuilds.collection)
.where('status', '==', 'failed')
.where('buildInfo.repoVersion', '==', repoVersion)
.get();
return snapshot.docs
.filter((doc) => {
const data = doc.data() as CiBuild;
return (data.meta?.failureCount ?? 0) >= settings.maxFailuresPerBuild;
})
.map((doc) => ({
id: doc.id,
data: doc.data() as CiBuild,
}));
};
public static haveAllBuildsForJobBeenPublished = async (jobId: string): Promise<boolean> => {
const snapshot = await db
.collection(CiBuilds.collection)
.where('relatedJobId', '==', jobId)
.where('status', '!=', 'published')
.limit(1)
.get();
return snapshot.docs.length === 0;
};
}