fix(updates): scan release channels across pages

Share a bounded release scan across channels and compare tag versions across pages. Report uncertainty when the scan hits its limit without confirming a newer release.

Verified with local release responses covering cross-page versions, truncation, and missing feeds.
This commit is contained in:
N0VAN0M4LY committed 2026-11-30 15:23:18 +08:00
1 parent 5a78b1fdf8
commit 31f4fedafe
11 files changed
+173 -101

No files matched your search

@@ -23,7 +23,7 @@ import {
import type { ActivePatchSet, PackApplyResult, PackCheck, PackProblem, PackRelease } from '@shared/schemas/patch-pack.ts';
import { bundledResourcePaths, usesDownloadedPacks } from '../resources/resource-paths.ts';
import { activeDownloadedPack, installPack, useBundledPatchSet } from './pack-store.ts';
import { downloadReleaseFile, FeedUnreachableError, newestPackRelease, type PackReleaseFiles } from './release-feed.ts';
import { downloadReleaseFile, FeedUnreachableError, newestProjectRelease, ReleasePageLimitError, type PackReleaseFiles } from './release-feed.ts';
/** The manifest copy beside a release is a few hundred bytes. */
const MANIFEST_COPY_MAX_BYTES = 64 * 1024;
@@ -41,7 +41,7 @@ export async function checkPackUpdate(): Promise<PackCheck> {
const active = activePatchSet();
if (!packSigningPublicKey()) return { status: 'failed', active, latest: null, problem: 'no_signing_key' };
try {
const found = await newestRelease();
const found = await newestRelease(active.version);
if (!found || !isNewer(found.manifest.version, active.version)) return { status: 'up_to_date', active, latest: found ? release(found) : null, problem: null };
const status = manifestIncompatibility(found.manifest, app.getVersion()) ? 'needs_app_update' : 'available';
return { status, active, latest: release(found), problem: null };
@@ -55,7 +55,7 @@ export async function checkPackUpdate(): Promise<PackCheck> {
export async function applyPackUpdate(): Promise<PackApplyResult> {
if (!packSigningPublicKey()) return { ok: false, problem: 'no_signing_key' };
try {
const found = await newestRelease();
const found = await newestRelease(activePatchSet().version);
if (!found || !isNewer(found.manifest.version, activePatchSet().version)) return { ok: false, problem: 'up_to_date' };
if (manifestIncompatibility(found.manifest, app.getVersion())) return { ok: false, problem: 'needs_app_update' };
const tuning = patchPackTuning();
@@ -81,8 +81,8 @@ interface FoundRelease {
readonly manifest: PatchPackManifest;
}
async function newestRelease(): Promise<FoundRelease | null> {
const files = await newestPackRelease();
async function newestRelease(installedVersion: string | null): Promise<FoundRelease | null> {
const files = await newestProjectRelease('pack', installedVersion);
if (!files) return null;
const text = new TextDecoder().decode(await downloadReleaseFile(files.manifestUrl, MANIFEST_COPY_MAX_BYTES));
const manifest = parseManifest(text);
@@ -116,6 +116,7 @@ function bundledVersion(root: string): string | null {
}
function problemOf(error: unknown): PackProblem {
if (error instanceof ReleasePageLimitError) return 'page_limit';
if (error instanceof FeedUnreachableError) return 'network';
if (error instanceof PatchPackError) {
if (error.problem === 'signature') return 'signature';
@@ -1,12 +1,21 @@
/**
* Adaptation pack releases on GitHub: the newest release tagged `patches-<version>` that carries
* all three files (zip, signature, manifest copy), and downloads of those files.
*
* Requests send no account, no cookie and nothing about the player; GitHub sees an anonymous
* request with a generic user agent.
* The launcher and adaptation pack channels share GitHub's public Releases list.
* Requests send no account, no cookie and nothing about the player.
*/
import { net } from 'electron';
import { comparePackVersions, packFileNames, packVersionOfTag, PatchPackError, patchPackTuning } from '@wto/patcher';
import {
compareAppVersions, comparePackVersions, packFileNames, packVersionOfTag, PatchPackError, patchPackTuning,
} from '@wto/patcher';
import { z } from 'zod';
import { AppReleaseVersionSchema, launcherReleaseFiles } from '@shared/schemas/app-update.ts';
export interface LauncherRelease {
readonly version: string;
readonly notes: string;
readonly installer: URL;
readonly manifest: URL;
readonly signature: URL;
}
export interface PackReleaseFiles {
readonly version: string;
@@ -16,44 +25,132 @@ export interface PackReleaseFiles {
readonly manifestUrl: string;
}
interface ReleaseCandidates {
launcher: LauncherRelease | null;
pack: PackReleaseFiles | null;
}
type ReleaseChannel = keyof ReleaseCandidates;
interface ReleaseListing {
readonly candidates: ReleaseCandidates;
readonly incomplete: Readonly<Partial<Record<ReleaseChannel, string>>>;
readonly pageLimit: number | null;
}
/** Thrown when GitHub cannot be reached or answers with an error. */
export class FeedUnreachableError extends Error {
override readonly name = 'FeedUnreachableError';
}
/** Thrown when the list ends at the configured page limit without finding a newer release. */
export class ReleasePageLimitError extends Error {
override readonly name = 'ReleasePageLimitError';
}
const HEADERS = { Accept: 'application/vnd.github+json', 'User-Agent': 'WTOffline-Launcher', 'X-GitHub-Api-Version': '2022-11-28' };
const LauncherReleaseEntry = z.object({
draft: z.literal(false),
prerelease: z.literal(false),
assets: z.array(z.object({ name: z.string() })),
body: z.string().nullable().optional(),
});
let listing: Promise<readonly unknown[]> | null = null;
let listing: Promise<ReleaseListing> | null = null;
/** Share the in-flight request when the launcher checks both release channels at startup. */
export function listProjectReleases(): Promise<readonly unknown[]> {
return listing ??= readProjectReleases().finally(() => { listing = null; });
/** Share the in-flight scan when the launcher checks both release channels at startup. */
export async function newestProjectRelease<Channel extends ReleaseChannel>(
channel: Channel, installedVersion: string | null,
): Promise<ReleaseCandidates[Channel]> {
listing ??= readProjectReleases().finally(() => { listing = null; });
const { candidates, incomplete, pageLimit } = await listing;
const candidate = candidates[channel];
const compare = channel === 'launcher' ? compareAppVersions : comparePackVersions;
if (candidate && (installedVersion === null || compare(candidate.version, installedVersion) > 0)) return candidate;
if (pageLimit !== null) {
throw new ReleasePageLimitError(`No newer ${channel} release was confirmed within ${pageLimit} pages.`);
}
const partial = incomplete[channel];
if (partial && (!candidate || installedVersion === null || compare(partial, installedVersion) > 0)) {
throw new PatchPackError('contents', `Release ${partial} for the ${channel} channel is missing required files.`);
}
return candidate;
}
async function readProjectReleases(): Promise<readonly unknown[]> {
async function readProjectReleases(): Promise<ReleaseListing> {
const tuning = patchPackTuning();
const url = `https://api.github.com/repos/${tuning.repository}/releases?per_page=${tuning.releasesPerCheck}`;
const response = await request(url, HEADERS, tuning.requestTimeoutMs);
if (response.status === 404) return [];
if (!response.ok) throw new FeedUnreachableError(`GitHub answered HTTP ${response.status} for the release list`);
const releases = (await response.json()) as unknown;
if (!Array.isArray(releases)) throw new PatchPackError('contents', 'the release list is not a list');
return releases;
const candidates: ReleaseCandidates = { launcher: null, pack: null };
const incomplete: Partial<Record<ReleaseChannel, string>> = {};
const url = `https://api.github.com/repos/${tuning.repository}/releases?per_page=${tuning.releasePageSize}`;
for (let page = 1; page <= tuning.maxReleasePages; page += 1) {
const response = await request(`${url}&page=${page}`, HEADERS, tuning.requestTimeoutMs);
if (!response.ok) throw new FeedUnreachableError(`GitHub answered HTTP ${response.status} for release page ${page}`);
const releases: unknown = await response.json();
if (!Array.isArray(releases)) throw new PatchPackError('contents', 'the release list is not a list');
collectReleases(releases, candidates, incomplete, tuning.repository);
const hasNextPage = /;\s*rel="next"\s*(?:,|$)/i.test(response.headers.get('link') ?? '');
// GitHub does not sort release pages by tag version.
if (!hasNextPage) {
return { candidates, incomplete, pageLimit: null };
}
}
console.info(`[release-feed] More releases exist after the configured limit of ${tuning.maxReleasePages} pages.`);
return { candidates, incomplete, pageLimit: tuning.maxReleasePages };
}
/** The newest complete pack release, or null when none is released. */
export async function newestPackRelease(): Promise<PackReleaseFiles | null> {
const packs = (await listProjectReleases()).map(packRelease).filter((release): release is PackReleaseFiles => release !== null);
packs.sort((a, b) => comparePackVersions(b.version, a.version));
return packs[0] ?? null;
function collectReleases(
entries: readonly unknown[], candidates: ReleaseCandidates, incomplete: Partial<Record<ReleaseChannel, string>>, repository: string,
): void {
for (const entry of entries) {
if (typeof entry !== 'object' || entry === null) continue;
const release = entry as Record<string, unknown>;
const tag = release['tag_name'];
if (typeof tag !== 'string' || release['draft'] === true || release['prerelease'] === true) continue;
if (tag.startsWith('v')) {
const version = AppReleaseVersionSchema.safeParse(tag.slice(1));
if (!version.success) continue;
const launcher = launcherRelease(release, version.data, repository);
if (!launcher) {
const missing = incomplete.launcher;
if (!missing || compareAppVersions(version.data, missing) > 0) incomplete.launcher = version.data;
} else if (!candidates.launcher || compareAppVersions(launcher.version, candidates.launcher.version) > 0) {
candidates.launcher = launcher;
}
continue;
}
const version = packVersionOfTag(tag);
if (!version) continue;
const pack = packRelease(release, version);
if (!pack) {
const missing = incomplete.pack;
if (!missing || comparePackVersions(version, missing) > 0) incomplete.pack = version;
} else if (!candidates.pack || comparePackVersions(pack.version, candidates.pack.version) > 0) {
candidates.pack = pack;
}
}
}
function packRelease(value: unknown): PackReleaseFiles | null {
if (typeof value !== 'object' || value === null) return null;
const release = value as Record<string, unknown>;
if (release['draft'] === true || release['prerelease'] === true || typeof release['tag_name'] !== 'string') return null;
const version = packVersionOfTag(release['tag_name']);
if (!version || !Array.isArray(release['assets'])) return null;
function launcherRelease(entry: Record<string, unknown>, version: string, repository: string): LauncherRelease | null {
const parsed = LauncherReleaseEntry.safeParse(entry);
if (!parsed.success) return null;
const { assets, body } = parsed.data;
const names = launcherReleaseFiles(version);
const present = new Set(assets.map(({ name }) => name));
if (!Object.values(names).every((name) => present.has(name))) return null;
const directory = `https://github.com/${repository}/releases/download/v${version}/`;
return {
version,
notes: body?.trim().slice(0, 1600) ?? '',
installer: new URL(names.installer, directory),
manifest: new URL(names.manifest, directory),
signature: new URL(names.signature, directory),
};
}
function packRelease(release: Record<string, unknown>, version: string): PackReleaseFiles | null {
if (!Array.isArray(release['assets'])) return null;
const urls = new Map<string, string>();
for (const asset of release['assets'] as unknown[]) {
if (typeof asset !== 'object' || asset === null) continue;