Skip to content

Commit 7aed264

Browse files
fix: make crawler terminal status message reliably delivered (apify#3733)
Fixes https://apify.slack.com/archives/CD0SF6KD4/p1780936657459989. If there is no other code after the crawler.run, it could just never spin the event loop to send the HTTP for status message. I tested the fix on a few hundred runs, and it worked every time. https://claude.ai/code/session_01PnJVep34w4Yzupcb3JzLJu --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 4225a19 commit 7aed264

1 file changed

Lines changed: 12 additions & 8 deletions

File tree

packages/basic-crawler/src/internals/basic-crawler.ts

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ import {
5555
validators,
5656
} from '@crawlee/core';
5757
import type { Awaitable, BatchAddRequestsResult, Dictionary, SetStatusMessageOptions } from '@crawlee/types';
58-
import { getObjectType, isAsyncIterable, isIterable, RobotsTxtFile, ROTATE_PROXY_ERRORS } from '@crawlee/utils';
58+
import { getObjectType, isAsyncIterable, isIterable, RobotsTxtFile, ROTATE_PROXY_ERRORS, sleep } from '@crawlee/utils';
5959
import { stringify } from 'csv-stringify/sync';
6060
import { ensureDir, writeFile, writeJSON } from 'fs-extra';
6161
import ow, { ArgumentError } from 'ow';
@@ -1082,13 +1082,17 @@ export class BasicCrawler<Context extends CrawlingContext = BasicCrawlingContext
10821082
}
10831083

10841084
periodicLogger.stop();
1085-
// Don't await, we don't want to block the execution
1086-
void this.setStatusMessage(
1087-
`Finished! Total ${this.stats.state.requestsFinished + this.stats.state.requestsFailed} requests: ${
1088-
this.stats.state.requestsFinished
1089-
} succeeded, ${this.stats.state.requestsFailed} failed.`,
1090-
{ isStatusMessageTerminal: true, level: 'INFO' },
1091-
);
1085+
// Give the event loop a single tick to flush the HTTP
1086+
// 1ms is enough because we already have a keep-alive connection to the API
1087+
await Promise.race([
1088+
this.setStatusMessage(
1089+
`Finished! Total ${this.stats.state.requestsFinished + this.stats.state.requestsFailed} requests: ${
1090+
this.stats.state.requestsFinished
1091+
} succeeded, ${this.stats.state.requestsFailed} failed.`,
1092+
{ isStatusMessageTerminal: true, level: 'INFO' },
1093+
),
1094+
sleep(1),
1095+
]);
10921096

10931097
this.running = false;
10941098
this.hasFinishedBefore = true;

0 commit comments

Comments
 (0)