Skip to content

Commit

Permalink
Use AbortSignal.any (#5565)
Browse files Browse the repository at this point in the history
  • Loading branch information
kamilkisiela authored Oct 5, 2024
1 parent b695d77 commit 0f57dce
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 28 deletions.
16 changes: 14 additions & 2 deletions packages/services/cdn-worker/src/artifact-storage-reader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -275,7 +275,7 @@ export class ArtifactStorageReader {
status: response.status,
headers: response.headers,
body: await response.text().catch(error => {
this.breadcrumb('Error reading response body: ' + String(error));
this.breadcrumb('Error reading response body: ' + stringifyError(error));
return Promise.reject(error);
}),
} as const;
Expand All @@ -285,7 +285,7 @@ export class ArtifactStorageReader {

const body = await response
.text()
.catch(error => 'Failed to read response body due to ' + String(error));
.catch(error => 'Failed to read response body due to ' + stringifyError(error));
throw new Error(`GET request failed with status ${response.status}: ${body}`);
}

Expand Down Expand Up @@ -438,3 +438,15 @@ class PendingRequestAbortedError extends Error {
this.name = 'PendingRequestAbortedError';
}
}

function stringifyError(error: unknown) {
if (error instanceof Error) {
return error.stack ?? error.message;
}

if (error instanceof Event || (error != null && typeof error === 'object' && 'type' in error)) {
return `Event: ${error.type}}`;
}

return String(error);
}
37 changes: 11 additions & 26 deletions packages/services/cdn-worker/src/aws.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,12 +138,19 @@ export class AwsClient {
}
const signer = new AwsV4Signer(Object.assign({ url: input }, init, this, init && init.aws));

const signals: AbortSignal[] = [];

if (init?.timeout) {
signals.push(AbortSignal.timeout(init.timeout));
}

if (init?.signal) {
signals.push(init.signal);
}

const signed = Object.assign(
{
signal: anySignal([
init?.timeout ? AbortSignal.timeout(init.timeout) : undefined,
init?.signal,
]),
signal: signals.length ? AbortSignal.any(signals) : undefined,
},
init,
await signer.sign(),
Expand Down Expand Up @@ -535,28 +542,6 @@ function guessServiceRegion(url: URL, headers: Headers) {
return [HOST_SERVICES[service] || service, region];
}

function anySignal(signals: Array<AbortSignal | undefined>) {
const controller = new AbortController();

function onAbort(reason: unknown) {
controller.abort(reason);
}

for (const signal of signals) {
if (!signal) {
continue;
}

if (signal.aborted) {
onAbort(signal.reason);
break;
}
signal.addEventListener('abort', onAbort);
}

return controller.signal;
}

class ResponseNotOkayError extends Error {
response: Response;

Expand Down

0 comments on commit 0f57dce

Please sign in to comment.