Skip to content

Commit 72aacb4

Browse files
fix(impit-client): pause fromWeb stream to prevent early consumption (#3347)
Attaching a 'data' listener on Readable.fromWeb(response.body) switches the stream into flowing mode. This can start consuming the response body before Crawlee attaches its pipeline consumer, so initial chunks are lost and the downstream sees a truncated stream. That also aswers why only retries worked. Fix: call responseStream.pause() right after registering the 'data' handler. The stream stays paused until the pipeline/pipe attaches and resumes it, preventing early consumption while still allowing progress tracking. Closes [WCC issue #555](apify/store-website-content-crawler#555)
1 parent a978ab3 commit 72aacb4

1 file changed

Lines changed: 16 additions & 11 deletions

File tree

packages/impit-client/src/index.ts

Lines changed: 16 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { Readable } from 'node:stream';
1+
import { pipeline, Readable, Transform } from 'node:stream';
22
import { type ReadableStream } from 'node:stream/web';
33
import { isGeneratorObject } from 'node:util/types';
44

@@ -210,19 +210,24 @@ export class ImpitHttpClient implements BaseHttpClient {
210210
const responseStream = Readable.fromWeb(response.body as ReadableStream<any>);
211211
let transferred = 0;
212212
const total = Number(response.headers.get('content-length') ?? 0);
213-
responseStream.on('data', (chunk) => {
214-
transferred += chunk.length;
213+
const counter = new Transform({
214+
transform(chunk, _enc, cb) {
215+
transferred += chunk.length;
216+
cb(null, chunk);
217+
},
215218
});
216219

217-
const getDownloadProgress = () => {
218-
return {
219-
percent: Math.round((transferred / total) * 100),
220-
transferred,
221-
total,
222-
};
223-
};
220+
pipeline(responseStream, counter, (err) => {
221+
if (err) counter.destroy(err);
222+
});
223+
224+
const getDownloadProgress = () => ({
225+
percent: total > 0 ? Math.round((transferred / total) * 100) : 0,
226+
transferred,
227+
total,
228+
});
224229

225-
return [responseStream, getDownloadProgress];
230+
return [counter, getDownloadProgress];
226231
}
227232

228233
/**

0 commit comments

Comments
 (0)