Skip to content

Commit

Permalink
fix: retry writing traced files if there are conflicts (nitrojs#537)
Browse files Browse the repository at this point in the history
  • Loading branch information
danielroe authored and WinterYukky committed Nov 1, 2022
1 parent de548f0 commit 03d420e
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 3 deletions.
6 changes: 3 additions & 3 deletions src/rollup/plugins/externals.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { nodeFileTrace, NodeFileTraceOptions } from '@vercel/nft'
import type { Plugin } from 'rollup'
import { resolvePath, isValidNodeImport, normalizeid } from 'mlly'
import semver from 'semver'
import { isDirectory } from '../../utils'
import { isDirectory, retry } from '../../utils'

export interface NodeExternalsOptions {
inline?: string[]
Expand Down Expand Up @@ -220,7 +220,7 @@ export function externals (opts: NodeExternalsOptions): Plugin {
}
}

const writeFile = async (file) => {
const writeFile = async (file: string) => {
if (!await isFile(file)) { return }
const src = resolve(opts.traceOptions.base, file)
const { pkgName, subpath } = parseNodeModulePath(file)
Expand All @@ -230,7 +230,7 @@ export function externals (opts: NodeExternalsOptions): Plugin {
}

// Write traced files
await Promise.all(tracedFiles.map(writeFile))
await Promise.all(tracedFiles.map(file => retry(() => writeFile(file), 3)))

// Write an informative package.json
await fsp.writeFile(resolve(opts.outDir, 'package.json'), JSON.stringify({
Expand Down
12 changes: 12 additions & 0 deletions src/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -146,3 +146,15 @@ export function resolveAliases (_aliases: Record<string, string>) {
}
return aliases
}

export async function retry (fn: () => Promise<void>, retries: number) {
let retry = 0
let error: any
while (retry++ < retries) {
try { return await fn() } catch (err) {
error = err
await new Promise(resolve => setTimeout(resolve, 2))
}
}
throw error
}
22 changes: 22 additions & 0 deletions test/unit/utils.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { describe, it, expect } from 'vitest'
import { retry } from '../../src/utils'

describe('retry', () => {
it('retries function', async () => {
let counter = 0
// eslint-disable-next-line require-await
const fn = async () => {
if (!counter++) {
throw new Error('deliberate')
}
}

await retry(fn, 3)
expect(counter).toEqual(2)
})
it('throws function', async () => {
// eslint-disable-next-line require-await
const fn = async () => { throw new Error('deliberate') }
expect(await retry(fn, 2).catch(() => 'thrown')).toEqual('thrown')
})
})

0 comments on commit 03d420e

Please sign in to comment.