Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

release-http-fixture.js

505 lines15.6 KB

1/** Real npm/pnpm HTTP receiver support; no expected release computation. */
2import assert from 'node:assert/strict'
3import { execFileSync, fork, spawn } from 'node:child_process'
4import {
5 accessSync,
6 constants,
7 mkdirSync,
8 readFileSync,
9 realpathSync,
10 symlinkSync,
11 writeFileSync,
12} from 'node:fs'
13import { createRequire } from 'node:module'
14import { delimiter, join } from 'node:path'
15import { fileURLToPath } from 'node:url'
16import { packageNames } from './release-history-oracle.js'
17import { manifestPath, readJson, writeJson } from './release-fixture.js'
18​
19const require = createRequire(import.meta.url)
20const changeset = require.resolve('@changesets/cli/bin.js')
21const registryScript = fileURLToPath(
22 new URL('./release-http-registry.js', import.meta.url),
24const publishScript = fileURLToPath(
25 new URL('./release-http-publish.mjs', import.meta.url),
27​
28function killGroup(child) {
29 if (child.pid === undefined) return
30 try {
31 process.kill(-child.pid, 'SIGKILL')
32 } catch (error) {
33 if (error.code !== 'ESRCH') throw error
34 }
36​
37function waitForExit(child) {
38 if (child.exitCode !== null || child.signalCode !== null)
39 return Promise.resolve()
40 return new Promise((resolve, reject) => {
41 const timer = setTimeout(
42 () => reject(new Error('Child did not exit after termination')),
43 5000,
44 )
45 child.once('exit', () => {
46 clearTimeout(timer)
47 resolve()
48 })
49 })
51​
52async function failAfterTermination(child, primary) {
53 const secondary = []
54 try {
55 killGroup(child)
56 } catch (error) {
57 secondary.push(error)
58 }
59 try {
60 await waitForExit(child)
61 } catch (error) {
62 secondary.push(error)
63 }
64 if (secondary.length > 0)
65 throw new AggregateError(
66 [primary, ...secondary],
67 'HTTP registry failure and termination failures',
68 { cause: primary },
69 )
70 throw primary
72​
73/** Own the process group, including pnpm/Changesets/npm descendants. */
74export function runReleaseToolTree(executablePath, args, options) {
75 return new Promise((resolve) => {
76 const { timeout = 30_000, ...spawnOptions } = options
77 const child = spawn(executablePath, args, {
78 ...spawnOptions,
79 detached: true,
80 stdio: ['ignore', 'pipe', 'pipe'],
81 })
82 const stdout = []
83 const stderr = []
84 const outputLimit = 16 * 1024 * 1024
85 let outputBytes = 0
86 let error
87 const cleanupErrors = []
88 let terminationRequested = false
89 const terminate = () => {
90 if (terminationRequested) return
91 terminationRequested = true
92 try {
93 killGroup(child)
94 } catch (cleanup) {
95 cleanupErrors.push(cleanup)
96 try {
97 child.kill('SIGKILL')
98 } catch (fallback) {
99 cleanupErrors.push(fallback)
100 }
101 }
102 }
103 const timer = setTimeout(() => {
104 error ??= new Error('Real release command timed out')
105 terminate()
106 }, timeout)
107 child.once('error', (cause) => {
108 error ??= cause
109 terminate()
110 })
111 child.once('exit', () => {
112 terminate()
113 })
114 for (const [stream, chunks] of [
115 [child.stdout, stdout],
116 [child.stderr, stderr],
117 ])
118 stream.on('data', (data) => {
119 const remaining = outputLimit - outputBytes
120 if (remaining > 0) {
121 const accepted = data.subarray(0, remaining)
122 chunks.push(accepted)
123 outputBytes += accepted.length
124 }
125 if (data.length > remaining) {
126 error ??= new Error('Real release output exceeds fixture bound')
127 terminate()
128 }
129 })
130 child.once('close', (status, signal) => {
131 clearTimeout(timer)
132 if (cleanupErrors.length > 0)
133 error = new AggregateError(
134 error === undefined ? cleanupErrors : [error, ...cleanupErrors],
135 'Real release command and process termination failures',
136 { cause: error ?? cleanupErrors[0] },
137 )
138 resolve({
139 status,
140 signal,
141 stdout: Buffer.concat(stdout).toString(),
142 stderr: Buffer.concat(stderr).toString(),
143 error,
144 })
145 })
146 })
148​
149function executable(name) {
150 for (const directory of (process.env.PATH ?? '').split(delimiter)) {
151 const path = join(directory, name)
152 try {
153 accessSync(path, constants.X_OK)
154 return realpathSync(path)
155 } catch {}
156 }
157 throw new Error(`HTTP release setup requires an installed ${name} executable`)
159​
160async function startRegistry(statePath) {
161 const child = fork(registryScript, [statePath], {
162 detached: true,
163 stdio: ['ignore', 'pipe', 'pipe', 'ipc'],
164 env: {
165 ...(process.env.HOME ? { HOME: process.env.HOME } : {}),
166 ...(process.env.TMPDIR ? { TMPDIR: process.env.TMPDIR } : {}),
167 },
168 })
169 let output = ''
170 for (const stream of [child.stdout, child.stderr])
171 stream.on('data', (chunk) => {
172 output = (output + chunk).slice(-8192)
173 })
174 try {
175 const origin = await new Promise((resolve, reject) => {
176 const timer = setTimeout(
177 () => reject(new Error(`HTTP registry setup timed out: ${output}`)),
178 5000,
179 )
180 const finish = (error, value) => {
181 clearTimeout(timer)
182 error ? reject(error) : resolve(value)
183 }
184 child.once('error', (error) => finish(error))
185 child.once('exit', (code, signal) =>
186 finish(
187 new Error(
188 `HTTP registry exited during setup: ${code}/${signal}: ${output}`,
189 ),
190 ),
191 )
192 child.once('message', (message) =>
193 message.origin
194 ? finish(undefined, message.origin)
195 : finish(
196 new Error(
197 `HTTP registry setup failed: ${message.code}: ${message.setupError}`,
198 ),
199 ),
200 )
201 })
202 return { child, origin, output: () => output }
203 } catch (error) {
204 return failAfterTermination(child, error)
205 }
207​
208async function stopRegistry({ child, output }) {
209 if (child.exitCode !== null || child.signalCode !== null)
210 throw new Error(
211 `HTTP registry exited unexpectedly: ${child.exitCode}/${child.signalCode}: ${output()}`,
212 )
213 try {
214 await new Promise((resolve, reject) => {
215 const timer = setTimeout(() => {
216 reject(new Error('HTTP registry cleanup timed out'))
217 }, 5000)
218 child.once('exit', (code, signal) => {
219 clearTimeout(timer)
220 code === 0
221 ? resolve()
222 : reject(
223 new Error(
224 `HTTP registry cleanup failed: ${code}/${signal}: ${output()}`,
225 ),
226 )
227 })
228 child.send('close')
229 })
230 } catch (error) {
231 return failAfterTermination(child, error)
232 }
234​
235/** The server is a child because publishDuringRc synchronously blocks Node. */
236export async function withHttpPublishReceiver(root, history, body) {
237 if (process.platform === 'win32')
238 throw new Error(
239 'HTTP release receiver requires POSIX process-group cleanup',
240 )
241 writeFileSync(
242 join(root, 'pnpm-workspace.yaml'),
243 readFileSync(join(root, 'pnpm-workspace.yaml'), 'utf8') +
244 '\nverifyDepsBeforeRun: false\n',
245 )
246 const bin = join(root, 'real-bin')
247 mkdirSync(bin)
248 const toolPaths = {
249 node: process.execPath,
250 npm: executable('npm'),
251 pnpm: executable('pnpm'),
252 git: executable('git'),
253 }
254 for (const [name, resolvedPath] of Object.entries(toolPaths)) {
255 // A pnpm shell launcher can find its CLI relative to $0. Invoke it at its
256 // installed path instead of relocating that pathname through a symlink.
257 if (name === 'pnpm') {
258 const quotedPath = `'${resolvedPath.replaceAll("'", "'\\''")}'`
259 writeFileSync(join(bin, name), `#!/bin/sh\nexec ${quotedPath} "$@"\n`, {
260 mode: 0o755,
261 })
262 } else symlinkSync(realpathSync(resolvedPath), join(bin, name))
263 }
264 mkdirSync(join(root, 'node_modules', '.bin'), { recursive: true })
265 symlinkSync(changeset, join(root, 'node_modules', '.bin', 'changeset'))
266 const manifests = Object.keys(packageNames).map((key) => {
267 const manifest = readJson(manifestPath(root, key))
268 manifest.version =
269 key === 'db'
270 ? history.candidate
271 : key === 'react'
272 ? (history.reactCandidate ?? history.candidate)
273 : key === 'query'
274 ? '1.5.0'
275 : '1.2.0'
276 writeJson(manifestPath(root, key), manifest)
277 writeFileSync(
278 join(root, 'packages', key, 'index.js'),
279 'export const fixture = true\n',
280 )
281 return manifest
282 })
283 // pnpm resolves workspace:* from local links while packing. Supply those
284 // fixture links directly; this receiver performs no dependency installation
285 // and makes no claim about the repository's installed dependency graph.
286 for (const [owner, name, target] of [
287 ['db', 'release-private', 'private'],
288 ['react', packageNames.db, 'db'],
289 ]) {
290 const directory = join(root, 'packages', owner, 'node_modules')
291 mkdirSync(join(directory, name.startsWith('@') ? name.split('/')[0] : ''), {
292 recursive: true,
293 })
294 symlinkSync(join(root, 'packages', target), join(directory, name))
295 }
296 const initialRegistry = Object.fromEntries(
297 manifests.map(({ name, version }, index) => {
298 const key = Object.keys(packageNames)[index]
299 const candidate = name === packageNames.db || name === packageNames.react
300 const current =
301 history.registry === 'current' || history.currentCandidate === key
302 const versions =
303 history.registry === 'never'
304 ? []
305 : current
306 ? ['older-rc', 'older-rc-latest-current'].includes(
307 history.tagShape,
308 ) && candidate
309 ? ['1.0.0-rc.1', version]
310 : [version]
311 : candidate
312 ? history.registry === 'only-rc'
313 ? ['1.0.0-rc.1']
314 : ['0.15.2']
315 : ['1.0.0']
316 const last = versions.at(-1)
317 // A dist-tag may point only to an existing version. Missing tags are legal,
318 // including after a candidate was accidentally published under latest.
319 const tags =
320 last === undefined ||
321 (candidate && history.tagShape === 'no-tags') ||
322 (!candidate && history.stableTagShape === 'no-tags')
323 ? {}
324 : candidate && history.tagShape === 'latest-only'
325 ? { latest: last }
326 : candidate &&
327 ['older-rc', 'older-rc-latest-current'].includes(
328 history.tagShape,
329 )
330 ? {
331 rc: versions[0],
332 ...(history.tagShape === 'older-rc-latest-current'
333 ? { latest: last }
334 : {}),
335 }
336 : candidate && ['only-rc', 'current'].includes(history.registry)
337 ? {
338 rc: last,
339 ...(history.tagShape === 'latest-alias'
340 ? { latest: last }
341 : {}),
342 }
343 : { latest: last }
344 return [name, { versions, tags }]
345 }),
346 )
347 // Reject a nearby invalid packument: every authored tag names a present
348 // version. Tag absence and exact-target absence remain independent facts.
349 for (const entry of Object.values(initialRegistry))
350 for (const version of Object.values(entry.tags))
351 assert(
352 entry.versions.includes(version),
353 'fixture dist-tag names an existing version',
354 )
355 const statePath = join(root, 'http-registry.json')
356 writeJson(statePath, {
357 packages: structuredClone(initialRegistry),
358 failed: false,
359 requests: [],
360 candidateNames: [packageNames.db, packageNames.react],
361 failureMode:
362 history.failure === 'candidate-after-success'
363 ? history.failure
364 : undefined,
365 failureName:
366 history.failure === 'stable'
367 ? packageNames.query
368 : history.failure === 'candidate'
369 ? packageNames.db
370 : undefined,
371 })
372 writeJson(join(root, '.changeset', 'pre.json'), {
373 mode: 'pre',
374 tag: 'rc',
375 initialVersions: Object.fromEntries(
376 manifests.map(({ name, version }) => [name, version]),
377 ),
378 changesets: [],
379 })
380 const registry = await startRegistry(statePath)
381 let failed = false
382 let primary
383 try {
384 const userConfig = join(root, 'npm-user-config')
385 const globalConfig = join(root, 'npm-global-config')
386 const gitConfig = join(root, 'git-global-config')
387 const hooks = join(root, 'empty-hooks')
388 mkdirSync(hooks)
389 writeFileSync(globalConfig, '')
390 writeFileSync(gitConfig, '')
391 writeFileSync(
392 userConfig,
393 [
394 `registry=${registry.origin}`,
395 `@tanstack:registry=${registry.origin}`,
396 `//${new URL(registry.origin).host}/:_authToken=release-http-fixture`,
397 'ignore-scripts=true',
398 'audit=false',
399 'fund=false',
400 'update-notifier=false',
401 'fetch-retries=0',
402 'fetch-timeout=5000',
403 'provenance=false',
404 ].join('\n') + '\n',
405 )
406 const environment = {
407 PATH: `${bin}:/usr/bin:/bin`,
408 ...(process.env.HOME ? { HOME: process.env.HOME } : {}),
409 ...(process.env.TMPDIR ? { TMPDIR: process.env.TMPDIR } : {}),
410 CI: 'true',
411 COREPACK_ENABLE_NETWORK: '0',
412 npm_config_registry: registry.origin,
413 NPM_CONFIG_USERCONFIG: userConfig,
414 NPM_CONFIG_GLOBALCONFIG: globalConfig,
415 NPM_CONFIG_CACHE: join(root, 'npm-cache'),
416 NPM_CONFIG_LOGLEVEL: 'error',
417 NPM_CONFIG_LOGS_MAX: '0',
418 XDG_CONFIG_HOME: join(root, 'xdg-config'),
419 GIT_CONFIG_GLOBAL: gitConfig,
420 GIT_CONFIG_NOSYSTEM: '1',
421 GIT_TERMINAL_PROMPT: '0',
422 }
423 for (const args of [
424 ['init', '--quiet', `--template=${hooks}`],
425 ['config', 'core.hooksPath', hooks],
426 ['config', 'commit.gpgSign', 'false'],
427 ['config', 'tag.gpgSign', 'false'],
428 ['config', 'user.email', 'oracle@example.invalid'],
429 ['config', 'user.name', 'Release oracle'],
430 ['add', '.'],
431 ['commit', '--quiet', '-m', 'HTTP release fixture'],
432 ])
433 execFileSync(join(bin, 'git'), args, {
434 cwd: root,
435 env: environment,
436 stdio: 'pipe',
437 timeout: 10_000,
438 })
439 const receiver = {
440 manifests,
441 initialRegistry,
442 origin: registry.origin,
443 tools: {
444 paths: toolPaths,
445 ...Object.fromEntries(
446 ['npm', 'pnpm'].map((name) => [
447 name,
448 execFileSync(join(bin, name), ['--version'], {
449 cwd: root,
450 env: environment,
451 encoding: 'utf8',
452 timeout: 10_000,
453 }).trim(),
454 ]),
455 ),
456 },
457 readState: () => readJson(statePath),
458 bytes: () =>
459 Object.fromEntries(
460 [
461 '.changeset/pre.json',
462 ...Object.keys(packageNames).map(
463 (key) => `packages/${key}/package.json`,
464 ),
465 ].map((file) => [file, readFileSync(join(root, file), 'base64')]),
466 ),
467 async run() {
468 const result = await runReleaseToolTree(
469 process.execPath,
470 [publishScript, root],
471 {
472 cwd: root,
473 env: environment,
474 timeout: 30_000,
475 },
476 )
477 if (result.error)
478 throw new Error('Real release command setup or timeout failure', {
479 cause: result.error,
480 })
481 if (result.status !== 0)
482 throw new Error(
483 `Real release command failed (${result.status}):\n${result.stdout}\n${result.stderr}`,
484 )
485 },
486 }
487 return await body(receiver)
488 } catch (error) {
489 failed = true
490 primary = error
491 throw error
492 } finally {
493 try {
494 await stopRegistry(registry)
495 } catch (cleanup) {
496 throw failed
497 ? new AggregateError(
498 [primary, cleanup],
499 'HTTP release comparison and cleanup failures',
500 { cause: primary },
501 )
502 : cleanup
503 }
504 }