@preventive/triage 1.0.0-alpha.56 → 1.0.0-alpha.58

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.
@@ -9,6 +9,10 @@ import { githubBundleFilename } from './bundle-build.ts'
9
9
  import { bundleBuildDiagnostic } from './bundle-build-diagnostics.js'
10
10
  import { MAX_STASIS_CONFIG_BYTES, STASIS_CONFIG, namesLockfiles, parseStasisConfig } from './stasis-config.ts'
11
11
 
12
+ // A bundle's JSON, before compression, at most: a project producing it is
13
+ // what a build's heap is sized for (bundle-build.ts buildHeapLimitMib).
14
+ export const MAX_SERIALIZED_BYTES = 512 * 1024 * 1024
15
+
12
16
  const regularFile = entry => entry.type === 'blob' && ['100644', '100755'].includes(entry.mode)
13
17
  const parentOf = path => posix.dirname(path).replace(/^\.$/u, '')
14
18
 
@@ -141,8 +145,14 @@ export async function buildStasisBundle({ input, github, token, maxBytes, scopes
141
145
  // narrower team grant: the storage location must cover the actual bundle.
142
146
  if (!allowed(directory)) throw new Error('build-scope')
143
147
  progress('serialize')
144
- const serialized = bundle.serialize()
145
- if (Buffer.byteLength(serialized) > 200 * 1024 * 1024) throw new Error('too-large')
148
+ // V8 holds no string much past MAX_SERIALIZED_BYTES (2^29 - 24 characters):
149
+ // a bundle that would be longer can't be serialized, and is too large too.
150
+ let serialized
151
+ try { serialized = bundle.serialize() } catch (error) {
152
+ if (error instanceof RangeError) throw new Error('too-large', { cause: error })
153
+ throw error
154
+ }
155
+ if (Buffer.byteLength(serialized) > MAX_SERIALIZED_BYTES) throw new Error('too-large')
146
156
  progress('compress')
147
157
  const bytes = brotliCompressSync(serialized, brotliOptions())
148
158
  if (bytes.length > maxBytes) throw new Error('too-large')
@@ -1,5 +1,6 @@
1
1
  import { Buffer } from 'node:buffer'
2
2
  import { createHash, randomUUID } from 'node:crypto'
3
+ import { totalmem } from 'node:os'
3
4
  import { posix } from 'node:path'
4
5
  import { Worker } from 'node:worker_threads'
5
6
  import { BUNDLE_BUILD_TIMEOUT_MS, type BundleBuildLeaseStore } from './bundle-build-leases.ts'
@@ -111,8 +112,25 @@ export interface BuildRequest {
111
112
  // none, as on Vercel. Resolved here: the worker's env holds NPM_TOKEN alone.
112
113
  cacheDir: string | null
113
114
  }
114
- // An extra per-process ceiling; admission must also hold the shared DB lease.
115
+ // An extra per-process ceiling, one build at a time, its worker given the heap
116
+ // buildHeapLimitMib sizes; admission must also hold the shared DB lease.
115
117
  const active = new Set<string>()
118
+ const MAX_ACTIVE_BUILDS = 1
119
+
120
+ // What a build's worker may take of the JS heap, in MiB: what a project
121
+ // producing the largest bundle a build serializes (512 MiB of JSON, the
122
+ // worker's MAX_SERIALIZED_BYTES) takes to build, its tree laid out, scanned,
123
+ // held and serialized in memory, about 1.3 GiB as measured, with room to
124
+ // spare; less only where the memory the process may use, its container's
125
+ // limit else the machine's, leaves less once the server keeps
126
+ // SERVER_RESERVE_MIB, down to the 512 MiB a build always had. Past it, Node
127
+ // terminates the worker (build-memory), not the process.
128
+ const BUILD_HEAP_MIB = 2048
129
+ const SERVER_RESERVE_MIB = 512
130
+ const MIN_BUILD_HEAP_MIB = 512
131
+ export function buildHeapLimitMib(memory = Math.min(process.constrainedMemory() || Infinity, totalmem())): number {
132
+ return Math.min(BUILD_HEAP_MIB, Math.max(MIN_BUILD_HEAP_MIB, Math.floor(memory / 1024 ** 2) - SERVER_RESERVE_MIB))
133
+ }
116
134
 
117
135
  export async function withBundleBuildLease<T>(db: BundleBuildLeaseStore, userId: string, signal: AbortSignal,
118
136
  work: (signal: AbortSignal) => Promise<T>): Promise<T> {
@@ -145,15 +163,16 @@ export async function withBundleBuildLease<T>(db: BundleBuildLeaseStore, userId:
145
163
  // Cap concurrent builds, terminate disconnected/timed-out work, and share no
146
164
  // credentials or mutable Stasis state between requests.
147
165
  export async function buildRepositoryBundle(userId: string, request: BuildRequest, signal: AbortSignal): Promise<BuiltBundle> {
148
- if (active.has(userId) || active.size >= 2) throw new BundleBuildError(429, 'build-busy')
166
+ if (active.has(userId) || active.size >= MAX_ACTIVE_BUILDS) throw new BundleBuildError(429, 'build-busy')
149
167
  signal.throwIfAborted()
150
168
  active.add(userId)
151
169
  let worker: Worker | undefined
152
170
  let workerUrl: URL | undefined
153
171
  let stage: BundleBuildStage = 'worker-start'
154
172
  const buildId = randomUUID(), started = performance.now()
173
+ const heapLimitMib = buildHeapLimitMib()
155
174
  const context = { buildId, repoId: request.input.repoId, github: request.github, commit: request.input.commit,
156
- directory: request.input.directory, entryCount: request.input.entries.length, node: process.version }
175
+ directory: request.input.directory, entryCount: request.input.entries.length, node: process.version, heapLimitMib }
157
176
  const log = (event: string, details: Record<string, unknown> = {}) => {
158
177
  const write = event === 'failed' ? console.error : console.info
159
178
  write('managed-bundle-build:', JSON.stringify({ ...context, workerUrl: workerUrl?.href, event, stage, elapsedMs: Math.round(performance.now() - started), ...details }))
@@ -166,7 +185,7 @@ export async function buildRepositoryBundle(userId: string, request: BuildReques
166
185
  const npmToken = process.env['NPM_TOKEN']
167
186
  const env = npmToken ? { NPM_TOKEN: npmToken } : {}
168
187
  worker = new Worker(workerUrl, {
169
- workerData: { ...request, type: 'managed-bundle-build' }, env, execArgv: [], resourceLimits: { maxOldGenerationSizeMb: 512 },
188
+ workerData: { ...request, type: 'managed-bundle-build' }, env, execArgv: [], resourceLimits: { maxOldGenerationSizeMb: heapLimitMib },
170
189
  })
171
190
  const running = worker
172
191
  return await new Promise((resolve, reject) => {
@@ -194,7 +213,11 @@ export async function buildRepositoryBundle(userId: string, request: BuildReques
194
213
  const { bytes } = message
195
214
  resolve({ bytes: Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength), directory: message.directory, filename: message.filename })
196
215
  })
197
- running.once('error', error => fail(422, 'build-failed', { diagnostic: bundleBuildDiagnostic(error, request.token) }))
216
+ // Past its heap (heapLimitMib), Node terminates the worker with ERR_WORKER_OUT_OF_MEMORY.
217
+ running.once('error', error => {
218
+ const outOfMemory = (error as { code?: unknown }).code === 'ERR_WORKER_OUT_OF_MEMORY'
219
+ fail(outOfMemory ? 413 : 422, outOfMemory ? 'build-memory' : 'build-failed', { diagnostic: bundleBuildDiagnostic(error, request.token) })
220
+ })
198
221
  running.once('exit', exitCode => fail(422, 'build-failed', { exitCode }))
199
222
  if (signal.aborted) abort()
200
223
  })
File without changes