Skip to content

armgit / Pake

Public Imported from GitHub
0

Turn any website into a lightweight desktop app with one command, on macOS, Windows and Linux.

fix: cancel in-flight icon downloads with builds

yuxino891521b49993
diff --git a/bin/options/icon.ts b/bin/options/icon.ts
index 4eeed823..617eb5df 100644
--- a/bin/options/icon.ts
+++ b/bin/options/icon.ts
@@ -16,6 +16,10 @@ import {
} from '@/utils/icon-source';
import { generateLinuxPackageName, getSafeAppName } from '@/utils/name';
import { PakeAppOptions } from '@/types';
+import {
+ getBuildCancellationSignal,
+ throwIfBuildCancelled,
+} from '@/utils/build-workspace';
import {
ensureMultiResolutionIco,
writeIcoWithPreferredSize,
@@ -609,6 +613,7 @@ async function tryResolveIconSource(
return resolvedPath;
}
} catch (error: unknown) {
+ throwIfBuildCancelled();
if (error instanceof Error) {
const label =
source === 'dashboard' ? 'Dashboard icon' : 'Icon service';
@@ -627,9 +632,10 @@ async function tryGetFavicon(
url: string,
appName: string,
): Promise<string | null> {
+ let spinner: ReturnType<typeof getSpinner> | undefined;
try {
const domain = new URL(url).hostname;
- const spinner = getSpinner(`Fetching icon from ${domain}...`);
+ spinner = getSpinner(`Fetching icon from ${domain}...`);
const isCI =
process.env.CI === 'true' || process.env.GITHUB_ACTIONS === 'true';
@@ -662,10 +668,13 @@ async function tryGetFavicon(
spinner.warn(`No favicon found for ${domain}. Using default.`);
return null;
} catch (error) {
+ throwIfBuildCancelled();
if (error instanceof Error) {
logger.warn(`Failed to fetch favicon: ${error.message}`);
}
return null;
+ } finally {
+ spinner?.stop();
}
}
@@ -677,6 +686,8 @@ export async function downloadIcon(
showSpinner = true,
customTimeout?: number,
): Promise<string | null> {
+ throwIfBuildCancelled();
+ const buildSignal = getBuildCancellationSignal();
const controller = new AbortController();
const timeoutId = setTimeout(() => {
controller.abort();
@@ -684,7 +695,9 @@ export async function downloadIcon(
try {
const response = await fetch(iconUrl, {
- signal: controller.signal,
+ signal: buildSignal
+ ? AbortSignal.any([controller.signal, buildSignal])
+ : controller.signal,
});
if (!response.ok) {
@@ -710,6 +723,7 @@ export async function downloadIcon(
return await saveIconFile(arrayBuffer, extension);
} catch (error: unknown) {
+ throwIfBuildCancelled();
if (showSpinner) {
if (error instanceof Error && error.name === 'AbortError') {
logger.error('Icon download timed out!');
diff --git a/dist/cli.js b/dist/cli.js
index 83fc0a3e..1872670a 100644
--- a/dist/cli.js
+++ b/dist/cli.js
@@ -3291,6 +3291,7 @@ async function tryResolveIconSource(source, domain, appName, downloadTimeout) {
}
}
catch (error) {
+ throwIfBuildCancelled();
if (error instanceof Error) {
const label = source === 'dashboard' ? 'Dashboard icon' : 'Icon service';
logger.debug(`${label} ${iconUrl} failed: ${error.message}`);
@@ -3303,9 +3304,10 @@ async function tryResolveIconSource(source, domain, appName, downloadTimeout) {
* Attempts to fetch favicon from website
*/
async function tryGetFavicon(url, appName) {
+ let spinner;
try {
const domain = new URL(url).hostname;
- const spinner = getSpinner(`Fetching icon from ${domain}...`);
+ spinner = getSpinner(`Fetching icon from ${domain}...`);
const isCI = process.env.CI === 'true' || process.env.GITHUB_ACTIONS === 'true';
const downloadTimeout = isCI
? ICON_CONFIG.downloadTimeout.ci
@@ -3325,23 +3327,31 @@ async function tryGetFavicon(url, appName) {
return null;
}
catch (error) {
+ throwIfBuildCancelled();
if (error instanceof Error) {
logger.warn(`Failed to fetch favicon: ${error.message}`);
}
return null;
}
+ finally {
+ spinner?.stop();
+ }
}
/**
* Downloads icon from URL
*/
async function downloadIcon(iconUrl, showSpinner = true, customTimeout) {
+ throwIfBuildCancelled();
+ const buildSignal = getBuildCancellationSignal();
const controller = new AbortController();
const timeoutId = setTimeout(() => {
controller.abort();
}, customTimeout || 10000);
try {
const response = await fetch(iconUrl, {
- signal: controller.signal,
+ signal: buildSignal
+ ? AbortSignal.any([controller.signal, buildSignal])
+ : controller.signal,
});
if (!response.ok) {
if (response.status === 404 && !showSpinner) {
@@ -3359,6 +3369,7 @@ async function downloadIcon(iconUrl, showSpinner = true, customTimeout) {
return await saveIconFile(arrayBuffer, extension);
}
catch (error) {
+ throwIfBuildCancelled();
if (showSpinner) {
if (error instanceof Error && error.name === 'AbortError') {
logger.error('Icon download timed out!');
diff --git a/tests/unit/icon.test.ts b/tests/unit/icon.test.ts
index 5a98b1e7..19fc86b7 100644
--- a/tests/unit/icon.test.ts
+++ b/tests/unit/icon.test.ts
@@ -11,8 +11,10 @@ vi.mock('execa', () => ({
execa: execaMock,
}));
-import { downloadIcon, generateMacOSIcns } from '@/options/icon';
+import { downloadIcon, generateMacOSIcns, handleIcon } from '@/options/icon';
import { getIconSourcePriority } from '@/utils/icon-source';
+import { beginBuildCancellation } from '@/utils/build-workspace';
+import { DEFAULT_PAKE_OPTIONS } from '@/defaults';
const downloadedIconPaths: string[] = [];
const generatedIconDirs: string[] = [];
@@ -41,6 +43,69 @@ it('keeps the download deadline active until the response body completes', async
}
});
+it.each(['SIGINT', 'SIGTERM'] as const)(
+ 'cancels an in-flight icon response on %s',
+ async (signal) => {
+ let requestStarted!: () => void;
+ const started = new Promise<void>((resolve) => {
+ requestStarted = resolve;
+ });
+ const server = http.createServer((_request, response) => {
+ response.writeHead(200, { 'content-type': 'image/png' });
+ response.flushHeaders();
+ requestStarted();
+ });
+ await new Promise<void>((resolve) =>
+ server.listen(0, '127.0.0.1', resolve),
+ );
+ const endCancellation = beginBuildCancellation();
+ try {
+ const port = (server.address() as import('net').AddressInfo).port;
+ const download = downloadIcon(
+ `http://127.0.0.1:${port}/icon`,
+ false,
+ 2000,
+ );
+ const cancelled = expect(download).rejects.toThrow(
+ `Build cancelled (${signal}).`,
+ );
+ await started;
+ const cancelledAt = performance.now();
+ process.emit(signal, signal);
+ await cancelled;
+ expect(performance.now() - cancelledAt).toBeLessThan(1000);
+ } finally {
+ endCancellation();
+ server.closeAllConnections();
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+ }
+ },
+);
+
+it('does not try another favicon source after the build is cancelled', async () => {
+ const endCancellation = beginBuildCancellation();
+ const fetchMock = vi.fn(async () => {
+ process.emit('SIGINT', 'SIGINT');
+ throw new Error('Request interrupted');
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ try {
+ await expect(
+ handleIcon(
+ {
+ ...DEFAULT_PAKE_OPTIONS,
+ name: 'CancelProbe',
+ identifier: 'com.pake.cancelprobe',
+ },
+ 'https://example.com',
+ ),
+ ).rejects.toThrow('Build cancelled (SIGINT).');
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ } finally {
+ endCancellation();
+ }
+});
+
afterEach(() => {
vi.unstubAllGlobals();
vi.restoreAllMocks();