Skip to content
Merged
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
39 changes: 23 additions & 16 deletions src/core/chunked_stream.js
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,7 @@ class ChunkedStream extends Stream {
}

class ChunkedStreamManager {
#aborted = false;
#abortReason = null;

#requestId = 0;

Expand Down Expand Up @@ -281,7 +281,7 @@ class ChunkedStreamManager {
while (true) {
const { value, done } = await rangeReader.read();

if (this.#aborted) {
if (this.#abortReason) {
chunks = null;
return; // Ignoring any data after abort.
}
Expand Down Expand Up @@ -312,14 +312,18 @@ class ChunkedStreamManager {
* contiguous ranges to load in as few requests as possible.
*/
requestAllChunks(noFetch = false) {
if (!noFetch) {
if (!noFetch && !this.#abortReason) {
const missingChunks = this.stream.getMissingChunks();
this._requestChunks(missingChunks);
this.#requestChunks(missingChunks);
}
return this.#loadedStreamCapability.promise;
}

_requestChunks(chunks) {
#requestChunks(chunks) {
if (this.#abortReason) {
return Promise.reject(this.#abortReason);
}

const chunksNeeded = new Set();
for (const chunk of chunks) {
if (!this.stream.hasChunk(chunk)) {
Expand Down Expand Up @@ -360,12 +364,10 @@ class ChunkedStreamManager {
}
}

return capability.promise.catch(reason => {
if (this.#aborted) {
return; // Ignoring any pending requests after abort.
}
throw reason;
});
// Prevent "uncaught exception: Object"-messages in the console.
capability.promise.catch(() => {});

return capability.promise;
}

getStream() {
Expand All @@ -385,7 +387,7 @@ class ChunkedStreamManager {
for (let chunk = beginChunk; chunk < endChunk; ++chunk) {
chunks.push(chunk);
}
return this._requestChunks(chunks);
return this.#requestChunks(chunks);
}

requestRanges(ranges = []) {
Expand All @@ -401,7 +403,7 @@ class ChunkedStreamManager {
}

chunksToRequest.sort((a, b) => a - b);
return this._requestChunks(chunksToRequest);
return this.#requestChunks(chunksToRequest);
}

/**
Expand Down Expand Up @@ -476,7 +478,11 @@ class ChunkedStreamManager {

// If there are no pending requests, automatically fetch the next
// unfetched chunk of the PDF file.
if (!this.disableAutoFetch && this._requestsByChunk.size === 0) {
if (
!this.disableAutoFetch &&
!this._requestsByChunk.size &&
!this.#abortReason
) {
let nextEmptyChunk;
if (stream.numChunksLoaded === 1) {
// This is a special optimization so that after fetching the first
Expand All @@ -490,7 +496,7 @@ class ChunkedStreamManager {
nextEmptyChunk = stream.nextEmptyChunk(endChunk);
}
if (Number.isInteger(nextEmptyChunk)) {
this._requestChunks([nextEmptyChunk]);
this.#requestChunks([nextEmptyChunk]);
}
}

Expand Down Expand Up @@ -519,7 +525,8 @@ class ChunkedStreamManager {
}

abort(reason) {
this.#aborted = true;
assert(reason instanceof Error, "abort must have a valid reason");
this.#abortReason = reason;
this.pdfStream?.cancelAllRequests(reason);

for (const capability of this._promisesByRequest.values()) {
Expand Down
12 changes: 9 additions & 3 deletions src/core/worker.js
Original file line number Diff line number Diff line change
Expand Up @@ -1059,10 +1059,16 @@ class WorkerMessageHandler {

const waitOn = [];
if (pdfManager) {
pdfManager.terminate(new AbortException("Worker was terminated."));
// While `terminate` itself isn't asynchronous we need to allow some
// time for any pending `ChunkedStreamManager` request-Promises to be
// rejected *before* tearing down the document, since otherwise various
// API-methods may remain pending indefinitely. (Without this,
// the unit-test for issue 22051 hangs with Workers enabled.)
await pdfManager.terminate(
new AbortException("Worker was terminated.")
);

const cleanupPromise = pdfManager.cleanup();
waitOn.push(cleanupPromise);
waitOn.push(pdfManager.cleanup());

pdfManager = null;
} else {
Expand Down
95 changes: 95 additions & 0 deletions test/unit/api_spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
*/

import {
AbortException,
AnnotationEditorType,
AnnotationMode,
AnnotationType,
Expand Down Expand Up @@ -7451,6 +7452,100 @@ have written that much by now. So, here’s to squashing bugs.`);

await loadingTask.destroy();
});

it("should destroy document during a hanging range request (issue 22051)", async function () {
const initialDataLength = 80000; // Larger than `rangeChunkSize`, since otherwise it's pretty pointless.
const subArrays = [];
let fetches = 0;

const data = await dataPromise;
const dataLength = data.length;
const initialData = new Uint8Array(data.subarray(0, initialDataLength));
subArrays.push(initialData);

const transport = new PDFDataRangeTransport(
dataLength,
initialData,
/* progressiveDone = */ undefined,
/* contentDispositionFilename = */ "aaa.pdf"
);
transport.requestDataRange = async (begin, end) => {
fetches++;
if (fetches > 3) {
await loadingTask.destroy();
return;
}
waitSome(() => {
const chunk = new Uint8Array(data.subarray(begin, end));
subArrays.push(chunk);

transport.onDataRange(begin, chunk);
});
};

const loadingTask = getDocument({
range: transport,
rangeChunkSize: 65536,
});

const pdfDocument = await loadingTask.promise;
expect(pdfDocument.numPages).toEqual(14);

await expectAsync(pdfDocument.getPage(10)).toBeRejectedWithError(
AbortException,
"Worker was terminated."
);

expect(fetches).toEqual(4);
});

it("should destroy document during a pending range request, with auto-fetching enabled", async function () {
const initialDataLength = 80000; // Larger than `rangeChunkSize`, since otherwise it's pretty pointless.
const subArrays = [];
let fetches = 0;
const abortCapability = Promise.withResolvers();
let loaded = false;

const data = await dataPromise;
const dataLength = data.length;
const initialData = new Uint8Array(data.subarray(0, initialDataLength));
subArrays.push(initialData);

const transport = new PDFDataRangeTransport(
dataLength,
initialData,
/* progressiveDone = */ undefined,
/* contentDispositionFilename = */ "aaa.pdf"
);
transport.requestDataRange = async (begin, end) => {
fetches++;
if (loaded) {
abortCapability.resolve();
return;
}
waitSome(() => {
const chunk = new Uint8Array(data.subarray(begin, end));
subArrays.push(chunk);

transport.onDataRange(begin, chunk);
});
};

const loadingTask = getDocument({
range: transport,
rangeChunkSize: 65536,
disableStream: true,
});

const pdfDocument = await loadingTask.promise;
expect(pdfDocument.numPages).toEqual(14);

loaded = true;
await abortCapability.promise;
await loadingTask.destroy();

expect(fetches).toEqual(6);
});
});

describe("Annotations", function () {
Expand Down
Loading