/** * Save layer: one save per account, holding the profile in Gaijin's * profile structure. * * /saves//save.json format version and bookkeeping * /saves//profile.blk the profile, binary BLK with every value's type kept * * Every write reaches the disk before the caller replies to the game. A save written by an * older format version is upgraded step by step when it is opened (save-upgrades.ts). */ import { existsSync, readFileSync } from 'node:fs'; import { join } from 'node:path'; import { decodeBlk, encodeBlk, type BlkBlock } from '@wto/blk'; import { normalizeModificationBlocks } from '../profile/profile-modifications.ts'; import { writeFileAtomic } from '../storage/atomic-file.ts'; import type { SaveUpgrades } from './save-upgrades.ts'; interface SaveInfo { formatVersion: number; created: string; updated: string; } export class SaveStore { readonly #folder: string; readonly #upgrades: SaveUpgrades; constructor(dataFolder: string, upgrades: SaveUpgrades) { this.#folder = join(dataFolder, 'saves'); this.#upgrades = upgrades; } /** The account's profile, or undefined when the account has no save yet. */ loadProfile(userId: string): BlkBlock | undefined { const infoPath = this.#infoPath(userId); if (!existsSync(infoPath)) return undefined; const info = JSON.parse(readFileSync(infoPath, 'utf8')) as SaveInfo; const profile = decodeBlk(readFileSync(this.#profilePath(userId))); if (info.formatVersion === this.#upgrades.currentFormat) return profile; const upgraded = this.#upgrades.upgrade(profile, info.formatVersion); this.saveProfile(userId, upgraded); return upgraded; } saveProfile(userId: string, profile: BlkBlock): void { const now = new Date().toISOString(); const previous = existsSync(this.#infoPath(userId)) ? (JSON.parse(readFileSync(this.#infoPath(userId), 'utf8')) as SaveInfo) : undefined; normalizeModificationBlocks(profile); writeFileAtomic(this.#profilePath(userId), encodeBlk(profile)); const info: SaveInfo = { formatVersion: this.#upgrades.currentFormat, created: previous?.created ?? now, updated: now }; writeFileAtomic(this.#infoPath(userId), JSON.stringify(info, null, 2)); } #infoPath(userId: string): string { return join(this.#folder, safeId(userId), 'save.json'); } #profilePath(userId: string): string { return join(this.#folder, safeId(userId), 'profile.blk'); } } function safeId(userId: string): string { if (!/^\d+$/.test(userId)) throw new Error(`invalid user id: ${userId}`); return userId; }