@preventive/triage 1.0.0-alpha.66 → 1.0.0-alpha.68
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/common/bundle-imports.js +20 -0
- package/common/bundle-metadata.js +1 -1
- package/common/bundle-reasons.d.ts +4 -0
- package/common/bundle-reasons.js +38 -1
- package/common/bundle-sources.d.ts +1 -0
- package/common/bundle-sources.js +22 -0
- package/common/managed/npm-packages.js +3 -3
- package/common/managed/routes.js +37 -18
- package/common/managed/stasis-config.ts +7 -0
- package/out/activity.js +4 -4
- package/out/{chunk-J2FWBXFV.js → chunk-2F3CYNPZ.js} +1 -1
- package/out/chunk-2HGKTQ5Q.js +52 -0
- package/out/chunk-4RS3NDOG.js +1 -0
- package/out/chunk-CGRIZ5M5.js +1 -0
- package/out/{chunk-Z6VEV2QL.js → chunk-D37M7J4B.js} +1 -1
- package/out/chunk-GZ46SSTF.js +1 -0
- package/out/{chunk-IZ6MYRYB.js → chunk-HETCVNO4.js} +1 -1
- package/out/chunk-MPXVKVPF.js +3 -0
- package/out/{chunk-24AKGEH3.js → chunk-NB4JBTKK.js} +1 -1
- package/out/{chunk-OVGR4D3M.js → chunk-OAWY4T6R.js} +1 -1
- package/out/chunk-QPGM3DTI.js +42 -0
- package/out/chunk-SCN2TBP2.js +247 -0
- package/out/chunk-VG5RH6KN.js +2 -0
- package/out/chunk-WFDXHPT2.js +12 -0
- package/out/client-managed-import.js +2 -2
- package/out/client-managed.js +19 -19
- package/out/compare.js +12 -12
- package/out/dialogs.js +38 -38
- package/out/graph.js +8 -8
- package/out/index.html +9 -9
- package/out/scan.js +2 -2
- package/out/view.css +1 -1
- package/out/view.js +15 -15
- package/package.json +11 -8
- package/server-managed/activity.ts +21 -12
- package/server-managed/bundle-build-diagnostics.d.ts +1 -1
- package/server-managed/bundle-build-worker.js +140 -19
- package/server-managed/bundle-build.ts +102 -21
- package/server-managed/bundle-cache.ts +28 -6
- package/server-managed/bundle-dependency-reviews.ts +38 -22
- package/server-managed/commit-lockfiles.ts +2 -1
- package/server-managed/db-neon.ts +5 -2
- package/server-managed/dependency-review-comments.ts +38 -16
- package/server-managed/dependency-reviews.ts +17 -14
- package/server-managed/http.ts +178 -70
- package/server-managed/locked-packages.ts +34 -14
- package/server-managed/lockfile-scope.ts +10 -1
- package/server-managed/npm-kept.ts +10 -0
- package/server-managed/npm-patch.ts +188 -53
- package/server-managed/public-workspace.ts +3 -2
- package/server-managed/pull-dependencies.ts +58 -37
- package/server-managed/pull-dependency-reviews.ts +35 -22
- package/server-managed/report-sources.ts +6 -3
- package/server-managed/repository-dependency-reviews.ts +4 -2
- package/server-managed/repository-issues.ts +14 -11
- package/server-managed/stasis-dependencies.ts +170 -0
- package/out/chunk-65PLAG3I.js +0 -12
- package/out/chunk-DCBXCBLL.js +0 -52
- package/out/chunk-F3UI65ZI.js +0 -42
- package/out/chunk-FAG6E5RC.js +0 -3
- package/out/chunk-OBZWBTZL.js +0 -247
- package/out/chunk-PTFQKLKO.js +0 -1
- package/out/chunk-QVKFY4FA.js +0 -1
- package/out/chunk-SYXT3SFP.js +0 -2
- package/out/chunk-WL3SPQB4.js +0 -1
- /package/out/{chunk-WCPJDAYA.js → chunk-D6NVKGGG.js} +0 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@preventive/triage",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.68",
|
|
4
4
|
"description": "Client & relay server for triaging of automated reports",
|
|
5
5
|
"license": "MIT OR Apache-2.0",
|
|
6
6
|
"author": {
|
|
@@ -218,6 +218,7 @@
|
|
|
218
218
|
"server-managed/sql-postgres.ts",
|
|
219
219
|
"server-managed/sql.ts",
|
|
220
220
|
"server-managed/stasis-config.ts",
|
|
221
|
+
"server-managed/stasis-dependencies.ts",
|
|
221
222
|
"server-managed/static.ts",
|
|
222
223
|
"server-managed/storage.ts",
|
|
223
224
|
"server-managed/storage-command.ts",
|
|
@@ -260,6 +261,7 @@
|
|
|
260
261
|
"common/bundle-compare-diff.d.ts",
|
|
261
262
|
"common/bundle-compare-inputs.d.ts",
|
|
262
263
|
"common/bundle-compare-inputs.js",
|
|
264
|
+
"common/bundle-imports.js",
|
|
263
265
|
"common/bundle-metadata.d.ts",
|
|
264
266
|
"common/bundle-pkg-of.d.ts",
|
|
265
267
|
"common/bundle-pkg-of.js",
|
|
@@ -312,6 +314,7 @@
|
|
|
312
314
|
"common/managed/routes.d.ts",
|
|
313
315
|
"common/managed/routes.js",
|
|
314
316
|
"common/managed/scan-models.ts",
|
|
317
|
+
"common/managed/stasis-config.ts",
|
|
315
318
|
"common/managed/team-app.js",
|
|
316
319
|
"common/managed/team-app.d.ts",
|
|
317
320
|
"common/managed/team-filters.js",
|
|
@@ -412,23 +415,23 @@
|
|
|
412
415
|
"@noble/ciphers": "^2.4.0",
|
|
413
416
|
"@preventive/terminal": "2.0.0-beta.3",
|
|
414
417
|
"@rray/frontend": "^1.0.0",
|
|
415
|
-
"@stylistic/stylelint-plugin": "^6.0.
|
|
418
|
+
"@stylistic/stylelint-plugin": "^6.0.1",
|
|
416
419
|
"@types/node": "^26.6.6",
|
|
417
420
|
"@types/ws": "^8.18.2",
|
|
418
|
-
"@vercel/functions": "^3.
|
|
421
|
+
"@vercel/functions": "^3.11.0",
|
|
419
422
|
"brotli": "^1.3.3",
|
|
420
423
|
"esbuild": "^0.28.2",
|
|
421
424
|
"lit": "^3.3.3",
|
|
422
425
|
"minify-html-literals": "^1.3.5",
|
|
423
|
-
"oxlint": "^1.
|
|
426
|
+
"oxlint": "^1.92.0",
|
|
424
427
|
"prismjs": "^1.30.0",
|
|
425
428
|
"stylelint": "^18.0.0",
|
|
426
429
|
"stylelint-config-recommended": "^19.0.0",
|
|
427
430
|
"typescript": "^7.0.2"
|
|
428
431
|
},
|
|
429
432
|
"dependencies": {
|
|
430
|
-
"@exodus/stasis": "1.0.0-rc.
|
|
431
|
-
"@exodus/stasis-core": "1.0.0-rc.
|
|
433
|
+
"@exodus/stasis": "1.0.0-rc.6",
|
|
434
|
+
"@exodus/stasis-core": "1.0.0-rc.6",
|
|
432
435
|
"@preventive/archive": "^1.4.1",
|
|
433
436
|
"@preventive/compare": "^1.2.13",
|
|
434
437
|
"@preventive/diff": "^1.1.1",
|
|
@@ -440,7 +443,7 @@
|
|
|
440
443
|
"css-tree": "^3.2.1",
|
|
441
444
|
"oxc-minify": "^0.157.0",
|
|
442
445
|
"oxc-parser": "^0.152.0",
|
|
443
|
-
"oxfmt": "^0.
|
|
446
|
+
"oxfmt": "^0.77.0",
|
|
444
447
|
"semver": "^7.8.6",
|
|
445
448
|
"ws": "^8.22.1"
|
|
446
449
|
},
|
|
@@ -460,5 +463,5 @@
|
|
|
460
463
|
"optional": true
|
|
461
464
|
}
|
|
462
465
|
},
|
|
463
|
-
"packageManager": "pnpm@12.
|
|
466
|
+
"packageManager": "pnpm@12.18.0+sha512.9d7882d5dc82147ecfc4e062aa34834e0ad0296710a1837a1115ae012127d36b7109e321ac1598a1dd0a65597681b1e99917e12ed0d749eae91187943363beb3"
|
|
464
467
|
}
|
|
@@ -26,8 +26,11 @@ export interface ActivityContext {
|
|
|
26
26
|
repo: string | null
|
|
27
27
|
}
|
|
28
28
|
|
|
29
|
+
// `actor` is the login of who acted as it is now, else the one recorded;
|
|
30
|
+
// `actorId` the user they are (null for a legacy login), and `actorName` the
|
|
31
|
+
// name they chose to show, as it is now.
|
|
29
32
|
export type ActivityEntry = {
|
|
30
|
-
id: string; kind: string; actor: string | null; action: string
|
|
33
|
+
id: string; kind: string; actor: string | null; actorId: string | null; actorName: string | null; action: string
|
|
31
34
|
repo: string | null; reportId: string | null; report: string | null
|
|
32
35
|
finding: string | null; at: number
|
|
33
36
|
}
|
|
@@ -48,7 +51,8 @@ export interface ActivityQuery {
|
|
|
48
51
|
|
|
49
52
|
export interface ActivityFilters {
|
|
50
53
|
repos: string[]
|
|
51
|
-
|
|
54
|
+
// `id` is the actor's filter key; `userId` the user, null for a legacy login.
|
|
55
|
+
users: { id: string; userId: string | null; login: string; name: string | null; detail: string | null }[]
|
|
52
56
|
}
|
|
53
57
|
|
|
54
58
|
export interface ActivityStore {
|
|
@@ -175,9 +179,10 @@ export function activityMethods(db: ManagedSql): ActivityStore {
|
|
|
175
179
|
}
|
|
176
180
|
const history = rows.map(({ total: _total, ...entry }) => entry)
|
|
177
181
|
const filters: ActivityFilters = { repos: [], users: [] }
|
|
178
|
-
|
|
182
|
+
type FacetRow = { facet: string; id: string; userId: string | null; login: string; name: string | null; detail: string | null }
|
|
183
|
+
for (const row of (await stmts.filters.all(scope)) as FacetRow[]) {
|
|
179
184
|
if (row.facet === 'repo') filters.repos.push(row.id)
|
|
180
|
-
else filters.users.push({ id: row.id, login: row.login, detail: row.detail })
|
|
185
|
+
else filters.users.push({ id: row.id, userId: row.userId, login: row.login, name: row.name, detail: row.detail })
|
|
181
186
|
}
|
|
182
187
|
return { history, total, page: currentPage, limit, filters }
|
|
183
188
|
},
|
|
@@ -186,14 +191,17 @@ export function activityMethods(db: ManagedSql): ActivityStore {
|
|
|
186
191
|
|
|
187
192
|
// Both rows and selector choices come from the authorized source. Keep legacy
|
|
188
193
|
// login-only actors separate: a historical login is not proof of user identity.
|
|
194
|
+
// A user shows by their login and name as they are now, as in the selector.
|
|
189
195
|
function activityStatements(db: ManagedSql, source: string) {
|
|
190
196
|
const activity = `WITH events AS (${source}), activity AS (
|
|
191
|
-
SELECT
|
|
197
|
+
SELECT e.id, e.kind, COALESCE(u.login, e.actor) AS actor, e.actorId, u.name AS actorName, e.action,
|
|
198
|
+
e.repo, e.reportId, e.report, e.finding, e.at, COALESCE('user:' || e.actorId, 'legacy:' || e.actor) AS actorKey
|
|
199
|
+
FROM events e LEFT JOIN managed_user u ON u.id = e.actorId
|
|
192
200
|
)`
|
|
193
|
-
const filtered = `${activity} SELECT id, kind, actor, action, repo, reportId, report, finding, at FROM activity
|
|
201
|
+
const filtered = `${activity} SELECT id, kind, actor, actorId, actorName, action, repo, reportId, report, finding, at FROM activity
|
|
194
202
|
WHERE (:kind = 'all' OR kind = :kind)
|
|
195
203
|
AND (:repo = '' OR repo = :repo) AND (:actor = '' OR actorKey = :actor)
|
|
196
|
-
AND (:query = '' OR instr(lower(coalesce(actor, '') || ' ' || action || ' ' ||
|
|
204
|
+
AND (:query = '' OR instr(lower(coalesce(actor, '') || ' ' || coalesce(actorName, '') || ' ' || action || ' ' ||
|
|
197
205
|
coalesce(repo, '') || ' ' || coalesce(report, '') || ' ' || coalesce(finding, '')), lower(:query)) > 0)`
|
|
198
206
|
// A page's rows each carry the total, so the source is read once for both;
|
|
199
207
|
// the selector choices, repositories then users, once between them.
|
|
@@ -202,13 +210,14 @@ function activityStatements(db: ManagedSql, source: string) {
|
|
|
202
210
|
rows: db.prepare(`SELECT filtered.*, count(*) OVER () AS total FROM (${filtered}) AS filtered ORDER BY at DESC,
|
|
203
211
|
CASE WHEN kind = 'triage' THEN CAST(substr(id, instr(id, ':') + 1) AS INTEGER) ELSE 0 END DESC,
|
|
204
212
|
id DESC LIMIT :limit OFFSET :offset`),
|
|
205
|
-
filters: db.prepare(`${activity} SELECT 'repo' AS facet, repo AS id,
|
|
213
|
+
filters: db.prepare(`${activity} SELECT 'repo' AS facet, repo AS id, NULL AS userId, repo AS login, NULL AS name, NULL AS detail,
|
|
214
|
+
repo AS sort, '' AS tiebreak
|
|
206
215
|
FROM (SELECT DISTINCT repo FROM activity WHERE repo IS NOT NULL AND repo <> '') AS repos
|
|
207
|
-
UNION ALL SELECT 'user' AS facet, a.actorKey AS id,
|
|
208
|
-
CASE WHEN a.actorId IS NULL THEN 'Legacy actor' ELSE NULL END AS detail, COALESCE(
|
|
209
|
-
SELECT actorKey, actorId, actor, ROW_NUMBER() OVER (PARTITION BY actorKey ORDER BY at DESC, id DESC) AS position
|
|
216
|
+
UNION ALL SELECT 'user' AS facet, a.actorKey AS id, a.actorId AS userId, COALESCE(a.actor, a.actorId) AS login, a.actorName AS name,
|
|
217
|
+
CASE WHEN a.actorId IS NULL THEN 'Legacy actor' ELSE NULL END AS detail, COALESCE(a.actor, a.actorId) AS sort, a.actorKey AS tiebreak FROM (
|
|
218
|
+
SELECT actorKey, actorId, actor, actorName, ROW_NUMBER() OVER (PARTITION BY actorKey ORDER BY at DESC, id DESC) AS position
|
|
210
219
|
FROM activity WHERE actorKey IS NOT NULL AND actorKey <> 'legacy:'
|
|
211
|
-
) a
|
|
220
|
+
) a WHERE a.position = 1
|
|
212
221
|
ORDER BY facet, sort, tiebreak`),
|
|
213
222
|
}
|
|
214
223
|
}
|
|
@@ -7,4 +7,4 @@ export interface BundleBuildDiagnostic {
|
|
|
7
7
|
cause?: BundleBuildDiagnostic
|
|
8
8
|
}
|
|
9
9
|
export function bundleBuildDiagnostic(error: unknown, token: string | null): BundleBuildDiagnostic
|
|
10
|
-
export type BundleBuildStage = 'worker-start' | 'build' | 'scope' | 'serialize' | 'compress'
|
|
10
|
+
export type BundleBuildStage = 'worker-start' | 'build' | 'scope' | 'serialize' | 'compress' | 'lockfile'
|
|
@@ -1,9 +1,13 @@
|
|
|
1
1
|
import { parentPort, workerData } from 'node:worker_threads'
|
|
2
2
|
import { Buffer } from 'node:buffer'
|
|
3
|
-
import {
|
|
3
|
+
import { createHash } from 'node:crypto'
|
|
4
|
+
import { mkdir, readFile, readdir, rename, rm, stat, statfs, writeFile } from 'node:fs/promises'
|
|
5
|
+
import { join, posix } from 'node:path'
|
|
4
6
|
import { brotliCompressSync } from 'node:zlib'
|
|
7
|
+
import { isEvidenceFile } from '@exodus/stasis/audit-corrections'
|
|
5
8
|
import { buildGitHubBundle, setCacheDir } from '@exodus/stasis/vfs-bundle'
|
|
6
9
|
import { brotliOptions } from '@exodus/stasis-core/brotli'
|
|
10
|
+
import { LOCK_FILE, dependencyEcosystem, integrityHex } from '@exodus/stasis-core/util'
|
|
7
11
|
import { HttpError, createClient } from '@preventive/upstream/github.js'
|
|
8
12
|
import { githubBundleFilename } from './bundle-build.ts'
|
|
9
13
|
import { bundleBuildDiagnostic } from './bundle-build-diagnostics.js'
|
|
@@ -104,11 +108,10 @@ async function packageName(input, github, project, bundle, client) {
|
|
|
104
108
|
return typeof name === 'string' ? name : null
|
|
105
109
|
}
|
|
106
110
|
|
|
107
|
-
// `
|
|
108
|
-
//
|
|
109
|
-
// repo
|
|
110
|
-
|
|
111
|
-
const allowed = path => scopes.some(scope => !scope || path === scope || path.startsWith(scope + '/'))
|
|
111
|
+
// `client` as a build reads the repo with it: each directory's listing read
|
|
112
|
+
// once, and each tree it downloads of the repo noted (`download`), the whole
|
|
113
|
+
// repo's or a directory's, and its bytes.
|
|
114
|
+
function buildClientOf(client, note) {
|
|
112
115
|
// Reuse these immutable listings when Stasis discovers the lockfile root.
|
|
113
116
|
const listings = new Map()
|
|
114
117
|
const downloaded = (tree, read) => async options => {
|
|
@@ -116,15 +119,24 @@ export async function buildStasisBundle({ input, github, token, maxBytes, scopes
|
|
|
116
119
|
note('download', { tree, bytes: bytes.length })
|
|
117
120
|
return bytes
|
|
118
121
|
}
|
|
119
|
-
|
|
122
|
+
return { ...client, listRepoDir(options) {
|
|
120
123
|
const key = JSON.stringify([options.repo, options.sha, options.directory ?? ''])
|
|
121
124
|
if (!listings.has(key)) listings.set(key, client.listRepoDir(options))
|
|
122
125
|
return listings.get(key)
|
|
123
126
|
}, getRepoTarball: downloaded('repo', options => client.getRepoTarball(options)),
|
|
124
127
|
getRepoTreeTarball: downloaded('directory', options => client.getRepoTreeTarball(options)) }
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// `note` is told what the build log keeps of a build beside its stages: the
|
|
131
|
+
// directory Stasis builds from (`project`), and each tree it downloads of the
|
|
132
|
+
// repo (`download`, buildClientOf).
|
|
133
|
+
export async function buildStasisBundle({ input, github, token, maxBytes, scopes, cacheDir = null, instanceDir = null }, client = createClient({ token }), progress = () => {}, note = () => {}) {
|
|
134
|
+
const allowed = path => scopes.some(scope => !scope || path === scope || path.startsWith(scope + '/'))
|
|
135
|
+
const buildClient = buildClientOf(client, note)
|
|
125
136
|
// Upstream's disk cache keeps the npm tarballs and version documents, and
|
|
126
|
-
// the repo's tree, in `cacheDir`; without one (Vercel),
|
|
127
|
-
//
|
|
137
|
+
// the repo's tree, in `cacheDir`; without one (Vercel), what it downloads
|
|
138
|
+
// of npm is kept in `instanceDir` (cacheOf), where one is given. This fresh
|
|
139
|
+
// worker inherits no application credentials but NPM_TOKEN.
|
|
128
140
|
setCacheDir(cacheDir ?? false)
|
|
129
141
|
progress('build')
|
|
130
142
|
// Entries stasis.config.json lists are built from its directory, where
|
|
@@ -144,10 +156,12 @@ export async function buildStasisBundle({ input, github, token, maxBytes, scopes
|
|
|
144
156
|
const { packageManager, ...options } = input.options
|
|
145
157
|
const named = packageManager !== undefined && !namesLockfiles(await configText(project) ?? '{}')
|
|
146
158
|
note('project', { project, configured: configured !== null, ...(named && { packageManager }) })
|
|
159
|
+
// The branch the commit was picked by, where it was, Stasis asks first of
|
|
160
|
+
// whether the commit is the repo's own (bundle-build.ts).
|
|
147
161
|
const { bundle } = await buildGitHubBundle({
|
|
148
|
-
github, sha: input.commit, directory: project || undefined,
|
|
162
|
+
github, sha: input.commit, ...(input.branch !== undefined && { branch: input.branch }), directory: project || undefined,
|
|
149
163
|
entries: input.entries.map(entry => posix.relative(project || '.', entry)),
|
|
150
|
-
...options, ...(named && { packageManager }), client: buildClient, ...(cacheDir
|
|
164
|
+
...options, ...(named && { packageManager }), client: buildClient, ...await cacheOf(cacheDir, instanceDir),
|
|
151
165
|
})
|
|
152
166
|
const directory = bundle.repo?.directory ?? ''
|
|
153
167
|
progress('scope')
|
|
@@ -159,6 +173,8 @@ export async function buildStasisBundle({ input, github, token, maxBytes, scopes
|
|
|
159
173
|
// module too large for V8 to hold as one is too large too.
|
|
160
174
|
let serialized
|
|
161
175
|
try { serialized = bundle.serializedBytes() } catch (error) {
|
|
176
|
+
// A failure's code, as buildErrorCode reads it, not a value of the wrong type.
|
|
177
|
+
// oxlint-disable-next-line unicorn/prefer-type-error
|
|
162
178
|
if (error instanceof RangeError) throw new Error('too-large', { cause: error })
|
|
163
179
|
throw error
|
|
164
180
|
}
|
|
@@ -170,13 +186,103 @@ export async function buildStasisBundle({ input, github, token, maxBytes, scopes
|
|
|
170
186
|
return { bytes, directory, filename: githubBundleFilename(github, project, input.commit, name) }
|
|
171
187
|
}
|
|
172
188
|
|
|
189
|
+
// The npm package versions a Stasis lockfile holds code of (an evidence
|
|
190
|
+
// file, by Stasis's audit rule), each once as it was installed: with its
|
|
191
|
+
// tarball's integrity and, patched, pnpm's hash of its patch (a sha256 in
|
|
192
|
+
// hex, as pnpm's lockfile names it), where the lockfile attests them.
|
|
193
|
+
export function lockfileDependencies(lockfile) {
|
|
194
|
+
const found = new Map()
|
|
195
|
+
for (const [dir, info] of lockfile.modules) {
|
|
196
|
+
const { name, version } = info
|
|
197
|
+
if (dir === '.' || dependencyEcosystem(dir, info.ecosystem) !== 'npm' || typeof name !== 'string' || !name || typeof version !== 'string' || !version) continue
|
|
198
|
+
if (!Object.keys(info.files).some(file => isEvidenceFile(name, version, file, 'npm'))) continue
|
|
199
|
+
const patch = typeof info.patch?.integrity === 'string' ? integrityHex(info.patch.integrity) : undefined
|
|
200
|
+
const one = { name, version, ...(typeof info.integrity === 'string' && { integrity: info.integrity }), ...(patch && { patch }) }
|
|
201
|
+
found.set(`${name}\0${version}\0${one.integrity ?? ''}\0${patch ?? ''}`, one)
|
|
202
|
+
}
|
|
203
|
+
return [...found].toSorted(([a], [b]) => a < b ? -1 : 1).map(([, one]) => one)
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
// The npm tarballs and version documents a build downloads, kept as files in
|
|
207
|
+
// `dir` for the builds after it in this instance, where no cache directory
|
|
208
|
+
// is set (serverless, whose temporary directory lasts as long as its
|
|
209
|
+
// instance): a store Stasis reads and writes in place of its cache, so a
|
|
210
|
+
// bundle's build, a pull request's head and merge base, and the commits
|
|
211
|
+
// after them download each version once. As much as `budget` bytes: found
|
|
212
|
+
// past it, or with less than `spare` bytes left on its disk (Vercel's holds
|
|
213
|
+
// 500 MB), the directory is emptied, and nothing is written past it. A file
|
|
214
|
+
// is written whole or not at all, as what is read is held to its integrity,
|
|
215
|
+
// a mismatch failing the build; one a stopped build left half-written is
|
|
216
|
+
// removed.
|
|
217
|
+
const INSTANCE_KEPT = new Set(['npm/tarballs', 'npm/versions'])
|
|
218
|
+
const INSTANCE_BUDGET = 512 * 1024 * 1024
|
|
219
|
+
const INSTANCE_SPARE = 64 * 1024 * 1024
|
|
220
|
+
export async function instanceCache(dir, budget = INSTANCE_BUDGET, spare = INSTANCE_SPARE) {
|
|
221
|
+
let used = 0, written = 0
|
|
222
|
+
for (const name of await readdir(dir).catch(() => [])) {
|
|
223
|
+
if (name.endsWith('.tmp')) await rm(join(dir, name), { force: true }).catch(() => {})
|
|
224
|
+
else used += (await stat(join(dir, name)).catch(() => null))?.size ?? 0
|
|
225
|
+
}
|
|
226
|
+
const free = await statfs(dir).then(disk => disk.bavail * disk.bsize, () => Infinity)
|
|
227
|
+
if (used > budget || (used > 0 && free < spare)) {
|
|
228
|
+
await rm(dir, { recursive: true, force: true }).catch(() => {})
|
|
229
|
+
used = 0
|
|
230
|
+
}
|
|
231
|
+
await mkdir(dir, { recursive: true }).catch(() => {})
|
|
232
|
+
const pathOf = (kind, name) => join(dir, createHash('sha256').update(`${kind}\0${name}`).digest('hex'))
|
|
233
|
+
return {
|
|
234
|
+
async read(kind, name) {
|
|
235
|
+
const bytes = INSTANCE_KEPT.has(kind) ? await readFile(pathOf(kind, name)).catch(() => null) : null
|
|
236
|
+
if (bytes === null || kind === 'npm/tarballs') return bytes
|
|
237
|
+
try { return JSON.parse(bytes.toString()) } catch { return null }
|
|
238
|
+
},
|
|
239
|
+
async write(kind, name, value) {
|
|
240
|
+
if (!INSTANCE_KEPT.has(kind)) return
|
|
241
|
+
const bytes = value instanceof Uint8Array ? value : Buffer.from(JSON.stringify(value))
|
|
242
|
+
if (used + bytes.length > budget) return
|
|
243
|
+
used += bytes.length
|
|
244
|
+
const path = pathOf(kind, name), tmp = `${path}.${++written}.tmp`
|
|
245
|
+
await writeFile(tmp, bytes).then(() => rename(tmp, path)).catch(() => rm(tmp, { force: true }).catch(() => {}))
|
|
246
|
+
},
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
// Stasis's `cache` option for a build: none with a cache directory set,
|
|
251
|
+
// which it reads and writes; else the instance's own (instanceCache), where
|
|
252
|
+
// it has a directory, and nothing kept where it has none.
|
|
253
|
+
const cacheOf = async (cacheDir, instanceDir) => cacheDir === null ? { cache: instanceDir === null ? false : await instanceCache(instanceDir) } : {}
|
|
254
|
+
|
|
255
|
+
// What the stasis.config.json at `input.config` has Stasis reach at
|
|
256
|
+
// `input.commit`, for the repository's dependency review
|
|
257
|
+
// (stasis-dependencies.ts): the npm versions of the lockfile it builds in
|
|
258
|
+
// its directory, as `stasis github-bundle --lockfile-only` does, no bundle
|
|
259
|
+
// serialized; none of a commit with no file there.
|
|
260
|
+
export async function buildStasisLockfile({ input, github, token, cacheDir = null, instanceDir = null }, client = createClient({ token }), progress = () => {}, note = () => {}) {
|
|
261
|
+
const buildClient = buildClientOf(client, note)
|
|
262
|
+
setCacheDir(cacheDir ?? false)
|
|
263
|
+
progress('build')
|
|
264
|
+
const directory = parentOf(input.config)
|
|
265
|
+
const configText = configReader(input, github, buildClient)
|
|
266
|
+
if (await configText(directory) === null) return []
|
|
267
|
+
// One Stasis can't tell the entries of is config-invalid before anything is fetched.
|
|
268
|
+
await directoryConfig(configText, directory)
|
|
269
|
+
note('project', { project: directory, configured: true })
|
|
270
|
+
const { lockfile } = await buildGitHubBundle({ github, sha: input.commit, ...(input.branch !== undefined && { branch: input.branch }), directory: directory || undefined, lockfile: LOCK_FILE, client: buildClient,
|
|
271
|
+
...await cacheOf(cacheDir, instanceDir) })
|
|
272
|
+
progress('lockfile')
|
|
273
|
+
if (!lockfile) throw new Error('Stasis built no lockfile of these entries')
|
|
274
|
+
return lockfileDependencies(lockfile)
|
|
275
|
+
}
|
|
276
|
+
|
|
173
277
|
// The code a failed build answers with. Never upstream bodies or paths outside
|
|
174
278
|
// the caller's grants: those stay in the diagnostic. A missing or ambiguous
|
|
175
279
|
// lockfile, or the named one missing, is the lockfile's. Stasis refuses a
|
|
176
280
|
// stasis.config.json entry setting an option that runs a program, whatever
|
|
177
281
|
// is given (nothing of the repo runs); a bundle holding a path or package its
|
|
178
282
|
// allowedPaths, disallowedPaths, allowedModules or disallowedModules refuses,
|
|
179
|
-
//
|
|
283
|
+
// or its excludeModules excludes (an entry in such a package among them), the
|
|
284
|
+
// config's or an entry's, is the policy's, as is one broken at load by
|
|
285
|
+
// imports excludeModules excludes alone; one it can't read, build with
|
|
180
286
|
// its options, or lay out the lockfiles it names of, is the config's. A build
|
|
181
287
|
// the repository's stasis.lock.json disagrees with, or that its lock mode
|
|
182
288
|
// holds to one that isn't there, is the stasis.lock.json's. A commit Stasis
|
|
@@ -188,13 +294,23 @@ export function buildErrorCode(error, message) {
|
|
|
188
294
|
if (error instanceof HttpError) return error.status === 429 ? 'github-rate-limited' : 'github-build-failed'
|
|
189
295
|
if (/, which runs .+, and nothing of the project runs here$/u.test(message)) return 'config-runs-code'
|
|
190
296
|
if (message.endsWith(': bundle either the entries it names or others, not both')) return 'config-mixed'
|
|
191
|
-
if (/\bstasis\.config\.json(?:: entries .*?)?: (?:allowed|disallowed)(?:Paths|Modules) (?:refuses|does not allow|allows none of) /u.test(message)) return 'config-policy'
|
|
297
|
+
if (/\bstasis\.config\.json(?:: entries .*?)?: (?:(?:allowed|disallowed)(?:Paths|Modules) (?:refuses|does not allow|allows none of)|excludeModules excludes) /u.test(message)) return 'config-policy'
|
|
298
|
+
if (brokenByExclusion(message)) return 'config-policy'
|
|
192
299
|
if (/\bstasis\.config\.json(?: is not valid JSON|: |'s lockfiles )/u.test(message)) return 'config-invalid'
|
|
193
300
|
if (/\bstasis\.lock\.json(?::| isn't there,| \(lock = )/u.test(message)) return 'stasis-lock'
|
|
194
301
|
if (/ is in the history of no branch or tag of | is at no tag or branch head of .+ nor in its default branch's history/u.test(message)) return 'commit-not-own'
|
|
195
302
|
return /no packageManager given|lockfile installs|no (?:pnpm-lock\.yaml|yarn\.lock|package-lock\.json|soldeer\.lock) found in /u.test(message) ? 'build-lockfile' : 'build-failed'
|
|
196
303
|
}
|
|
197
304
|
|
|
305
|
+
// Whether Stasis finds a JS bundle broken at load by what excludeModules
|
|
306
|
+
// leaves out alone: each of what it lists (ten at most, none cut short past
|
|
307
|
+
// them) an import unresolved for that reason, which it gives first.
|
|
308
|
+
function brokenByExclusion(message) {
|
|
309
|
+
const [head, ...lines] = message.split('\n')
|
|
310
|
+
return /JS bundle would be broken at load time(?: \(.*\))?:$/u.test(head) && lines.length > 0
|
|
311
|
+
&& lines.every(line => /^ {2}unresolved .* \(excluded by excludeModules[;)]/u.test(line))
|
|
312
|
+
}
|
|
313
|
+
|
|
198
314
|
// The status a failed build answers with, by its code: 422 for any other.
|
|
199
315
|
const FAILED_STATUS = new Map([['too-large', 413], ['build-scope', 403], ['bad-conditions', 400]])
|
|
200
316
|
|
|
@@ -221,13 +337,18 @@ if (parentPort && workerData?.type === 'managed-bundle-build') {
|
|
|
221
337
|
}
|
|
222
338
|
const reporting = setInterval(() => send({ type: 'memory', memory: memoryOf() }), MEMORY_EVERY_MS)
|
|
223
339
|
reporting.unref()
|
|
340
|
+
const progress = stage => send({ type: 'progress', stage, memory: memoryOf() })
|
|
341
|
+
const note = (event, details) => send({ type: 'note', event, details })
|
|
224
342
|
try {
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
343
|
+
// A lockfile's dependencies in place of a bundle, where they are asked for (`lockfileOnly`).
|
|
344
|
+
if (workerData.lockfileOnly) send({ dependencies: await buildStasisLockfile(workerData, undefined, progress, note) })
|
|
345
|
+
else {
|
|
346
|
+
const built = await buildStasisBundle(workerData, undefined, progress, note)
|
|
347
|
+
// The bytes handed over rather than copied, where they alone fill their
|
|
348
|
+
// buffer (a small one may share Node's pool, which can't be moved).
|
|
349
|
+
const { bytes } = built
|
|
350
|
+
send(built, bytes.byteOffset === 0 && bytes.byteLength === bytes.buffer.byteLength ? [bytes.buffer] : [])
|
|
351
|
+
}
|
|
231
352
|
} catch (error) {
|
|
232
353
|
const diagnostic = bundleBuildDiagnostic(error, workerData.token)
|
|
233
354
|
const code = buildErrorCode(error, diagnostic.message)
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { Buffer } from 'node:buffer'
|
|
2
2
|
import { createHash, randomUUID } from 'node:crypto'
|
|
3
|
-
import { totalmem } from 'node:os'
|
|
4
|
-
import { posix } from 'node:path'
|
|
3
|
+
import { tmpdir, totalmem } from 'node:os'
|
|
4
|
+
import { join, posix } from 'node:path'
|
|
5
5
|
import { Worker } from 'node:worker_threads'
|
|
6
6
|
import { BUNDLE_BUILD_TIMEOUT_MS, type BundleBuildLeaseStore } from './bundle-build-leases.ts'
|
|
7
7
|
import { type BundleBuildDiagnostic, type BundleBuildStage, bundleBuildDiagnostic } from './bundle-build-diagnostics.js'
|
|
@@ -23,6 +23,19 @@ interface BundleBuildInput {
|
|
|
23
23
|
// conditions, and for entries given none, which stasis.config.json must
|
|
24
24
|
// then list (the build checks: bundle-build-worker.js).
|
|
25
25
|
conditions: BundleBuildConditions | null
|
|
26
|
+
// The branch the commit was picked by, where it was: Stasis asks it first
|
|
27
|
+
// when it holds the commit to the repo's own history, which GitHub's compare
|
|
28
|
+
// tells of it, so nothing is taken on trust (one the commit isn't of is
|
|
29
|
+
// looked past). Without it, Stasis lists the repo's tags and branches and
|
|
30
|
+
// compares up to 100 of those.
|
|
31
|
+
branch?: string
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// A name git takes for a branch (git check-ref-format --branch), at most
|
|
35
|
+
// GitHub's length for one.
|
|
36
|
+
export function branchName(value: unknown): value is string {
|
|
37
|
+
return typeof value === 'string' && value.length > 0 && value.length <= 255
|
|
38
|
+
&& !/[\p{Cc}\s~^:?*[\\]|\.\.|@\{|\/\/|^-|^\/|\/$|\.$|^@$|(?:^|\/)\.|\.lock(?:\/|$)/u.test(value)
|
|
26
39
|
}
|
|
27
40
|
|
|
28
41
|
function path(value: unknown): value is string {
|
|
@@ -40,10 +53,11 @@ export function buildableEntry(value: unknown): value is string {
|
|
|
40
53
|
export function parseBundleBuild(value: unknown): BundleBuildInput {
|
|
41
54
|
const fail = (code = 'bad-request'): never => { throw new BundleBuildError(400, code) }
|
|
42
55
|
if (value == null || typeof value !== 'object' || Array.isArray(value)) return fail()
|
|
43
|
-
const { repoId, commit, entries, conditions } = value as Record<string, unknown>
|
|
56
|
+
const { repoId, commit, entries, conditions, branch } = value as Record<string, unknown>
|
|
44
57
|
if (typeof repoId !== 'number' || !Number.isSafeInteger(repoId) || repoId <= 0
|
|
45
58
|
|| typeof commit !== 'string' || !/^[a-f\d]{40}$/u.test(commit)
|
|
46
|
-
|| !Array.isArray(entries) || entries.length === 0 || entries.length > 100 || !entries.every(path)
|
|
59
|
+
|| !Array.isArray(entries) || entries.length === 0 || entries.length > 100 || !entries.every(path)
|
|
60
|
+
|| (branch != null && !branchName(branch))) return fail()
|
|
47
61
|
const selected = [...new Set(entries as string[])]
|
|
48
62
|
const scripts = selected.every(isScript)
|
|
49
63
|
if (!scripts && !selected.every(entry => entry.endsWith('.sol'))) return fail('unsupported-entries')
|
|
@@ -76,7 +90,7 @@ export function parseBundleBuild(value: unknown): BundleBuildInput {
|
|
|
76
90
|
recorded = { preset: preset as BundleBuildConditions['preset'], conditions: [...new Set(names as string[])],
|
|
77
91
|
platforms: options.platforms ?? [] }
|
|
78
92
|
}
|
|
79
|
-
return { repoId, commit, entries: selected, directory: parts.join('/'), options, conditions: recorded }
|
|
93
|
+
return { repoId, commit, entries: selected, directory: parts.join('/'), options, conditions: recorded, ...(branchName(branch) && { branch }) }
|
|
80
94
|
}
|
|
81
95
|
|
|
82
96
|
// A package name as a filename base: `@scope/name` as `scope-name`, or as
|
|
@@ -113,10 +127,33 @@ interface BuildRequest {
|
|
|
113
127
|
// VERCEL_ENV alone.
|
|
114
128
|
cacheDir: string | null
|
|
115
129
|
}
|
|
130
|
+
// A version a Stasis lockfile holds, as the worker tells it in place of a
|
|
131
|
+
// bundle (bundle-build-worker.js buildStasisLockfile); and what it is asked
|
|
132
|
+
// to build one of, with the `branch` the commit is of, where its asker knows
|
|
133
|
+
// it, as a bundle's is (BundleBuildInput).
|
|
134
|
+
export interface StasisDependency { name: string; version: string; integrity?: string; patch?: string }
|
|
135
|
+
export interface LockfileInput { repoId: number; commit: string; config: string; branch?: string }
|
|
136
|
+
interface LockfileRequest { input: LockfileInput; github: string; token: string | null; cacheDir: string | null }
|
|
116
137
|
// An extra per-process ceiling, one build at a time, its worker given the heap
|
|
117
138
|
// buildHeapLimitMib sizes; admission must also hold the shared DB lease.
|
|
118
139
|
const active = new Set<string>()
|
|
119
140
|
const MAX_ACTIVE_BUILDS = 1
|
|
141
|
+
// The build running behind no request (buildRepositoryLockfile), which one
|
|
142
|
+
// asked for takes the slot and the lease of: told to yield
|
|
143
|
+
// (`build-yielded`), and gone once its lease is released.
|
|
144
|
+
let behind: { yield: () => void; gone: Promise<void> } | null = null
|
|
145
|
+
// Who builds behind no request, as `active` and the shared lease name it.
|
|
146
|
+
const LOCKFILE_BUILDER = 'dependency-review'
|
|
147
|
+
// Where builds keep what they download of npm for those after them in this
|
|
148
|
+
// instance, where no cache directory is set, as on Vercel
|
|
149
|
+
// (bundle-build-worker.js instanceCache).
|
|
150
|
+
const INSTANCE_DIR = join(tmpdir(), 'triage-stasis-cache')
|
|
151
|
+
async function yielded(): Promise<void> {
|
|
152
|
+
const running = behind
|
|
153
|
+
if (!running) return
|
|
154
|
+
running.yield()
|
|
155
|
+
await running.gone
|
|
156
|
+
}
|
|
120
157
|
|
|
121
158
|
// What a build's worker may take of the JS heap, in MiB: the memory the
|
|
122
159
|
// process may use, its container's limit else the machine's, less
|
|
@@ -134,6 +171,9 @@ export function buildHeapLimitMib(memory = processMemory()): number {
|
|
|
134
171
|
return Math.max(MIN_BUILD_HEAP_MIB, Math.floor(memory / 1024 ** 2) - RESERVED_MIB)
|
|
135
172
|
}
|
|
136
173
|
|
|
174
|
+
// `work` under one of the deployment's leases, `userId`'s one at a time. One
|
|
175
|
+
// asked for first has this instance's build behind no request yield, and
|
|
176
|
+
// waits for its lease to be released, lest that hold a lease against it.
|
|
137
177
|
export async function withBundleBuildLease<T>(db: BundleBuildLeaseStore, userId: string, signal: AbortSignal,
|
|
138
178
|
work: (signal: AbortSignal) => Promise<T>): Promise<T> {
|
|
139
179
|
signal.throwIfAborted()
|
|
@@ -143,6 +183,7 @@ export async function withBundleBuildLease<T>(db: BundleBuildLeaseStore, userId:
|
|
|
143
183
|
const combined = AbortSignal.any([signal, timeout.signal])
|
|
144
184
|
let claimed = false
|
|
145
185
|
try {
|
|
186
|
+
if (userId !== LOCKFILE_BUILDER && behind) await yielded()
|
|
146
187
|
claimed = await db.claimBundleBuildLease(userId, owner)
|
|
147
188
|
if (!claimed) throw new BundleBuildError(429, 'build-busy')
|
|
148
189
|
// Account for a slow/lost claim response or a suspended invocation before
|
|
@@ -164,10 +205,53 @@ export async function withBundleBuildLease<T>(db: BundleBuildLeaseStore, userId:
|
|
|
164
205
|
// Parsing repositories and compressing bundles stays off the HTTP event loop.
|
|
165
206
|
// Cap concurrent builds, terminate disconnected/timed-out work, and share no
|
|
166
207
|
// credentials or mutable Stasis state between requests.
|
|
167
|
-
export
|
|
168
|
-
|
|
208
|
+
export function buildRepositoryBundle(userId: string, request: BuildRequest, signal: AbortSignal): Promise<BuiltBundle> {
|
|
209
|
+
const context = { repoId: request.input.repoId, github: request.github, commit: request.input.commit, directory: request.input.directory, entryCount: request.input.entries.length }
|
|
210
|
+
const asked = { ...request, instanceDir: INSTANCE_DIR }
|
|
211
|
+
return runBuild<BuiltBundle & { bytes: Uint8Array }, BuiltBundle>(userId, asked, context, signal, message => {
|
|
212
|
+
// A view of the bytes the worker handed over, not a copy of them.
|
|
213
|
+
const { bytes } = message
|
|
214
|
+
return { value: { bytes: Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength), directory: message.directory, filename: message.filename }, logged: { byteSize: bytes.length } }
|
|
215
|
+
})
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
// A Stasis lockfile's dependencies in place of a bundle, for a repository's
|
|
219
|
+
// dependency review (stasis-dependencies.ts), built behind no request, under
|
|
220
|
+
// the deployment's lease as its one builder of them: in the same one slot,
|
|
221
|
+
// which it gives up to a build asked for, with its lease (`build-yielded`),
|
|
222
|
+
// and is refused while another holds (`build-busy`), to be built later.
|
|
223
|
+
export async function buildRepositoryLockfile(db: BundleBuildLeaseStore, request: LockfileRequest, signal: AbortSignal): Promise<StasisDependency[]> {
|
|
224
|
+
if (behind || active.size >= MAX_ACTIVE_BUILDS) throw new BundleBuildError(429, 'build-busy')
|
|
225
|
+
const context = { repoId: request.input.repoId, github: request.github, commit: request.input.commit, config: request.input.config, branch: request.input.branch, lockfileOnly: true }
|
|
226
|
+
const asked = { ...request, instanceDir: INSTANCE_DIR, lockfileOnly: true }
|
|
227
|
+
const yielding = new AbortController()
|
|
228
|
+
let gone = () => {}
|
|
229
|
+
behind = { yield: () => yielding.abort(new BundleBuildError(429, 'build-yielded')), gone: new Promise(resolve => { gone = resolve }) }
|
|
230
|
+
try {
|
|
231
|
+
return await withBundleBuildLease(db, LOCKFILE_BUILDER, AbortSignal.any([signal, yielding.signal]), leased => runBuild<{ dependencies: StasisDependency[] }, StasisDependency[]>(
|
|
232
|
+
LOCKFILE_BUILDER, asked, context, leased, ({ dependencies }) => ({ value: dependencies, logged: { dependencies: dependencies.length } }), true))
|
|
233
|
+
} finally {
|
|
234
|
+
behind = null
|
|
235
|
+
gone()
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
// What a build's worker told last, by its type: its progress, memory or a
|
|
240
|
+
// note, its failure, else what it built.
|
|
241
|
+
type WorkerMessage<M> = M & { type?: string; stage?: BundleBuildStage; error?: string; status?: number; diagnostic?: BundleBuildDiagnostic
|
|
242
|
+
memory?: Record<string, number>; event?: string; details?: Record<string, unknown> }
|
|
243
|
+
|
|
244
|
+
// `request` built in a worker of its own, `owner`'s one build at a time, what
|
|
245
|
+
// it built told by `built` of its last message, with what its log keeps of
|
|
246
|
+
// it; `background`, behind no request.
|
|
247
|
+
async function runBuild<M, T>(owner: string, request: { token: string | null }, about: Record<string, unknown>, signal: AbortSignal,
|
|
248
|
+
built: (message: M) => { value: T; logged: Record<string, unknown> }, background = false): Promise<T> {
|
|
249
|
+
const { token } = request
|
|
250
|
+
// One asked for takes the slot of one running behind no request, where its lease didn't already.
|
|
251
|
+
if (!background && behind) await yielded()
|
|
252
|
+
if (active.has(owner) || active.size >= MAX_ACTIVE_BUILDS) throw new BundleBuildError(429, 'build-busy')
|
|
169
253
|
signal.throwIfAborted()
|
|
170
|
-
active.add(
|
|
254
|
+
active.add(owner)
|
|
171
255
|
let worker: Worker | undefined
|
|
172
256
|
let workerUrl: URL | undefined
|
|
173
257
|
let stage: BundleBuildStage = 'worker-start'
|
|
@@ -175,8 +259,7 @@ export async function buildRepositoryBundle(userId: string, request: BuildReques
|
|
|
175
259
|
const heapLimitMib = buildHeapLimitMib()
|
|
176
260
|
// How this Node was built, as it decides what a heap holds the same objects in.
|
|
177
261
|
const { v8_enable_pointer_compression: pointerCompression, v8_enable_sandbox: v8Sandbox } = process.config.variables as Record<string, unknown>
|
|
178
|
-
const context = { buildId,
|
|
179
|
-
directory: request.input.directory, entryCount: request.input.entries.length, node: process.version, v8: process.versions.v8, pointerCompression, v8Sandbox,
|
|
262
|
+
const context = { buildId, ...about, node: process.version, v8: process.versions.v8, pointerCompression, v8Sandbox,
|
|
180
263
|
memoryMib: Math.round(processMemory() / 1024 ** 2), heapLimitMib }
|
|
181
264
|
const log = (event: string, details: Record<string, unknown> = {}) => {
|
|
182
265
|
const write = event === 'failed' ? console.error : console.info
|
|
@@ -203,16 +286,15 @@ export async function buildRepositoryBundle(userId: string, request: BuildReques
|
|
|
203
286
|
if (settled) return
|
|
204
287
|
settled = true
|
|
205
288
|
cleanup()
|
|
206
|
-
log(code === 'build-cancelled' ? 'cancelled' : 'failed', { code, ...details })
|
|
289
|
+
log(code === 'build-cancelled' || code === 'build-yielded' ? 'cancelled' : 'failed', { code, ...details })
|
|
207
290
|
reject(new BundleBuildError(status, code))
|
|
208
291
|
}
|
|
209
292
|
const timer = setTimeout(() => fail(504, 'build-timeout'), BUNDLE_BUILD_TIMEOUT_MS)
|
|
210
293
|
const abort = () => signal.reason instanceof BundleBuildError ? fail(signal.reason.status, signal.reason.code) : fail(499, 'build-cancelled')
|
|
211
294
|
signal.addEventListener('abort', abort, { once: true })
|
|
212
295
|
// The worker's memory and notes are the log's alone: the response tells
|
|
213
|
-
//
|
|
214
|
-
running.on('message', (message:
|
|
215
|
-
diagnostic?: BundleBuildDiagnostic; memory?: Record<string, number>; event?: string; details?: Record<string, unknown> }) => {
|
|
296
|
+
// what it built, or the error's code, and nothing of them.
|
|
297
|
+
running.on('message', (message: WorkerMessage<M>) => {
|
|
216
298
|
if (settled) return
|
|
217
299
|
if (message.type === 'progress' && message.stage) { stage = message.stage; log('progress', { memory: message.memory }); return }
|
|
218
300
|
if (message.type === 'memory') { log('memory', { memory: message.memory }); return }
|
|
@@ -220,25 +302,24 @@ export async function buildRepositoryBundle(userId: string, request: BuildReques
|
|
|
220
302
|
if (message.error) { fail(message.status ?? 422, message.error, { diagnostic: message.diagnostic, memory: message.memory }); return }
|
|
221
303
|
settled = true
|
|
222
304
|
cleanup()
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
resolve({ bytes: Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength), directory: message.directory, filename: message.filename })
|
|
305
|
+
const { value, logged } = built(message)
|
|
306
|
+
log('completed', logged)
|
|
307
|
+
resolve(value)
|
|
227
308
|
})
|
|
228
309
|
// Past its heap (heapLimitMib), Node terminates the worker with ERR_WORKER_OUT_OF_MEMORY.
|
|
229
310
|
running.once('error', error => {
|
|
230
311
|
const outOfMemory = (error as { code?: unknown }).code === 'ERR_WORKER_OUT_OF_MEMORY'
|
|
231
|
-
fail(outOfMemory ? 413 : 422, outOfMemory ? 'build-memory' : 'build-failed', { diagnostic: bundleBuildDiagnostic(error,
|
|
312
|
+
fail(outOfMemory ? 413 : 422, outOfMemory ? 'build-memory' : 'build-failed', { diagnostic: bundleBuildDiagnostic(error, token) })
|
|
232
313
|
})
|
|
233
314
|
running.once('exit', exitCode => fail(422, 'build-failed', { exitCode }))
|
|
234
315
|
if (signal.aborted) abort()
|
|
235
316
|
})
|
|
236
317
|
} catch (error) {
|
|
237
318
|
if (!(error instanceof BundleBuildError)) {
|
|
238
|
-
log('failed', { code: 'build-failed', diagnostic: bundleBuildDiagnostic(error,
|
|
319
|
+
log('failed', { code: 'build-failed', diagnostic: bundleBuildDiagnostic(error, token) })
|
|
239
320
|
}
|
|
240
321
|
throw error
|
|
241
322
|
} finally {
|
|
242
|
-
try { await worker?.terminate() } finally { active.delete(
|
|
323
|
+
try { await worker?.terminate() } finally { active.delete(owner) }
|
|
243
324
|
}
|
|
244
325
|
}
|