Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: terminate the process correctly #2499

Closed
wants to merge 10 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion lib/fetch/body.js
Original file line number Diff line number Diff line change
Expand Up @@ -277,7 +277,8 @@ function cloneBody (body) {
const out2Clone = structuredClone(out2, { transfer: [out2] })
// This, for whatever reasons, unrefs out2Clone which allows
// the process to exit by itself.
const [, finalClone] = out2Clone.tee()
const [cancelClone, finalClone] = out2Clone.tee()
cancelClone.cancel().catch(() => null)

// 2. Set body’s stream to out1.
body.stream = out1
Expand Down
63 changes: 63 additions & 0 deletions test/fetch/worker_threads.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
const {
isMainThread,
parentPort,
Worker,
workerData
} = require('node:worker_threads')

if (isMainThread) {
const { test } = require('tap')
const { once } = require('node:events')
const { cpus } = require('node:os')
const { createServer } = require('node:http')
const THREADS = cpus().length - 1
const ROUNDS = 10
test('terminate the process correctly', async (t) => {
const server = createServer((req, res) => {
res.end('Hi')
})

t.teardown(server.close.bind(server))
server.listen(0)
await once(server, 'listening')

const serverName = `http://localhost:${server.address().port}`

async function task () {
const worker = new Worker(__filename, { workerData: { serverName } })
await new Promise((resolve) => {
worker.on('message', (message) => {
if (message === 'DONE') resolve()
})
})

await worker.terminate()
}

const pool = new Array(ROUNDS).fill(task)

async function execute () {
const task = pool.shift()

if (task) {
await task()
return execute()
}
}
await Promise.all(new Array(THREADS).fill(execute).map((task) => task()))
t.end()
})
} else {
(async () => {
const serverName = workerData.serverName
const { fetch } = require('../..')

await Promise.all([
fetch(serverName).then((r) => r.arrayBuffer()),
fetch(serverName).then((r) => r.arrayBuffer()),
fetch(serverName).then((r) => r.arrayBuffer()),
fetch(serverName).then((r) => r.arrayBuffer())
])
parentPort.postMessage('DONE')
})()
}
Loading