Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
27 changes: 19 additions & 8 deletions packages/core/src/storages/batched-adds.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,32 +114,43 @@ export async function drainRequestBatches<TItem extends Source>(
return buildResult(addedRequests, Promise.resolve([]));
}

// Under `deferred` a writer that finishes after commit would have nowhere to put its journal entries.
const awaitsRemainder = waitForAllRequestsToBeAdded || deferred;

const backgroundFailures: unknown[] = [];

const processRemainingChunks = async () => {
const added: ProcessedRequest[] = [];
for await (const chunk of chunks) {
added.push(...(await addChunk(chunk, false)));
try {
added.push(...(await addChunk(chunk, false)));
} catch (error) {
if (awaitsRemainder) throw error;
// Nobody is waiting for this chunk, and losing it must not cost the ones after it.
log.exception(error as Error, 'A batch of requests could not be added to the queue in the background');
backgroundFailures.push(error);
}
// Under `deferred` no chunk performs backend I/O, so pacing them would only stall the handler.
await sleep(deferred ? 0 : waitBetweenBatchesMillis);
}
// Whoever does await the remainder still learns that it was not added in full.
if (backgroundFailures.length > 0) throw backgroundFailures[0];

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

return added;
};

// Under `deferred` a writer that finishes after commit would have nowhere to put its journal entries.
const awaitsRemainder = waitForAllRequestsToBeAdded || deferred;

// An un-awaited writer outlives the transaction scope it inherits, so it must not record into a
// transaction that may already be closed. It writes directly - its write-through additions were never
// going to be rolled back anyway - which means the requests it adds are not journaled.
// See `StorageTransactionView.enqueuedUrls`.
const remainder = awaitsRemainder ? processRemainingChunks() : withDirectStorageAccess(processRemainingChunks);

// The caller is not obliged to await `remainder`, so give it a handler of its own - an unhandled
// rejection here would otherwise take the process down. Awaited failures reach the caller, so only
// background ones get logged.
// rejection here would otherwise take the process down. Awaited failures reach the caller, and failed
// chunks are logged as they happen, so what is left to log here is a failure of the input iterable.
trackBackgroundBatches?.(
remainder.catch((error) => {
if (!awaitsRemainder) {
log.exception(error as Error, 'A batch of requests could not be added to the queue in the background');
if (!awaitsRemainder && !backgroundFailures.includes(error)) {
log.exception(error as Error, 'Adding requests to the queue in the background failed');
}
}),
);
Expand Down
22 changes: 14 additions & 8 deletions test/core/storages/batched-adds.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,23 +4,26 @@ import { describe, expect, it, vitest } from 'vitest';
import { drainRequestBatches } from '../../../packages/core/src/storages/batched-adds.js';
import type { CrawleeLogger } from '../../../packages/core/src/log.js';

async function* twoItems() {
async function* threeItems() {
yield { url: 'https://example.com/1' };
yield { url: 'https://example.com/2' };
yield { url: 'https://example.com/3' };
}

function setup(waitForAllRequestsToBeAdded: boolean) {
const exception = vitest.fn();
let tracked: Promise<unknown> | undefined;
const processedUrls: string[] = [];

const result = drainRequestBatches({
items: twoItems(),
items: threeItems(),
batchSize: 1,
waitBetweenBatchesMillis: 0,
waitForAllRequestsToBeAdded,
log: { exception } as unknown as CrawleeLogger,
processChunk: async (chunk, isInitial) => {
if (!isInitial) throw new Error('boom');
processChunk: async (chunk) => {
if (chunk[0].url.endsWith('/2')) throw new Error('boom');
processedUrls.push(chunk[0].url);
return chunk.map((): ProcessedRequest => ({
uniqueKey: '',
requestId: '',
Expand All @@ -33,16 +36,19 @@ function setup(waitForAllRequestsToBeAdded: boolean) {
},
});

return { exception, result, tracked: () => tracked };
return { exception, result, tracked: () => tracked, processedUrls };
}

describe('drainRequestBatches', () => {
it('logs a failed background batch', async () => {
const { exception, result, tracked } = setup(false);
it('logs a failed background batch, still adds the ones after it, and rejects at the end', async () => {
const { exception, result, tracked, processedUrls } = setup(false);

expect((await result).addedRequests).toHaveLength(1);
const { addedRequests, waitForAllRequestsToBeAdded } = await result;
expect(addedRequests).toHaveLength(1);
await expect(waitForAllRequestsToBeAdded).rejects.toThrow('boom');
await tracked();

expect(processedUrls).toEqual(['https://example.com/1', 'https://example.com/3']);
expect(exception).toHaveBeenCalledOnce();
});

Expand Down
Loading