Files
bworld/desktop/client_updates.ts
2026-10-13 11:57:43 -03:00

175 lines
6.4 KiB
TypeScript

// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// keeps the desktop app's client (build/client and build/assets) the same as the site's, like a game launcher: the
// build writes a manifest of every file's hash, the app downloads the site's when it's different and plays that
// copy from its data folder. the singleplayer server is part of the app and can't update this way, so a client for
// a different protocol is never used. anything that goes wrong leaves the app on the client it has
import { join } from "@std/path";
import { sha256 } from "../common/utils.ts";
// where the manifest is, in a build folder and on the site
export const CLIENT_MANIFEST = "client/manifest.json";
export interface ClientManifest {
// the protocol the client speaks, see common/protocol.ts
protocol: number;
// changes whenever any file does
build: string;
// path in the build folder to its sha-256, as hex
files: Record<string, string>;
}
export async function client_manifest(files: Record<string, string>, protocol: number): Promise<ClientManifest> {
const sorted = Object.fromEntries(Object.entries(files).sort(([a], [b]) => a.localeCompare(b)));
const listing = Object.entries(sorted).map(([path, hash]) => `${path} ${hash}`).join("\n");
return { protocol, build: (await sha256(new TextEncoder().encode(listing))).slice(0, 16), files: sorted };
}
export interface ClientUpdateOptions {
// the site, like https://bworld.moder.fans
source: string;
// the client the app was built with
bundled_dir: string;
// where downloaded clients go, one folder per build
cache_dir: string;
// what the app's singleplayer server speaks
protocol: number;
fetch?: typeof fetch;
}
// the folder to serve the client from: the site's if it could be had, else the last one downloaded, else the bundled
// one. clients for another protocol are skipped
export async function update_client(options: ClientUpdateOptions): Promise<string> {
const fallback = () => current_client(options);
const bundled = read_manifest(options.bundled_dir);
let remote: ClientManifest;
try {
const response = await (options.fetch ?? fetch)(`${options.source}/${CLIENT_MANIFEST}`);
if (!response.ok) throw new Error(`manifest: ${response.status}`);
remote = await response.json();
} catch (e) {
console.log(`Couldn't check for a newer client: ${(e as Error).message}`);
return fallback();
}
if (remote.protocol !== options.protocol) {
console.log(`The site's client speaks protocol ${remote.protocol}, this app's server ${options.protocol}`);
return fallback();
}
if (remote.build === bundled?.build) {
return options.bundled_dir;
}
const folder = join(options.cache_dir, remote.build);
if (read_manifest(folder)?.build === remote.build) {
return folder;
}
try {
await download_client(remote, folder, options).catch((e) => {
remove(`${folder}.partial`);
throw e;
});
console.log(`Updated the client to ${remote.build}`);
remove_old_clients(options.cache_dir);
return folder;
} catch (e) {
console.log(`Couldn't update the client: ${(e as Error).message}`);
return fallback();
}
}
// every file into a temporary folder, taking the ones that didn't change from the bundled client or an older
// download, then the folder is renamed into place so a half done download is never used
async function download_client(manifest: ClientManifest, folder: string, options: ClientUpdateOptions) {
const partial = `${folder}.partial`;
remove(partial);
const known = local_files(options);
for (const [path, hash] of Object.entries(manifest.files)) {
if (path.split("/").includes("..")) throw new Error(`bad path ${path}`);
let bytes = known.get(hash)?.();
if (!bytes) {
const response = await (options.fetch ?? fetch)(`${options.source}/${path}`);
if (!response.ok) throw new Error(`${path}: ${response.status}`);
bytes = new Uint8Array(await response.arrayBuffer());
}
if (await sha256(bytes) !== hash) throw new Error(`${path} doesn't match the manifest`);
const target = join(partial, path);
Deno.mkdirSync(join(target, ".."), { recursive: true });
Deno.writeFileSync(target, bytes);
}
Deno.writeTextFileSync(join(partial, CLIENT_MANIFEST), JSON.stringify(manifest));
remove(folder);
Deno.renameSync(partial, folder);
}
// files the app already has, by hash, read only if they're needed
function local_files(options: ClientUpdateOptions) {
const files = new Map<string, () => Uint8Array<ArrayBuffer> | undefined>();
const folders = [options.bundled_dir, ...cache_folders(options.cache_dir)];
for (const folder of folders) {
for (const [path, hash] of Object.entries(read_manifest(folder)?.files ?? {})) {
if (!files.has(hash)) files.set(hash, () => try_read(join(folder, path)));
}
}
return files;
}
// the newest download for this protocol
function cached_client(options: ClientUpdateOptions): string | undefined {
return cache_folders(options.cache_dir)
.filter((folder) => read_manifest(folder)?.protocol === options.protocol)
.sort(by_newest)[0];
}
// what to play without checking the site, like when checking takes too long
export function current_client(options: ClientUpdateOptions): string {
return cached_client(options) ?? options.bundled_dir;
}
// the newest two are kept: the one just downloaded, and the one the app may still be playing if the download took
// longer than it waited
function remove_old_clients(cache_dir: string) {
const newest_first = cache_folders(cache_dir).sort(by_newest);
for (const folder of newest_first.slice(2)) remove(folder);
}
function by_newest(a: string, b: string) {
return Deno.statSync(b).mtime!.getTime() - Deno.statSync(a).mtime!.getTime();
}
function cache_folders(cache_dir: string): string[] {
try {
return [...Deno.readDirSync(cache_dir)]
.filter((entry) => entry.isDirectory && !entry.name.endsWith(".partial"))
.map((entry) => join(cache_dir, entry.name));
} catch {
return [];
}
}
function read_manifest(folder: string): ClientManifest | undefined {
const bytes = try_read(join(folder, CLIENT_MANIFEST));
try {
return bytes && JSON.parse(new TextDecoder().decode(bytes));
} catch {
return undefined;
}
}
function remove(path: string) {
try {
Deno.removeSync(path, { recursive: true });
} catch (e) {
if (!(e instanceof Deno.errors.NotFound)) throw e;
}
}
function try_read(path: string): Uint8Array<ArrayBuffer> | undefined {
try {
return Deno.readFileSync(path);
} catch {
return undefined;
}
}