publish.ts 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. /**
  2. * Publish one packed release family from the tarballs the pack step produced.
  3. *
  4. * Publication is decided per package against the registry, never from a list of
  5. * "what this release includes": a version the registry lacks is published, a
  6. * version whose published tarball has the same integrity is skipped, and a
  7. * version whose published tarball differs fails the run — that last case means
  8. * the content changed without a version bump
  9. * ([rationale](../../.agents/notes/implemented/process/2026-08-10-npm-release-sequences.md)).
  10. *
  11. * Skipping on identical integrity is what makes re-running the publish step over
  12. * the same artifact safe.
  13. */
  14. import { createHash } from 'node:crypto'
  15. import { readFileSync } from 'node:fs'
  16. import { join, resolve } from 'node:path'
  17. import { setTimeout as sleep } from 'node:timers/promises'
  18. import { parseArgs } from 'node:util'
  19. import { releaseFamily } from './families.ts'
  20. import { attempt, attemptEchoed, isEntry } from './process.ts'
  21. import { packedIdentity, readPublishOrder } from './tarball.ts'
  22. /**
  23. * Registry codes that answer a write which did not settle, rather than a
  24. * rejection of what was sent. `E409 Failed to save packument` is the one this
  25. * sequence actually hits: publishing several packages in a row can outrun the
  26. * registry's own processing. A rejected payload (`E403` over an existing
  27. * version, a malformed manifest) never clears on a retry and must surface.
  28. */
  29. const TRANSIENT_PUBLISH_CODES = ['E409', 'E429', 'E500', 'E502', 'E503', 'E504', 'ETIMEDOUT', 'ECONNRESET', 'EAI_AGAIN'] as const
  30. /** How many times one tarball's publish is attempted before the run fails. */
  31. const PUBLISH_ATTEMPTS = 4
  32. /**
  33. * Shortest gap between two publishes, and the first retry backoff.
  34. *
  35. * The registry needs a moment to commit a packument before the next write; back
  36. * to back publishes are what produce `E409`.
  37. */
  38. const PUBLISH_SPACING_MS = 2_000
  39. /** What the registry knows about one version. */
  40. type RegistryState =
  41. | { readonly kind: 'absent' }
  42. | { readonly kind: 'present'; readonly integrity: string }
  43. /**
  44. * Whether a failed publish is worth another attempt.
  45. * @param output - combined npm output.
  46. * @returns True when the registry reported a write it did not commit.
  47. */
  48. function isTransientFailure(output: string): boolean {
  49. return TRANSIENT_PUBLISH_CODES.some(code => output.includes(`code ${code}`))
  50. }
  51. /**
  52. * The subresource integrity string npm records for a tarball.
  53. * @param tarball - absolute tarball path.
  54. * @returns A `sha512-<base64>` string.
  55. */
  56. function integrityOf(tarball: string): string {
  57. return `sha512-${createHash('sha512').update(readFileSync(tarball)).digest('base64')}`
  58. }
  59. /**
  60. * Ask the registry whether a version exists, and with what integrity.
  61. * @param name - package name.
  62. * @param version - package version.
  63. * @returns The registry state for that version.
  64. */
  65. function registryState(name: string, version: string): RegistryState {
  66. const result = attempt('npm', ['view', `${name}@${version}`, 'dist.integrity', '--json'])
  67. if (result.status !== 0) {
  68. const output = `${result.stdout}${result.stderr}`
  69. if (output.includes('E404') || output.includes('404 Not Found')) return { kind: 'absent' }
  70. throw new Error(`npm view ${name}@${version} failed:\n${output}`)
  71. }
  72. const parsed: unknown = JSON.parse(result.stdout)
  73. if (typeof parsed !== 'string' || parsed === '') {
  74. throw new Error(`registry reported no dist.integrity for ${name}@${version}`)
  75. }
  76. return { kind: 'present', integrity: parsed }
  77. }
  78. /**
  79. * Publish one tarball, retrying a registry write that did not settle.
  80. *
  81. * Every retry re-reads the registry first, because `E409` can answer a write
  82. * that landed anyway: republishing a version that now exists fails permanently,
  83. * so the same integrity appearing under the failed attempt counts as success.
  84. * @param tarball - absolute tarball path.
  85. * @param name - package name the tarball declares.
  86. * @param version - package version the tarball declares.
  87. */
  88. async function publishTarball(tarball: string, name: string, version: string): Promise<void> {
  89. // A prerelease version never takes the latest dist-tag.
  90. const tagArgs = version.includes('-') ? ['--tag', 'next'] : []
  91. for (let tries = 1; tries <= PUBLISH_ATTEMPTS; tries += 1) {
  92. // No --access: the sequences do not share one access level, so a
  93. // command-line flag could not serve both and would override the manifest
  94. // that does. Each packed manifest decides, and
  95. // check-workspace-constraints holds every manifest to its sequence's level.
  96. const result = attemptEchoed('npm', ['publish', tarball, ...tagArgs])
  97. const output = `${result.stdout}${result.stderr}`
  98. if (result.status === 0) return
  99. const settled = registryState(name, version)
  100. if (settled.kind === 'present' && settled.integrity === integrityOf(tarball)) {
  101. console.log(`release publish: ${name}@${version} landed despite a reported failure, continuing`)
  102. return
  103. }
  104. if (tries === PUBLISH_ATTEMPTS || !isTransientFailure(output)) {
  105. throw new Error(`npm publish ${name}@${version} failed:\n${output}`)
  106. }
  107. const backoff = PUBLISH_SPACING_MS * 2 ** (tries - 1)
  108. console.log(
  109. `release publish: ${name}@${version} hit a transient registry failure`
  110. + ` (attempt ${String(tries)} of ${String(PUBLISH_ATTEMPTS)}), retrying in ${String(backoff)}ms`,
  111. )
  112. await sleep(backoff)
  113. }
  114. }
  115. /** Publish the family named by `--family` from the directory named by `--from`. */
  116. async function main(): Promise<void> {
  117. const { values } = parseArgs({
  118. options: { family: { type: 'string' }, from: { type: 'string' } },
  119. allowPositionals: false,
  120. })
  121. if (values.family === undefined || values.from === undefined) {
  122. throw new Error('usage: publish.ts --family <dsh|vendor> --from <packed directory>')
  123. }
  124. const family = releaseFamily(values.family)
  125. const directory = resolve(process.cwd(), values.from)
  126. // Every entry in the order settles as either published or already present, so
  127. // one counter answers "how far along is this run" for whoever is watching a
  128. // release that takes minutes per family.
  129. const order = readPublishOrder(directory)
  130. const total = String(order.length)
  131. let published = 0
  132. let skipped = 0
  133. for (const [index, filename] of order.entries()) {
  134. const progress = `[${String(index + 1)}/${total}]`
  135. const tarball = join(directory, filename)
  136. const { name, version } = packedIdentity(tarball)
  137. const state = registryState(name, version)
  138. if (state.kind === 'present') {
  139. const local = integrityOf(tarball)
  140. if (state.integrity !== local) {
  141. throw new Error(
  142. `${name}@${version} is already published with different content`
  143. + `\n registry: ${state.integrity}\n packed: ${local}`
  144. + '\nBump the version, or investigate why the build is not reproducible.',
  145. )
  146. }
  147. console.log(`release publish: ${progress} ${name}@${version} already published, skipping`)
  148. skipped += 1
  149. continue
  150. }
  151. // Space out the writes: the gap belongs between publishes, so a run that
  152. // only skips does not wait at all.
  153. if (published > 0) await sleep(PUBLISH_SPACING_MS)
  154. await publishTarball(tarball, name, version)
  155. console.log(`release publish: ${progress} ${name}@${version} published`)
  156. published += 1
  157. }
  158. console.log(
  159. `release publish: family ${family.id}, ${total} member(s),`
  160. + ` ${String(published)} published, ${String(skipped)} already present`,
  161. )
  162. }
  163. if (isEntry(import.meta.url)) await main()