Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(cli): retry npm installer downloads (#82416)

Manoel Aranda Netoc75bed062278
diff --git a/.github/scripts/patch-cli-npm-installer.mjs b/.github/scripts/patch-cli-npm-installer.mjs
new file mode 100644
index 000000000000..7eceb77d234f
--- /dev/null
+++ b/.github/scripts/patch-cli-npm-installer.mjs
@@ -0,0 +1,138 @@
+#!/usr/bin/env node
+
+import { execFileSync } from 'node:child_process'
+import { createHash } from 'node:crypto'
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { basename, join } from 'node:path'
+import { fileURLToPath } from 'node:url'
+
+// Remove this release-time patch when cargo-dist extends https://github.com/axodotdev/cargo-dist/pull/2311 to its npm installer.
+const DOWNLOAD_MAX_ATTEMPTS = 4
+const DOWNLOAD_RETRY_BASE_DELAY_MS = 1000
+
+export function isTransientDownloadError(error) {
+ const status = Number(/HTTP (\d{3})/.exec(error?.message ?? '')?.[1])
+ if (status) {
+ return status === 408 || status === 429 || status >= 500
+ }
+
+ return (
+ ['ECONNRESET', 'ECONNREFUSED', 'EHOSTUNREACH', 'ENETUNREACH', 'ETIMEDOUT', 'EAI_AGAIN'].includes(error?.code) ||
+ /socket hang up|network|timed? ?out/i.test(error?.message ?? '')
+ )
+}
+
+function sleep(delayMs) {
+ return new Promise((resolve) => setTimeout(resolve, delayMs))
+}
+
+export async function downloadWithRetry(
+ operation,
+ {
+ maxAttempts = DOWNLOAD_MAX_ATTEMPTS,
+ baseDelayMs = DOWNLOAD_RETRY_BASE_DELAY_MS,
+ sleepFn = sleep,
+ onRetry = () => {},
+ } = {}
+) {
+ for (let attempt = 1; ; attempt++) {
+ try {
+ return await operation()
+ } catch (error) {
+ if (attempt >= maxAttempts || !isTransientDownloadError(error)) {
+ throw error
+ }
+
+ const delayMs = baseDelayMs * 2 ** (attempt - 1)
+ onRetry(error, attempt, delayMs)
+ await sleepFn(delayMs)
+ }
+ }
+}
+
+const RETRY_HELPER_SOURCE = `
+const DOWNLOAD_MAX_ATTEMPTS = ${DOWNLOAD_MAX_ATTEMPTS};
+const DOWNLOAD_RETRY_BASE_DELAY_MS = ${DOWNLOAD_RETRY_BASE_DELAY_MS};
+
+${isTransientDownloadError.toString()}
+
+${sleep.toString()}
+
+${downloadWithRetry.toString()}
+`
+
+export function patchBinaryInstaller(source) {
+ const importAnchor = 'const http = require("node:http");'
+ const downloadAnchor = 'return download(this.url)'
+
+ if (!source.includes(importAnchor)) {
+ throw new Error(`Could not find the HTTP import in cargo-dist's binary-install.js`)
+ }
+ if (!source.includes(downloadAnchor)) {
+ throw new Error(`Could not find the artifact download call in cargo-dist's binary-install.js`)
+ }
+ if (source.includes('downloadWithRetry(() => download(this.url)')) {
+ throw new Error(`cargo-dist's binary-install.js is already patched`)
+ }
+
+ return source
+ .replace(importAnchor, `${importAnchor}\n${RETRY_HELPER_SOURCE}`)
+ .replace(
+ downloadAnchor,
+ `return downloadWithRetry(() => download(this.url), {\n onRetry: (error, attempt, delayMs) => {\n console.error(\n \`Download attempt \${attempt} failed (\${error.message}); retrying in \${delayMs}ms...\`,\n );\n },\n })`
+ )
+}
+
+function sha256(path) {
+ return createHash('sha256').update(readFileSync(path)).digest('hex')
+}
+
+export function patchNpmArchive(archivePath) {
+ const workingDirectory = mkdtempSync(join(tmpdir(), 'posthog-cli-npm-'))
+
+ try {
+ execFileSync('tar', ['-xzf', archivePath, '-C', workingDirectory])
+ const installerPath = join(workingDirectory, 'package', 'binary-install.js')
+ writeFileSync(installerPath, patchBinaryInstaller(readFileSync(installerPath, 'utf8')))
+ execFileSync('tar', ['-czf', archivePath, '-C', workingDirectory, 'package'])
+ } finally {
+ rmSync(workingDirectory, { recursive: true, force: true })
+ }
+}
+
+export function updateReleaseChecksums(distributionDirectory, manifestPath, archivePath) {
+ const archiveName = basename(archivePath)
+ const archiveChecksum = sha256(archivePath)
+ const checksumPath = join(distributionDirectory, 'sha256.sum')
+ const checksumLines = readFileSync(checksumPath, 'utf8').trimEnd().split('\n')
+ const checksumIndex = checksumLines.findIndex((line) => line.endsWith(`*${archiveName}`))
+
+ if (checksumIndex === -1) {
+ throw new Error(`Could not find ${archiveName} in ${checksumPath}`)
+ }
+
+ checksumLines[checksumIndex] = `${archiveChecksum} *${archiveName}`
+ writeFileSync(checksumPath, `${checksumLines.join('\n')}\n`)
+
+ const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'))
+ const artifact = manifest.artifacts?.[archiveName]
+ if (!artifact?.checksums?.sha256) {
+ throw new Error(`Could not find the ${archiveName} checksum in ${manifestPath}`)
+ }
+
+ artifact.checksums.sha256 = archiveChecksum
+ writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`)
+}
+
+export function patchCliNpmInstaller(distributionDirectory, manifestPath) {
+ const archivePath = join(distributionDirectory, 'posthog-cli-npm-package.tar.gz')
+ patchNpmArchive(archivePath)
+ updateReleaseChecksums(distributionDirectory, manifestPath, archivePath)
+}
+
+if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) {
+ const [distributionDirectory = 'target/distrib', manifestPath = 'dist-manifest.json'] = process.argv.slice(2)
+ patchCliNpmInstaller(distributionDirectory, manifestPath)
+ console.log('Added retries with exponential backoff to the generated posthog-cli npm installer')
+}
diff --git a/.github/scripts/patch-cli-npm-installer.test.mjs b/.github/scripts/patch-cli-npm-installer.test.mjs
new file mode 100644
index 000000000000..d6164158615d
--- /dev/null
+++ b/.github/scripts/patch-cli-npm-installer.test.mjs
@@ -0,0 +1,124 @@
+import assert from 'node:assert/strict'
+import { execFileSync } from 'node:child_process'
+import { createHash } from 'node:crypto'
+import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import test from 'node:test'
+
+import {
+ downloadWithRetry,
+ isTransientDownloadError,
+ patchBinaryInstaller,
+ patchCliNpmInstaller,
+} from './patch-cli-npm-installer.mjs'
+
+const GENERATED_INSTALLER = `const http = require("node:http");
+
+class Package {
+ install() {
+ return download(this.url)
+ .then(() => {});
+ }
+}
+`
+
+test('classifies only transient download failures as retryable', () => {
+ for (const message of ['HTTP 408 from URL', 'HTTP 429 from URL', 'HTTP 500 from URL', 'socket hang up']) {
+ assert.equal(isTransientDownloadError(new Error(message)), true, message)
+ }
+
+ const reset = new Error('read ECONNRESET')
+ reset.code = 'ECONNRESET'
+ assert.equal(isTransientDownloadError(reset), true)
+ assert.equal(isTransientDownloadError(new Error('HTTP 404 from URL')), false)
+})
+
+test('retries transient failures with exponential backoff', async () => {
+ const delays = []
+ let attempts = 0
+
+ const result = await downloadWithRetry(
+ async () => {
+ attempts++
+ if (attempts < 4) {
+ throw new Error('HTTP 503 from URL')
+ }
+ return 'downloaded'
+ },
+ {
+ sleepFn: async (delayMs) => delays.push(delayMs),
+ }
+ )
+
+ assert.equal(result, 'downloaded')
+ assert.equal(attempts, 4)
+ assert.deepEqual(delays, [1000, 2000, 4000])
+})
+
+test('does not retry permanent failures', async () => {
+ let attempts = 0
+
+ await assert.rejects(
+ downloadWithRetry(async () => {
+ attempts++
+ throw new Error('HTTP 404 from URL')
+ }),
+ /HTTP 404/
+ )
+ assert.equal(attempts, 1)
+})
+
+test('patches the cargo-dist download call', () => {
+ const patched = patchBinaryInstaller(GENERATED_INSTALLER)
+
+ assert.match(patched, /downloadWithRetry\(\(\) => download\(this\.url\)/)
+ assert.match(patched, /DOWNLOAD_MAX_ATTEMPTS = 4/)
+ assert.match(patched, /DOWNLOAD_RETRY_BASE_DELAY_MS = 1000/)
+})
+
+test('patches the npm archive and refreshes release checksums', () => {
+ const root = mkdtempSync(join(tmpdir(), 'posthog-cli-patcher-test-'))
+
+ try {
+ const distributionDirectory = join(root, 'target', 'distrib')
+ const packageDirectory = join(root, 'package')
+ const archivePath = join(distributionDirectory, 'posthog-cli-npm-package.tar.gz')
+ const checksumPath = join(distributionDirectory, 'sha256.sum')
+ const manifestPath = join(root, 'dist-manifest.json')
+ mkdirSync(distributionDirectory, { recursive: true })
+ mkdirSync(packageDirectory)
+ writeFileSync(join(packageDirectory, 'binary-install.js'), GENERATED_INSTALLER)
+ execFileSync('tar', ['-czf', archivePath, '-C', root, 'package'])
+ writeFileSync(checksumPath, `old-checksum *posthog-cli-npm-package.tar.gz\n`)
+ writeFileSync(
+ manifestPath,
+ JSON.stringify({
+ artifacts: {
+ 'posthog-cli-npm-package.tar.gz': {
+ checksums: { sha256: 'old-checksum' },
+ },
+ },
+ })
+ )
+
+ patchCliNpmInstaller(distributionDirectory, manifestPath)
+
+ const unpackDirectory = join(root, 'unpacked')
+ mkdirSync(unpackDirectory)
+ execFileSync('tar', ['-xzf', archivePath, '-C', unpackDirectory])
+ assert.match(
+ readFileSync(join(unpackDirectory, 'package', 'binary-install.js'), 'utf8'),
+ /downloadWithRetry\(\(\) => download\(this\.url\)/
+ )
+
+ const checksum = createHash('sha256').update(readFileSync(archivePath)).digest('hex')
+ assert.equal(readFileSync(checksumPath, 'utf8'), `${checksum} *posthog-cli-npm-package.tar.gz\n`)
+ assert.equal(
+ JSON.parse(readFileSync(manifestPath, 'utf8')).artifacts['posthog-cli-npm-package.tar.gz'].checksums.sha256,
+ checksum
+ )
+ } finally {
+ rmSync(root, { recursive: true, force: true })
+ }
+})
diff --git a/.github/workflows/ci-scripts.yml b/.github/workflows/ci-scripts.yml
index b119b8f6ae87..19bda093d40f 100644
--- a/.github/workflows/ci-scripts.yml
+++ b/.github/workflows/ci-scripts.yml
@@ -73,6 +73,10 @@ jobs:
if: ${{ hashFiles('.github/scripts/weekly-flaky-report.test.mjs') != '' }}
run: node --test .github/scripts/weekly-flaky-report.test.mjs
+ - name: CLI npm installer patch tests (Node)
+ if: ${{ hashFiles('.github/scripts/patch-cli-npm-installer.test.mjs') != '' }}
+ run: node --test .github/scripts/patch-cli-npm-installer.test.mjs
+
- name: Turbo-discover dependent-cascade tests (Node)
run: node --test .github/scripts/turbo-discover-cascade.test.js
diff --git a/.github/workflows/release-cli.yml b/.github/workflows/release-cli.yml
index 0e9ff1fe7adc..354226322bfc 100644
--- a/.github/workflows/release-cli.yml
+++ b/.github/workflows/release-cli.yml
@@ -546,6 +546,8 @@ jobs:
dist build ${{ needs.plan-release.outputs.tag-flag }} --output-format=json "--artifacts=global" > dist-manifest.json
echo "dist ran successfully"
+ node .github/scripts/patch-cli-npm-installer.mjs target/distrib dist-manifest.json
+
# Parse out what we just built and upload it to scratch storage
echo "paths<<EOF" >> "$GITHUB_OUTPUT"
jq --raw-output ".upload_files[]" dist-manifest.json >> "$GITHUB_OUTPUT"
diff --git a/cli/.sampo/changesets/npm-installer-download-retries.md b/cli/.sampo/changesets/npm-installer-download-retries.md
new file mode 100644
index 000000000000..6a4253856e5c
--- /dev/null
+++ b/cli/.sampo/changesets/npm-installer-download-retries.md
@@ -0,0 +1,5 @@
+---
+cargo/posthog-cli: patch
+---
+
+Retry transient GitHub release download failures with exponential backoff when installing `@posthog/cli` from npm.