Files
WT-Offline/apps/server/src/game-data/datasets/dataset-cache.ts
T
N0VAN0M4LY 27fc535301 Split the repository into apps, packages and patches
Everything sat in packages/: two programs next to the small libraries
they use, and the patch data loose at the root. The programs now live in
apps/ and the shared libraries in packages/:

  apps/server        the local server (was packages/local-service),
                     package @wto/server
  packages/patcher   builds the game copy (was packages/build),
                     package @wto/patcher
  patches/exe        exe patch definitions (was exe-patches)
  patches/gui        GUI script patches (was gui-patches)

Inside the server, the network layer folder becomes transport/ so it is
not server/server/, the entry module is server.ts, and startLocalService
and its types become startServer, ServerOptions and RunningServer. The
health answer names the app wto-server, and the TLS files in the data
folder are server.key and server.crt (made again on the next start).
Comments, logs and tool texts say "local server".

The patcher no longer reaches into the server's folder. It read the
default tuning/store.jsonc by a relative path to register bundle GUIDs
for the multi-vehicle packs, which also ignored the player's overrides
in <data>/tuning/. It now takes the pack ids from its caller; the
server exports multiVehiclePackIds(dataFolder), which reads them the way
the running server does. rebuildGuiPack takes the patch folder from its
caller as well.

The development build moves out of the patcher to
scripts/build-game-copy.ts, since it uses both the server and the
patcher. It needs --data (the folder the server will run with) and
defaults the patch folders and the hook library to this repository.


Checked with the root typecheck, check-patches, check-gui,
check-offsets, the native build, a run of build-game-copy.ts into a
scratch folder (12 exe patches, 35 GUI patches, 496 bundle GUIDs as
before) and a server start from apps/server answering wto-server.
2026-11-29 03:20:54 +08:00

164 lines
5.6 KiB
TypeScript

/**
* Extract datasets once and reuse the result while the game files stay the same
*:
*
* 1. every pack the dataset read has the same size and modification time as when it was
* extracted: use the cached result;
* 2. otherwise compare the SHA-1 of the files the dataset actually read (and of the file
* listings it used): all equal, the result still holds, so only the pack stamps are
* updated (the build rewrites char.vromfs.bin on every launch without touching what
* the datasets read);
* 3. otherwise extract again.
*
* Cache entries live in <data folder>/cache/datasets/<dataset id>.json.
*/
import { createHash } from 'node:crypto';
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import type { BlkBlock } from '@wto/blk';
import { writeFileAtomic } from '../../storage/atomic-file.ts';
import type { GameFiles, GamePackName, PackStamp } from '../game-files.ts';
import type { Dataset, DatasetSource } from './dataset.ts';
interface FileInput {
readonly pack: GamePackName;
readonly path: string;
readonly sha1: string;
}
interface ListingInput {
readonly pack: GamePackName;
readonly sha1: string;
}
interface CacheEntry {
readonly id: string;
readonly version: number;
readonly packs: Partial<Record<GamePackName, PackStamp>>;
readonly files: readonly FileInput[];
readonly listings: readonly ListingInput[];
readonly data: unknown;
}
export type DatasetOrigin = 'cache' | 'cache, verified by content' | 'extracted';
export class DatasetCache {
readonly #folder: string;
readonly #gameFiles: GameFiles;
readonly #report: (line: string) => void;
constructor(dataFolder: string, gameFiles: GameFiles, report: (line: string) => void) {
this.#folder = join(dataFolder, 'cache', 'datasets');
this.#gameFiles = gameFiles;
this.#report = report;
}
load<T>(dataset: Dataset<T>): T {
const entryPath = join(this.#folder, `${dataset.id}.json`);
const cached = readEntry(entryPath);
if (cached && cached.id === dataset.id && cached.version === dataset.version) {
if (this.#stampsMatch(cached)) return this.#use(dataset, cached, 'cache');
if (this.#contentMatches(cached)) {
writeEntry(entryPath, { ...cached, packs: this.#stamps(Object.keys(cached.packs) as GamePackName[]) });
return this.#use(dataset, cached, 'cache, verified by content');
}
}
const started = Date.now();
const tracked = new TrackedSource(this.#gameFiles);
const data = dataset.extract(tracked);
const entry: CacheEntry = {
id: dataset.id,
version: dataset.version,
packs: this.#stamps(tracked.packs()),
files: tracked.files(),
listings: tracked.listings(),
data,
};
writeEntry(entryPath, entry);
this.#report(`dataset ${dataset.id}: extracted in ${Date.now() - started} ms (${entry.files.length} files)`);
return data;
}
#use<T>(dataset: Dataset<T>, entry: CacheEntry, origin: DatasetOrigin): T {
this.#report(`dataset ${dataset.id}: ${origin}`);
return entry.data as T;
}
#stamps(packs: readonly GamePackName[]): Partial<Record<GamePackName, PackStamp>> {
return Object.fromEntries(packs.map((pack) => [pack, this.#gameFiles.packStamp(pack)]));
}
#stampsMatch(entry: CacheEntry): boolean {
return Object.entries(entry.packs).every(([pack, stamp]) => {
const current = this.#gameFiles.packStamp(pack as GamePackName);
return stamp !== undefined && current.size === stamp.size && current.mtimeMs === stamp.mtimeMs;
});
}
#contentMatches(entry: CacheEntry): boolean {
return entry.files.every(({ pack, path, sha1 }) => this.#gameFiles.pack(pack).fileDigest(path) === sha1)
&& entry.listings.every(({ pack, sha1 }) => listingDigest(this.#gameFiles.pack(pack).paths()) === sha1);
}
}
/** Reads through to the game files and remembers every input. */
class TrackedSource implements DatasetSource {
readonly #gameFiles: GameFiles;
readonly #files = new Map<string, FileInput>();
readonly #listings = new Map<GamePackName, ListingInput>();
constructor(gameFiles: GameFiles) {
this.#gameFiles = gameFiles;
}
readBlk(pack: GamePackName, path: string): BlkBlock {
const gamePack = this.#gameFiles.pack(pack);
const sha1 = gamePack.fileDigest(path);
if (sha1 === undefined) throw new Error(`${pack} has no file ${path}`);
this.#files.set(`${pack}/${path}`, { pack, path, sha1 });
return gamePack.readBlk(path);
}
readText(pack: GamePackName, path: string): string {
const gamePack = this.#gameFiles.pack(pack);
const sha1 = gamePack.fileDigest(path);
if (sha1 === undefined) throw new Error(`${pack} has no file ${path}`);
this.#files.set(`${pack}/${path}`, { pack, path, sha1 });
return gamePack.readText(path);
}
listFiles(pack: GamePackName): readonly string[] {
const paths = this.#gameFiles.pack(pack).paths();
this.#listings.set(pack, { pack, sha1: listingDigest(paths) });
return paths;
}
packs(): GamePackName[] {
return [...new Set([...this.#files.values(), ...this.#listings.values()].map((input) => input.pack))];
}
files(): FileInput[] {
return [...this.#files.values()];
}
listings(): ListingInput[] {
return [...this.#listings.values()];
}
}
function listingDigest(paths: readonly string[]): string {
return createHash('sha1').update(paths.join('\n')).digest('hex');
}
function readEntry(path: string): CacheEntry | undefined {
try {
return JSON.parse(readFileSync(path, 'utf8')) as CacheEntry;
} catch {
return undefined;
}
}
function writeEntry(path: string, entry: CacheEntry): void {
writeFileAtomic(path, JSON.stringify(entry));
}