Skip to content

Commit f7bcc04

Browse files
gatsbybotascorbic
andauthored
fix(gatsby): wait for worker jobs to complete (#35513) (#35522)
Co-authored-by: Matt Kane <[email protected]>
1 parent f237aa7 commit f7bcc04

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

packages/gatsby/src/commands/build.ts

+5-1
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@ import {
6262
} from "../utils/page-mode"
6363
import { validateEngines } from "../utils/validate-engines"
6464
import { constructConfigObject } from "../utils/gatsby-cloud-config"
65+
import { waitUntilWorkerJobsAreComplete } from "../utils/jobs/worker-messaging"
6566

6667
module.exports = async function build(
6768
program: IBuildArgs,
@@ -295,7 +296,10 @@ module.exports = async function build(
295296
parentSpan: buildSpan,
296297
})
297298
// Jobs still might be running even though query running finished
298-
await waitUntilAllJobsComplete()
299+
await Promise.all([
300+
waitUntilAllJobsComplete(),
301+
waitUntilWorkerJobsAreComplete(),
302+
])
299303
// Restart worker pool before merging state to lower memory pressure while merging state
300304
waitForWorkerPoolRestart = workerPool.restart()
301305
await mergeWorkerState(workerPool, buildSpan)

packages/gatsby/src/utils/jobs/worker-messaging.ts

+16
Original file line numberDiff line numberDiff line change
@@ -11,11 +11,18 @@ import { internalActions } from "../../redux/actions"
1111
import { GatsbyWorkerPool } from "../worker/types"
1212
import { isWorker, getMessenger } from "../worker/messaging"
1313

14+
let hasActiveWorkerJobs: pDefer.DeferredPromise<void> | null = null
15+
let activeWorkerJobs = 0
16+
1417
export function initJobsMessagingInMainProcess(
1518
workerPool: GatsbyWorkerPool
1619
): void {
1720
workerPool.onMessage((msg, workerId) => {
1821
if (msg.type === MESSAGE_TYPES.JOB_CREATED) {
22+
if (activeWorkerJobs === 0) {
23+
hasActiveWorkerJobs = pDefer<void>()
24+
}
25+
activeWorkerJobs++
1926
store
2027
.dispatch(internalActions.createJobV2FromInternalJob(msg.payload))
2128
.then(result => {
@@ -42,10 +49,19 @@ export function initJobsMessagingInMainProcess(
4249
workerId
4350
)
4451
})
52+
.finally(() => {
53+
if (--activeWorkerJobs === 0) {
54+
hasActiveWorkerJobs?.resolve()
55+
hasActiveWorkerJobs = null
56+
}
57+
})
4558
}
4659
})
4760
}
4861

62+
export const waitUntilWorkerJobsAreComplete = (): Promise<void> =>
63+
hasActiveWorkerJobs ? hasActiveWorkerJobs.promise : Promise.resolve()
64+
4965
/**
5066
* This map is ONLY used in worker. It's purpose is to keep track of promises returned to plugins
5167
* when creating jobs (in worker context), so that we can resolve or reject those once main process

0 commit comments

Comments
 (0)