fix(update): recover from GitHub rate limits with configurable mirrors

This commit is contained in:
手瓜一十雪 committed 2026-10-18 19:41:02 +08:00
1 parent 68deb48811
commit 20cf7394e5
21 files changed
+1423 -93

No files matched your search

+104 -1
View File
@@ -5,10 +5,14 @@ import path from 'node:path';
import { zipSync } from 'fflate';
import { c as createTar } from 'tar';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { archivePath, assetName, downloadUpdate } from '../src/update/download';
import { archivePath, assetName, downloadUpdate as download } from '../src/update/download';
import { readManifest } from '../src/update/files';
import { releaseFixture } from './helpers/update-fixture';
const direct = { mode: 'direct', mirror: '', mirrors: [] } as const;
const downloadUpdate = (directory: string, version: string, target: string) =>
download(directory, version, target, { ...direct, mirrors: [] });
let root: string;
beforeEach(async () => {
root = await mkdtemp(path.join(os.tmpdir(), 'snowluma-download-test-'));
@@ -43,6 +47,105 @@ function mockRelease(bytes: Uint8Array, target: string, digest?: string) {
}
describe('release downloads', () => {
it.each(['403', 'html', 'corrupt', 'interrupted'])(
'cleans and retries a %s response through a mirror using HTML release checksums',
async (failure) => {
const manifest = await releaseFixture(path.join(root, 'source'), '2.0.0', 'win32-x64');
const bytes = zipSync({
'release.json': new TextEncoder().encode(JSON.stringify(manifest)),
'app.mjs': new TextEncoder().encode('verified payload'),
});
const name = assetName('2.0.0', 'win32-x64');
const digest = createHash('sha256').update(bytes).digest('hex');
const fetchMock = vi.fn<typeof fetch>(async (input) => {
const url = String(input);
if (url.includes('api.github.com')) {
return new Response('rate limited', { status: 403 });
}
if (url.includes('/expanded_assets/')) {
return new Response(
`<li><a href="/SnowLuma/SnowLuma/releases/download/v2.0.0/${name}">asset</a><clipboard-copy value="sha256:${digest}"></clipboard-copy></li>`,
);
}
if (url.startsWith('https://working.example/')) {
// Mirrors may stream a verified archive without Content-Length.
return new Response(new Uint8Array(bytes));
}
if (failure === '403') {
return new Response('blocked', { status: 403 });
}
if (failure === 'html') {
return new Response('<html>challenge</html>', {
headers: { 'Content-Type': 'text/html' },
});
}
if (failure === 'interrupted') {
let sent = false;
return new Response(
new ReadableStream({
pull(controller) {
if (sent) {
controller.error(new Error('connection reset'));
} else {
controller.enqueue(new Uint8Array([1, 2, 3]));
sent = true;
}
},
}),
);
}
return new Response('corrupt archive');
});
vi.stubGlobal('fetch', fetchMock);
await download(root, '2.0.0', 'win32-x64', {
mode: 'auto',
mirror: '',
mirrors: ['https://working.example'],
});
expect(await readFile(path.join(root, 'archive'))).toEqual(Buffer.from(bytes));
expect(await readFile(path.join(root, 'payload/app.mjs'), 'utf8')).toBe(
'verified payload',
);
expect(
fetchMock.mock.calls
.filter(([url]) => String(url).includes('/download/'))
.map(([url]) => String(url)),
).toEqual([
`https://github.com/SnowLuma/SnowLuma/releases/download/v2.0.0/${name}`,
`https://working.example/https://github.com/SnowLuma/SnowLuma/releases/download/v2.0.0/${name}`,
]);
},
);
it('does not try other download sources in pinned mode', async () => {
const bytes = new Uint8Array([1, 2, 3]);
const fetchMock = mockRelease(bytes, 'win32-x64');
const original = fetchMock.getMockImplementation()!;
fetchMock.mockImplementation(async (input) =>
String(input).includes('api.github.com')
? original(input)
: new Response('blocked', { status: 403 }),
);
await expect(
download(root, '2.0.0', 'win32-x64', {
mode: 'mirror',
mirror: 'https://pinned.example',
mirrors: ['https://other.example'],
}),
).rejects.toThrow('HTTP 403');
expect(fetchMock.mock.calls.map(([url]) => url)).toEqual([
'https://api.github.com/repos/SnowLuma/SnowLuma/releases/tags/v2.0.0',
`https://pinned.example/https://github.com/SnowLuma/SnowLuma/releases/download/v2.0.0/${assetName('2.0.0', 'win32-x64')}`,
]);
expect(await readdir(root)).toEqual([]);
});
it.each(['win32-x64', 'linux-x64', 'linux-arm64'])(
'downloads and validates the %s lite package',
async (target) => {
+126
View File
@@ -0,0 +1,126 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import type { UpdateSourceConfig } from '@snowluma/common/update-source';
import {
assetName,
fetchRelease,
parseLatestReleasePage,
parseReleaseAssetsPage,
} from '../src/update/release';
const direct: UpdateSourceConfig = { mode: 'direct', mirror: '', mirrors: [] };
const latest =
'<meta property="og:url" content="https://github.com/SnowLuma/SnowLuma/releases/tag/v2.0.1">';
const digest = `sha256:${'a'.repeat(64)}`;
const name = assetName('2.0.1', 'win32-x64');
const row = `<li><a href="/SnowLuma/SnowLuma/releases/download/v2.0.1/${name}">${name}</a><clipboard-copy value="${digest}"></clipboard-copy></li>`;
afterEach(() => vi.unstubAllGlobals());
describe('existing GitHub release pages', () => {
it('reads the canonical stable release without a new metadata asset', () => {
expect(parseLatestReleasePage(latest)).toEqual({
tag_name: 'v2.0.1',
html_url: 'https://github.com/SnowLuma/SnowLuma/releases/tag/v2.0.1',
});
expect(parseLatestReleasePage(latest.replace('https://github.com', '')).tag_name).toBe(
'v2.0.1',
);
});
it.each([
'<html>please sign in</html>',
latest.replace('github.com', 'unrelated.example'),
latest.replace('/SnowLuma/SnowLuma/', '/other/project/'),
latest.replace('v2.0.1', 'v02.0.1'),
latest.replace('v2.0.1', 'v2.0.1-rc.1'),
])('rejects non-release or invalid version pages', (html) => {
expect(() => parseLatestReleasePage(html)).toThrow();
});
it('matches an asset with its own digest, ignoring rounded HTML sizes', () => {
expect(parseReleaseAssetsPage(row, '2.0.1')).toEqual({
tag_name: 'v2.0.1',
assets: [{ name, size: null, digest }],
});
});
it.each([
row.replace('v2.0.1/', 'v2.0.0/'),
row.replace(digest, 'unavailable'),
row + row,
row.replace(`<clipboard-copy value="${digest}"></clipboard-copy>`, '') +
`<li><clipboard-copy value="${digest}"></clipboard-copy></li>`,
])('rejects absent, ambiguous or neighbouring checksum data', (html) => {
expect(() => parseReleaseAssetsPage(html, '2.0.1')).toThrow();
});
it('falls back from API 403 to the existing release page', async () => {
const fetchMock = vi.fn<typeof fetch>(async (url) =>
String(url).includes('api.github.com')
? new Response('rate limited', { status: 403 })
: new Response(latest),
);
vi.stubGlobal('fetch', fetchMock);
expect(await fetchRelease(undefined, direct)).toMatchObject({
fromPage: true,
data: { tag_name: 'v2.0.1' },
});
expect(fetchMock.mock.calls.map(([url]) => url)).toEqual([
'https://api.github.com/repos/SnowLuma/SnowLuma/releases/latest',
'https://github.com/SnowLuma/SnowLuma/releases/latest',
]);
});
it('waits for a valid mirror page after fast invalid responses and cancels other requests', async () => {
let finish!: (response: Response) => void;
const pending = new Promise<Response>((resolve) => {
finish = resolve;
});
const fetchMock = vi.fn<typeof fetch>(async (url) => {
if (String(url).startsWith('https://working.example/')) {
return pending;
}
return new Response('HTML challenge');
});
vi.stubGlobal('fetch', fetchMock);
const result = fetchRelease('2.0.1', {
...direct,
mode: 'auto',
mirrors: ['https://bad.example', 'https://working.example'],
});
await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(4));
finish(new Response(row));
expect(await result).toMatchObject({
fromPage: true,
data: { assets: [{ name, digest }] },
});
expect(fetchMock.mock.calls.slice(1).every(([, options]) => options?.signal?.aborted)).toBe(
true,
);
});
it('keeps direct release lookup when the pinned download mirror cannot serve pages', async () => {
const fetchMock = vi.fn<typeof fetch>(async (url) =>
String(url) === 'https://github.com/SnowLuma/SnowLuma/releases/latest'
? new Response(latest)
: new Response('blocked', { status: 403 }),
);
vi.stubGlobal('fetch', fetchMock);
expect(
await fetchRelease(undefined, {
...direct,
mode: 'mirror',
mirror: 'https://files.example',
}),
).toMatchObject({ data: { tag_name: 'v2.0.1' } });
});
it('rejects oversized release responses', async () => {
vi.stubGlobal(
'fetch',
vi.fn(async () => new Response('x'.repeat(1024 * 1024 + 1))),
);
await expect(fetchRelease(undefined, direct)).rejects.toThrow('发布信息过大');
});
});
@@ -0,0 +1,105 @@
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { readRuntimeConfig, updateRuntimeConfig } from '@snowluma/common/runtime';
import { createUpdateService } from '../src/update/service';
import { updateRoutes } from '../src/webui/update-routes';
let directory: string;
let previous: string;
beforeEach(() => {
directory = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-update-sources-'));
previous = process.cwd();
process.chdir(directory);
});
afterEach(() => {
process.chdir(previous);
vi.restoreAllMocks();
vi.unstubAllGlobals();
fs.rmSync(directory, { recursive: true, force: true });
});
async function routes() {
return updateRoutes(await createUpdateService(undefined, '2.0.1'), vi.fn());
}
describe('update source routes', () => {
it('returns a JSON error when persisted source settings are invalid', async () => {
fs.mkdirSync('config');
fs.writeFileSync(
'config/runtime.json',
JSON.stringify({ updateSource: { mode: 'invalid' } }),
);
const response = await (await routes()).request('/sources');
expect(response.status).toBe(500);
expect(response.headers.get('content-type')).toContain('application/json');
expect(await response.json()).toMatchObject({
message: expect.stringContaining('模式无效'),
});
});
it('persists settings for subsequent reads without changing other runtime values', async () => {
updateRuntimeConfig({ webuiPort: 6789, webuiHost: '127.0.0.2' });
const app = await routes();
const config = {
mode: 'mirror',
mirror: 'https://example.com/proxy/',
mirrors: ['https://second.example/'],
};
const response = await app.request('/sources', {
method: 'POST',
body: JSON.stringify(config),
});
expect(response.status).toBe(200);
const normalized = {
...config,
mirror: 'https://example.com/proxy',
mirrors: ['https://second.example'],
};
expect(await response.json()).toMatchObject({
config: normalized,
saved: true,
applied: true,
errors: [],
});
expect(readRuntimeConfig()).toMatchObject({
updateSource: normalized,
webuiPort: 6789,
webuiHost: '127.0.0.2',
});
expect(await (await app.request('/sources')).json()).toEqual({ config: normalized });
});
it.each(['not json', '{}', '[]', '{"mode":"mirror","mirrors":[]}'])(
'rejects malformed input without saving or fetching: %s',
async (body) => {
const fetchMock = vi.fn();
vi.stubGlobal('fetch', fetchMock);
const app = await routes();
for (const endpoint of ['/sources', '/sources/test']) {
expect((await app.request(endpoint, { method: 'POST', body })).status).toBe(400);
}
expect(fetchMock).not.toHaveBeenCalled();
expect(fs.existsSync('config/runtime.json')).toBe(false);
},
);
it('reports a persistence failure without claiming the config was saved', async () => {
updateRuntimeConfig({ webuiPort: 6789 });
const before = fs.readFileSync('config/runtime.json', 'utf8');
vi.spyOn(fs, 'renameSync').mockImplementationOnce(() => {
throw new Error('disk replacement failed');
});
const response = await (
await routes()
).request('/sources', {
method: 'POST',
body: JSON.stringify({ mode: 'direct', mirror: '', mirrors: [] }),
});
expect(response.status).toBe(500);
expect(await response.json()).toEqual({ message: 'disk replacement failed' });
expect(fs.readFileSync('config/runtime.json', 'utf8')).toBe(before);
});
});
@@ -0,0 +1,81 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { DEFAULT_UPDATE_SOURCE, sourceUrls, testUpdateSources } from '../src/update/sources';
import type { UpdateSourceConfig } from '@snowluma/common/update-source';
const config: UpdateSourceConfig = {
mode: 'auto',
mirror: '',
mirrors: [
'https://good.example',
'https://html.example',
'https://fake.example',
'https://failed.example',
],
};
afterEach(() => vi.unstubAllGlobals());
describe('update mirror selection', () => {
it('uses direct, ordered fallback or only the pinned mirror for downloads', () => {
const url = 'https://github.com/project/asset';
expect(sourceUrls(url, config)).toEqual([
url,
...config.mirrors.map((mirror) => `${mirror}/${url}`),
]);
expect(sourceUrls(url, { ...config, mode: 'direct' })).toEqual([url]);
expect(
sourceUrls(url, { ...config, mode: 'mirror', mirror: 'https://pinned.example/proxy' }),
).toEqual([`https://pinned.example/proxy/${url}`]);
expect(DEFAULT_UPDATE_SOURCE.mirrors.length).toBeGreaterThanOrEqual(7);
});
it('probes actual archive prefixes, rejects HTML even with a binary content type, and cancels bodies', async () => {
const cancelled = vi.fn();
const signature =
process.platform === 'win32' ? [0x50, 0x4b, 0x03, 0x04] : [0x1f, 0x8b, 0x08, 0];
const fetchMock = vi.fn<typeof fetch>(async (url) => {
if (String(url).startsWith('https://html.example')) {
return new Response('<html>blocked</html>', {
headers: { 'Content-Type': 'text/html' },
});
}
if (String(url).startsWith('https://fake.example')) {
return new Response('<html>blocked</html>', {
headers: { 'Content-Type': 'application/octet-stream' },
});
}
if (String(url).startsWith('https://failed.example')) {
return new Response('blocked', { status: 403 });
}
return new Response(
new ReadableStream({
start(controller) {
controller.enqueue(new Uint8Array(signature));
},
cancel: cancelled,
}),
);
});
vi.stubGlobal('fetch', fetchMock);
const results = await testUpdateSources(config);
expect(
results
.filter((result) => result.available)
.map((result) => result.mirror)
.sort(),
).toEqual(['', 'https://good.example']);
expect(results.filter((result) => !result.available)).toHaveLength(3);
expect(results.at(-1)?.available).toBe(false);
expect(cancelled).toHaveBeenCalledTimes(2);
expect(
fetchMock.mock.calls.every(
([, options]) =>
options?.headers &&
'Range' in options.headers &&
options.headers.Range === 'bytes=0-3',
),
).toBe(true);
});
});
+23 -9
View File
@@ -1,5 +1,8 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { getUpdateInfo } from '../src/update/check';
import { getUpdateInfo as checkUpdate } from '../src/update/check';
const getUpdateInfo = (force = false) =>
checkUpdate(force, { mode: 'direct', mirror: '', mirrors: [] });
const LATEST_RELEASE_URL = 'https://api.github.com/repos/SnowLuma/SnowLuma/releases/latest';
const NOTES_MAX = 4_000;
@@ -85,7 +88,7 @@ describe('getUpdateInfo', () => {
htmlUrl: null,
notes: null,
publishedAt: null,
error: 'ECONNRESET',
error: expect.stringContaining('ECONNRESET'),
});
fetchMock.mockImplementation(async () => jsonResponse({ tag_name: 'v1.0.0' }));
@@ -93,7 +96,7 @@ describe('getUpdateInfo', () => {
expect(ok.latest).toBe('1.0.0');
expect(ok.hasUpdate).toBe(true);
expect(ok.error).toBeUndefined();
expect(fetchMock).toHaveBeenCalledTimes(2);
expect(fetchMock).toHaveBeenCalledTimes(3);
});
it.each(['', '1', 'true', 'yes', 'on', ' '] as const)(
@@ -190,7 +193,7 @@ describe('getUpdateInfo', () => {
htmlUrl: null,
notes: null,
publishedAt: null,
error: 'github 403',
error: expect.stringContaining('GitHub 403'),
});
});
@@ -230,7 +233,7 @@ describe('getUpdateInfo', () => {
throw new Error('getaddrinfo ENOTFOUND');
});
const result = await getUpdateInfo(true);
expect(result.error).toBe('getaddrinfo ENOTFOUND');
expect(result.error).toContain('getaddrinfo ENOTFOUND');
expect(result.hasUpdate).toBe(false);
});
@@ -239,7 +242,7 @@ describe('getUpdateInfo', () => {
throw 'timeout';
});
const result = await getUpdateInfo(true);
expect(result.error).toBe('network error');
expect(result.error).toContain('timeout');
expect(result.hasUpdate).toBe(false);
});
@@ -257,7 +260,7 @@ describe('getUpdateInfo', () => {
throw new Error('boom');
});
await expect(getUpdateInfo(true)).resolves.toMatchObject({
error: 'boom',
error: expect.stringContaining('boom'),
hasUpdate: false,
});
});
@@ -298,12 +301,12 @@ describe('getUpdateInfo', () => {
throw new Error('boom');
});
const bad = await getUpdateInfo(true);
expect(bad.error).toBe('boom');
expect(bad.error).toContain('boom');
const cached = await getUpdateInfo();
expect(cached).toBe(good);
expect(cached.error).toBeUndefined();
expect(fetchMock).toHaveBeenCalledTimes(2);
expect(fetchMock).toHaveBeenCalledTimes(3);
});
it('collapses concurrent checks onto one fetch', async () => {
@@ -332,4 +335,15 @@ describe('getUpdateInfo', () => {
});
expect(fetchMock).toHaveBeenCalledTimes(1);
});
it('does not reuse the previous source configuration cache after a mirror change', async () => {
const source = { mode: 'auto', mirror: '', mirrors: ['https://first.example'] } as const;
const fetchMock = mockFetch(async () => jsonResponse({ tag_name: 'v3.0.0' }));
const first = await checkUpdate(false, { ...source, mirrors: [...source.mirrors] });
fetchMock.mockImplementation(async () => jsonResponse({ tag_name: 'v3.0.1' }));
const second = await checkUpdate(false, { ...source, mirrors: ['https://second.example'] });
expect(first.latest).toBe('3.0.0');
expect(second.latest).toBe('3.0.1');
expect(fetchMock).toHaveBeenCalledTimes(2);
});
});