diff --git a/.github/workflows/engine-ci.yml b/.github/workflows/engine-ci.yml index 4079bd4b5..f46cc061d 100644 --- a/.github/workflows/engine-ci.yml +++ b/.github/workflows/engine-ci.yml @@ -328,16 +328,28 @@ jobs: working-directory: engine run: cargo build -p ps5upload-unrar + # The tests run with the temp folder pointed at an empty folder of this job's own, and a + # step after them fails if they left anything there: tests that never removed their scratch + # folders once filled a developer's temp folder with 38 GB (scripts/check-test-tmp-leaks.sh). + - name: Empty temp folder for the tests + shell: bash + run: | + mkdir -p "$RUNNER_TEMP/test-tmp" + echo "TEST_TMP=$RUNNER_TEMP/test-tmp" >> "$GITHUB_ENV" + # nextest runs the test binaries side by side (cargo test runs them one at a time, and most # of these sit in network sleeps); doctests, which nextest does not run, follow separately. # Timing-sensitive binaries are serialized by engine/.config/nextest.toml. # Bounded per step: a hung test fails here in minutes instead of holding the job. + # Built first with the usual temp folder: only what the tests leave is checked. - name: cargo nextest working-directory: engine timeout-minutes: 25 env: RUST_BACKTRACE: 1 - run: cargo nextest run --profile ci ${{ matrix.select }} + run: | + cargo nextest run --profile ci --no-run ${{ matrix.select }} + TMPDIR="$TEST_TMP" cargo nextest run --profile ci ${{ matrix.select }} # After the main run and with its exact package set (matrix.select), so nothing recompiles: # a `cargo test -p ps5upload-engine` here first built the engine a second time. --no-capture @@ -401,7 +413,11 @@ jobs: - name: cargo test --doc working-directory: engine timeout-minutes: 10 - run: cargo test --doc ${{ matrix.select }} + run: TMPDIR="$TEST_TMP" cargo test --doc ${{ matrix.select }} + + - name: Tests left nothing in the temp folder + shell: bash + run: scripts/check-test-tmp-leaks.sh --check "$TEST_TMP" # target/tmp is CARGO_TARGET_TMPDIR, test scratch space, not build output. The UFS2 writer # tests leave sparse images there, one of them 68 GB apparent (lastcg.ffpkg): tar stored it diff --git a/CHANGELOG.md b/CHANGELOG.md index 313b453b3..59bc2fb5e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,27 @@ What's new in ps5upload, written for humans. ## Unreleased +**Payloads** +- **Your own payload sources are back.** In Payloads, add a GitHub, Gitea or Forgejo project that publishes payload files, and pick the file once (for example `kstuff.elf`). Its card shows the release you have, says when a newer one is out, and has Download, Update and Send to PS5. Nothing happens on its own: it checks only when you open Payloads or press Check, downloads only when you press Download, and before sending shows the file, its release, size and checksum. Only add projects you trust. The built-in list stays a guide with links. + +**Files** +- **Two panes on a wide screen (#952).** Turn on Two panes to keep the PS5 on one side and this computer, a saved server or another console on the other, and copy or move between them. Phones and tablets stay as they were. +- **Copy or move from the PS5 to a saved server (#953),** in Move to… and on the console's own page. A move deletes the original only after the copy is checked, and keeps a folder that holds links, which a share can't hold. + +**Convert** +- **Closing the page no longer marks a running build "Interrupted" (#954).** The build keeps going; the reopened page picks it up or shows it finished. The queue's next game, and the install after Convert & install, wait until the page is open again, and the page says so. + +**Games** +- **Check the copy no longer shows 100% while it still reads the package (#951).** It counts both reads and says which part it is on, and Cancel works in both. + +**Upload & Install** +- **"The file at this link changed" only when it really did.** Servers whose copies disagree on dates or tags no longer trip it; a different size or different first bytes still do. + +**Under the hood** +- The tests no longer leave folders behind in the system's temp folder (a full run used to leave about 2 GB), and CI checks it. A signing script no longer leaves its key file behind. + +## 12.6.33 + **Fake PS5 packages** - **Two ways to play them, explained side by side.** Install the package (on firmware 11.61 to 13.60 with the latest kstuff, which supports fake packages up to 13.60), or mount it with Kraken Mount. Upload & Install, Convert, the hint after a game doesn't start, the Payloads catalog, the FAQ and the website now all say this the same way, and the note is information rather than a warning. diff --git a/FAQ.md b/FAQ.md index 2bbd5ccf3..103de0a34 100644 --- a/FAQ.md +++ b/FAQ.md @@ -83,8 +83,8 @@ more depth further down. Send **elfldr** first (if your setup uses it), then **kstuff**, then **ShadowMount+**, then **ps5upload**. The **Set up your PS5** wizard does the last three in this order for you, with the delays the Payloads catalogue -recommends. ps5upload doesn't download payloads: get kstuff and ShadowMount+ from their project -pages (Payloads › Catalog links to them) and choose the files in the wizard. Send them one at a time; the loader takes one file per +recommends. The built-in catalogue only links to payloads: get kstuff and ShadowMount+ from their +project pages (Payloads › Catalog links to them) and choose the files in the wizard. Send them one at a time; the loader takes one file per connection. After a reboot the payloads are gone, so load them again. Rest mode can stop them too; the PS5Upload helper usually keeps running through it. @@ -559,8 +559,10 @@ something else, and records the send in a history panel so you can replay it without re-picking the file. **Q: How do I keep my payloads up to date?** -ps5upload doesn't download payloads. Get a newer release from the payload's project page and send -the file from **Payloads → Send payload**. **Payloads › Catalog › Payload updates** still tells you +For a payload from a project you added as your own payload source, its card says **New version +available** and **Update** downloads it (see *How do I add my own payload source?*). The built-in +catalogue's payloads aren't downloaded by the app: get a newer release from the payload's project +page and send the file from **Payloads → Send payload**. **Payloads › Catalog › Payload updates** still tells you when one is out: **Check for payload updates** compares each payload saved in the app (copies earlier versions of the app downloaded) with its latest release, and links to the release page. A copy an earlier update replaced is kept: **Roll back** puts it back. @@ -570,6 +572,32 @@ Manager loads it at boot** if you want it at boot) on a payload, and **Sync with copies the ones you keep into it when they change and adds the marked ones to its boot list. Nothing else in its list is changed. Payload Manager has to be running on the PS5 for this. +**Q: How do I add my own payload source (a custom GitHub or Gitea repo)?** +In **Payloads › Catalog**, under **Your payload sources**, press **Add a payload source** and paste +the project's address: `https://github.com/owner/project`, or a Gitea or Forgejo project +(`https://your-server/owner/project`; a server on your home network and its own port is fine). +Only https addresses work, without a user name or password in them. **Show its files** lists the +`.elf` and `.bin` files of the project's newest release: pick the payload once and press **Add +source**. PS5Upload will download and send whatever that project publishes under that name, so +only add projects you trust. + +Newer releases are matched by name: the same name apart from its version numbers. If you picked +`kstuff-v1.6.0.elf`, a later `kstuff-v1.7.elf` is the update; a name like `ftpsrv-ps5.elf` (no +version in it) has to stay exactly the same. The card shows the rule it uses. If the project +renames the file, use **Change file**. + +Each source gets a card. Nothing happens on its own: the app looks for new releases when you open +Payloads or press **Check** (at most every ten minutes otherwise; GitHub allows 60 checks an hour, +and when it says to wait, the card says until when). **Download** (or **Update**, when the card +says *New version available*) saves the file in the app's payload folder, checked against the +size the release gives and against its checksum file when it has one. The card then shows the +file's name, release, size and SHA-256, and **Send to PS5** asks once more, naming them, before +it sends. **Remove source** deletes the source and its downloaded file. The built-in catalogue +stays a list of project pages: PS5Upload never downloads those for you, so for them download the +file yourself and send it from **Payloads → Send payload**. + +Repos you added before 12.6.0 come back as sources: press **Pick the file** on their card once. + **Q: The Send button says "Waiting for the helper to start…" for a long time.** That is the normal probe window, up to 20 seconds. If it times out, the helper likely crashed on load; send it again. diff --git a/MCP.md b/MCP.md index 397ee2e58..078d7fba5 100644 --- a/MCP.md +++ b/MCP.md @@ -27,7 +27,7 @@ More than 120 tools, all of them thin layers over [the engine's API](API.md): | Convert | `convert_*` | Whether an archive can give its space back while it unpacks; put the AMPR emulator on a console for Convert on the PS5 (a conversion itself goes through `api_request`) | | Games | `games_*`, `processes_*`, `saves_*`, `cheats_*` | Installed titles, launch and stop, back up saves, cheats | | Hardware | `hw_*`, `power_*`, `notifications_*`, `health_*`, `disk_usage_*`, `cleanup_*`, `shell_run` | Temperatures, rest and wake, health checks and repairs, what fills the drive | -| Payloads | `payloads_*` | Catalogue, new-version checks and rollback, send (a file, or a copy already on the computer: ps5upload never downloads payloads), store, autoload, Payload Manager sync | +| Payloads | `payloads_*` | Catalogue, the payload sources you added (list, check for a new release, download its file), new-version checks and rollback, send (a file, or a copy already on the computer), store, autoload, Payload Manager sync. Built-in catalogue payloads are never downloaded, and only you can add a source, in the app | | Remote Play | `rp_*` | Start and stop a session, see the picture, press buttons, type, answer a passcode; see what the controller sends and how pairing went | | Friends and viewers | `together_*`, `golive_*`, `share_*` | Open Play Together and invite; go live; share an app's things with a friend | | Everything else | `settings_*`, `devices_list`, `drive_*`, `api_catalog`, `api_describe`, `api_request` | Settings, Mesh Drive, and any route of the API | @@ -282,6 +282,7 @@ clients let you allow tools one by one, so keep these on "ask". | `power_control` | Rest, reboot or shut down | | `shell_run` | Run any command on the console, and read any file there, sign-in keys included | | `payloads_send` | Run a program on the console, with the same reach as a shell | +| `payloads_source_download` | Replace the copy of a payload source's file on this computer with its newest release | | `payloads_store`, `payloads_delete`, `payloads_autoload`, `payloads_pm_sync` | Change what the console keeps and runs at boot | | `cleanup_apply`, `health_fix` | Delete what a scan found, and apply repairs | | `rp_stop` | End the Remote Play session someone may be playing | diff --git a/README.md b/README.md index 72a5801c6..37017bc27 100644 --- a/README.md +++ b/README.md @@ -99,9 +99,10 @@ - A script or AI agent on the engine's computer can watch and play a running session ([AUTOMATION.md](AUTOMATION.md)), and drive everything else too ([API and AI agents](#api-and-ai-agents)). - **Cheats, fan curve, hardware view,** payload sender with a payload guide and playlists, and - backport tools. ps5upload doesn't download payloads: get each one from its project page and - send the file. **Payload updates** says when a newer release is out, rolls back, and keeps - Payload Manager's copies and boot list in step. + backport tools. The payload guide links to each project page; add a GitHub, Gitea or Forgejo + project as your own payload source and the app downloads the file you picked when you ask, shows + its SHA-256 and sends it. **Payload updates** says when a newer release is out, rolls back, and + keeps Payload Manager's copies and boot list in step. - **Bug reports in one place.** Bug Report (always in the sidebar) gathers the app's, the engine's and the PS5 helper's logs for the time you pick into one `.zip`, with addresses, serials and keys removed, ready to post on GitHub or Discord. **Detailed logs** (Logs tab) diff --git a/VERSION b/VERSION index ada43bfb9..d4c89e99c 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -12.6.32 +12.6.33 diff --git a/client/e2e/files-move-to-server.spec.ts b/client/e2e/files-move-to-server.spec.ts new file mode 100644 index 000000000..121b1e487 --- /dev/null +++ b/client/e2e/files-move-to-server.spec.ts @@ -0,0 +1,122 @@ +import { expect, test, type Route } from "@playwright/test"; + +// #953: select items in Files, "Move to…", pick a saved server and a folder on it: each item goes +// to the engine as a download into that folder with remove_source (the engine deletes the original +// only after it checked the copy), one after another. "Copy there…" sends the same without it. +// The engine here is a fake. + +const PRO = "192.168.0.5"; + +async function setup(page: import("@playwright/test").Page) { + await page.addInitScript((pro) => { + window.localStorage.setItem("ps5upload.host", pro); + window.localStorage.setItem( + "ps5upload.roster.v1", + JSON.stringify({ profiles: [{ id: "pro", name: "Pro", host: pro }], active_id: "pro" }), + ); + }, PRO); + const json = (route: Route, body: unknown) => + route.fulfill({ status: 200, contentType: "application/json", body: JSON.stringify(body) }); + const downloads: Record[] = []; + let running = 0; + let overlapped = false; + await page.route( + (u) => u.pathname.startsWith("/api/"), + async (route) => { + const req = route.request(); + const url = new URL(req.url()); + const p = url.pathname; + if (p === "/api/version") return json(route, { caps: { rar: true }, version: "6.7.4" }); + if (p === "/api/ps5/status") + return json(route, { + command_count: 1, + instance_id: 1, + prior_instance: "clean", + ps5_kernel: "r229358/releases/13.60", + ucred_elevated: true, + version: "6.7.4", + }); + if (p === "/api/ps5/volumes") + return json(route, { + volumes: [ + { + path: "/data", + fs_type: "nullfs", + total_bytes: 900e9, + free_bytes: 400e9, + allocatable_bytes: 398e9, + writable: true, + is_placeholder: false, + }, + ], + }); + if (p === "/api/ps5/list-dir") + return json(route, { + path: url.searchParams.get("path") ?? "/data", + entries: [ + { name: "GameA-app", kind: "dir", size: 0, mtime: 1 }, + { name: "b.bin", kind: "file", size: 4_000_000, mtime: 1 }, + ], + truncated: false, + total_scanned: 2, + returned: 2, + }); + if (p === "/api/remote/connections") + return json(route, { + connections: [ + { id: "nas1", name: "Home NAS", protocol: "smb", host: "10.0.0.5", port: 445, share: "games", user: "", start_path: "/", host_key: null, has_secret: false }, + ], + }); + if (p === "/api/remote/list") { + const at = (JSON.parse(req.postData() ?? "{}") as { path: string }).path; + return json(route, { + entries: at.endsWith("/PS5") ? [] : [{ name: "PS5", is_dir: true, size: 0, mtime: null }], + next_cursor: null, + }); + } + if (p === "/api/transfer/download") { + if (running) overlapped = true; + running++; + downloads.push(req.postDataJSON()); + return json(route, { job_id: `j${downloads.length}` }); + } + // Each job ends at once, so the next item starts after it. + if (p.startsWith("/api/jobs/")) { + running = 0; + return json(route, { status: "done", bytes_sent: 10, total_bytes: 10, elapsed_ms: 5, dest: "x" }); + } + return json(route, {}); + }, + ); + return { downloads, overlapped: () => overlapped }; +} + +for (const how of ["Move", "Copy"] as const) { + test(`Files ${how === "Move" ? "moves" : "copies"} the selection to a folder on a saved server`, async ({ page }) => { + const seen = await setup(page); + await page.goto("/files", { waitUntil: "domcontentloaded" }); + const main = page.getByRole("main"); + await expect(main.getByText("GameA-app", { exact: true })).toBeVisible({ timeout: 30_000 }); + await main.getByTitle("Select all").check(); + await main.getByRole("button", { name: "Move to…" }).first().click(); + + const servers = page.getByTestId("move-servers"); + await expect(servers).toContainText("Home NAS"); + await servers.getByRole("button", { name: `${how} there…` }).click(); + + const picker = page.getByRole("dialog"); + await picker.getByText("PS5", { exact: true }).click(); + await picker.getByRole("button", { name: "Use this folder" }).click(); + + await expect.poll(() => seen.downloads.length, { timeout: 20_000 }).toBe(2); + expect(seen.overlapped()).toBe(false); + expect(seen.downloads.map((d) => [d.src_path, d.kind]).sort()).toEqual([ + ["/data/GameA-app", "folder"], + ["/data/b.bin", "file"], + ]); + for (const d of seen.downloads) { + expect(d.dest_dir).toBe("remote://nas1/PS5"); + expect(d.remove_source).toBe(how === "Move" ? true : undefined); + } + }); +} diff --git a/client/e2e/files-two-panes.spec.ts b/client/e2e/files-two-panes.spec.ts new file mode 100644 index 000000000..eb71f7573 --- /dev/null +++ b/client/e2e/files-two-panes.spec.ts @@ -0,0 +1,400 @@ +import { expect, test, type Locator, type Page } from "@playwright/test"; + +import { routeEngine, seedConsole } from "./fixtures/engine"; + +// #952: Files' two panes. The PS5 on one side, this computer (here the web UI, so the computer the +// engine runs on), a saved server or another console on the other, and Copy / Move between them. +// The engine is a fake that keeps a small file tree for each place, so what a transfer does shows. + +const SHOTS = process.env.PS5UPLOAD_SHOTS ?? ""; +const WIDE_FONT = "*{font-family:Verdana,'DejaVu Sans',sans-serif!important}"; + +interface Entry { + name: string; + dir: boolean; + size: number; +} + +/** The fake engine: three places, what each holds, and what was asked of it in order. */ +function fakeEngine() { + const ps5: Record = { + "/data": [ + { name: "homebrew", dir: true, size: 0 }, + { name: "notes.txt", dir: false, size: 4096 }, + ], + "/data/homebrew": [{ name: "tool.elf", dir: false, size: 900 }], + }; + const pc: Record = { + "/srv": [ + { name: "games", dir: true, size: 0 }, + { name: "patch.pkg", dir: false, size: 1234 }, + ], + "/srv/games": [{ name: "big.exfat", dir: false, size: 77 }], + }; + const nas: Record = { "/": [{ name: "backups", dir: true, size: 0 }], "/backups": [] }; + const log: string[] = []; + const jobs: Record void }> = {}; + let n = 0; + /** How a new download ends: at once ("done"), never until released ("hold"), or "fail". */ + const state = { download: "done" as "done" | "hold" | "fail" }; + const land = (tree: Record, dir: string, e: Entry) => { + tree[dir] = [...(tree[dir] ?? []).filter((x) => x.name !== e.name), e]; + }; + const entryAt = (path: string) => { + const i = path.lastIndexOf("/"); + const dir = i <= 0 ? "/" : path.slice(0, i); + return { dir, e: ps5[dir]?.find((x) => x.name === path.slice(i + 1)) }; + }; + return { + ps5, + pc, + nas, + log, + jobs, + state, + async install(page: Page) { + await routeEngine(page, (path, req) => { + const url = new URL(req.url()); + if (path === "/api/version") return { version: "12.6.33", caps: {} }; + if (path === "/api/ps5/status") + return { ok: true, version: "12.6.33", ucred_elevated: true, ps5_kernel: "releases/10.00", instance_id: 1, command_count: 1 }; + if (path === "/api/ps5/volumes") + return { volumes: [{ path: "/data", fs_type: "ufs", total_bytes: 825e9, free_bytes: 410e9, writable: true }] }; + if (path === "/api/ps5/files/prefs") return { supported: true, favorites: [], recent: [], last: null }; + if (path === "/api/ps5/list-dir") { + const dir = url.searchParams.get("path") ?? "/data"; + const list = ps5[dir] ?? []; + return { + path: dir, + entries: list.map((e) => ({ name: e.name, kind: e.dir ? "dir" : "file", size: e.size, mtime: 1 })), + truncated: false, + total_scanned: list.length, + returned: list.length, + }; + } + if (path === "/api/local/storage-roots") return ["/srv"]; + if (path === "/api/local/list-dir") { + const dir = url.searchParams.get("path") ?? "/srv"; + return (pc[dir] ?? []).map((e) => ({ name: e.name, path: `${dir}/${e.name}`, is_dir: e.dir, size: e.size })); + } + if (path === "/api/local/path-kind") return { kind: "file" }; + if (path === "/api/remote/connections") + return { + connections: [ + { id: "nas", name: "NAS", protocol: "smb", host: "10.0.0.9", port: 445, share: "games", user: "", start_path: "/", host_key: null, has_secret: false }, + ], + }; + if (path === "/api/remote/list") { + const raw = (req.postDataJSON() as { path: string }).path; + const dir = "/" + raw.replace(/^remote:\/\/nas\/?/, ""); + return { + entries: (nas[dir] ?? []).map((e) => ({ name: e.name, is_dir: e.dir, size: e.size, mtime: null })), + next_cursor: null, + }; + } + if (path === "/api/transfer/download") { + const body = req.postDataJSON() as { src_path: string; dest_dir: string; remove_source?: boolean }; + const id = `dl${++n}`; + log.push(`download ${body.src_path} -> ${body.dest_dir}${body.remove_source ? " (engine move)" : ""}`); + const { dir: srcDir, e } = entryAt(body.src_path); + const landIt = () => { + if (!e) return; + if (body.dest_dir.startsWith("remote://nas")) land(nas, "/" + body.dest_dir.replace(/^remote:\/\/nas\/?/, ""), e); + else land(pc, body.dest_dir, e); + // The engine's move (#953) deletes the source itself once the copy checked out. + if (body.remove_source) ps5[srcDir] = (ps5[srcDir] ?? []).filter((x) => x.name !== e.name); + }; + jobs[id] = { status: state.download === "fail" ? "failed" : state.download === "hold" ? "running" : "done", land: landIt }; + if (jobs[id].status === "done") landIt(); + return { job_id: id }; + } + if (/^\/api\/transfer\/(file|file-list|dir)$/.test(path)) { + log.push(`upload ${JSON.stringify(req.postDataJSON())}`); + return { job_id: `up${++n}` }; + } + if (path.startsWith("/api/jobs/")) { + const id = path.split("/")[3]; + const j = jobs[id]; + if (!j) return { status: "done", bytes_sent: 1, total_bytes: 1 }; + return j.status === "failed" + ? { status: "failed", error: "disk full" } + : { status: j.status, bytes_sent: j.status === "done" ? 10 : 3, total_bytes: 10 }; + } + if (path === "/api/jobs") return []; + if (path === "/api/ps5/fs/delete") { + const p = (req.postDataJSON() as { path: string }).path; + log.push(`delete ${p}`); + const { dir } = entryAt(p); + ps5[dir] = (ps5[dir] ?? []).filter((x) => `${dir}/${x.name}` !== p); + return { ok: true }; + } + return undefined; + }); + }, + /** Ends a held download as done, its file landing where it went. */ + finish(id: string) { + jobs[id].status = "done"; + jobs[id].land?.(); + }, + }; +} + +async function openFiles(page: Page, opts: { lang?: string; twoPanes?: boolean } = {}) { + await seedConsole(page); + await page.addInitScript( + ([lang, on]) => { + if (lang) window.localStorage.setItem("ps5upload.lang", lang); + if (on && !window.sessionStorage.getItem("seeded")) { + window.localStorage.setItem("ps5upload.files.twoPanes", "1"); + window.sessionStorage.setItem("seeded", "1"); + } + }, + [opts.lang ?? "", opts.twoPanes ? "1" : ""] as const, + ); + const engine = fakeEngine(); + await engine.install(page); + await page.goto("/files", { waitUntil: "domcontentloaded" }); + const main = page.getByRole("main"); + await expect(main.locator("[data-fs-name='notes.txt']")).toBeVisible({ timeout: 60_000 }); + return { main, engine }; +} + +const other = (page: Page) => page.getByTestId("two-panes-other"); +const row = (scope: Locator, name: string) => scope.locator(`[data-fs-name="${name}"]`); +const otherRow = (page: Page, name: string) => other(page).locator(`[data-other-row="${name}"]`); + +async function shot(page: Page, name: string) { + if (SHOTS) await page.screenshot({ path: `${SHOTS}/${name}.png` }); +} + +for (const viewport of [ + { width: 1280, height: 800 }, + { width: 1600, height: 900 }, +]) { + test.describe(`${viewport.width}x${viewport.height}`, () => { + test.use({ viewport }); + + test("the toggle opens the other side, both sides browse on their own, and it is remembered", async ({ page }) => { + const { main } = await openFiles(page); + const toggle = main.getByTestId("fs-two-panes-toggle"); + await expect(toggle).toHaveAttribute("aria-pressed", "false"); + await expect(page.locator("[data-two-panes]")).toHaveCount(0); + await shot(page, `off-${viewport.width}`); + + await toggle.click(); + await expect(toggle).toHaveAttribute("aria-pressed", "true"); + await expect(other(page).getByTestId("two-panes-place")).toHaveValue("computer"); + await expect(otherRow(page, "patch.pkg")).toBeVisible(); + // The PS5 side is on the left, the other side on the right, the actions between. + const ps5Box = (await page.locator("[data-pane='ps5']").boundingBox())!; + const otherBox = (await other(page).boundingBox())!; + const actionsBox = (await page.getByTestId("two-panes-actions").boundingBox())!; + expect(ps5Box.x + ps5Box.width).toBeLessThanOrEqual(actionsBox.x + 1); + expect(actionsBox.x + actionsBox.width).toBeLessThanOrEqual(otherBox.x + 1); + + // Each side opens its own folders. + await otherRow(page, "games").getByRole("button", { name: "games" }).click(); + await expect(otherRow(page, "big.exfat")).toBeVisible(); + await expect(other(page).getByTestId("two-panes-path")).toHaveText("/srv/games"); + await row(main, "homebrew").locator("[data-fs-open]").click(); + await expect(row(main, "tool.elf")).toBeVisible(); + await expect(other(page).getByTestId("two-panes-path")).toHaveText("/srv/games"); + await shot(page, `on-${viewport.width}`); + + // Kept for the next visit, with the other side's folder. + await page.reload(); + await expect(main.getByTestId("fs-two-panes-toggle")).toHaveAttribute("aria-pressed", "true", { timeout: 60_000 }); + await expect(other(page).getByTestId("two-panes-path")).toHaveText("/srv/games"); + await main.getByTestId("fs-two-panes-toggle").click(); + await page.reload(); + await expect(main.getByTestId("fs-two-panes-toggle")).toHaveAttribute("aria-pressed", "false", { timeout: 60_000 }); + await expect(page.locator("[data-two-panes]")).toHaveCount(0); + }); + }); +} + +test.describe("transfers", () => { + test.use({ viewport: { width: 1280, height: 800 } }); + + test("computer → PS5 is Add files into the PS5 folder; no Move from the computer", async ({ page }) => { + const { main, engine } = await openFiles(page, { twoPanes: true }); + await expect(otherRow(page, "patch.pkg")).toBeVisible(); + await expect(page.getByTestId("two-panes-move-ps5")).toBeDisabled(); + await expect(page.getByTestId("two-panes-actions")).toContainText("never deletes files on its computer"); + await expect(page.getByTestId("two-panes-copy-ps5")).toBeDisabled(); + await otherRow(page, "patch.pkg").getByRole("checkbox").check(); + await page.getByTestId("two-panes-copy-ps5").click(); + await expect.poll(() => engine.log.find((l) => l.startsWith("upload")), { timeout: 20_000 }).toContain("/srv/patch.pkg"); + expect(engine.log.find((l) => l.startsWith("upload"))).toContain("/data"); + expect(engine.log.some((l) => l.startsWith("delete"))).toBe(false); + await expect(main.getByTestId("fs-two-panes-toggle")).toBeVisible(); + }); + + test("PS5 → saved server is the download to that server, into the folder shown", async ({ page }) => { + const { main, engine } = await openFiles(page, { twoPanes: true }); + await other(page).getByTestId("two-panes-place").selectOption({ label: "NAS" }); + await expect(otherRow(page, "backups")).toBeVisible(); + await otherRow(page, "backups").getByRole("button", { name: "backups" }).click(); + await expect(other(page).getByTestId("two-panes-path")).toHaveText("/backups"); + // From the server to the PS5 copies; a move would need the server to delete. + await expect(page.getByTestId("two-panes-move-ps5")).toBeDisabled(); + await expect(page.getByTestId("two-panes-actions")).toContainText("doesn't delete files on saved servers"); + await row(main, "notes.txt").getByRole("checkbox").check(); + await page.getByTestId("two-panes-copy-other").click(); + await expect.poll(() => engine.log.filter((l) => l.startsWith("download"))).toEqual([ + "download /data/notes.txt -> remote://nas/backups", + ]); + // The copy shows on the server's side when it ends; the PS5 keeps its file. + await expect(otherRow(page, "notes.txt")).toBeVisible({ timeout: 20_000 }); + await expect(row(main, "notes.txt")).toBeVisible(); + expect(engine.log.some((l) => l.startsWith("delete"))).toBe(false); + await shot(page, "server-copied"); + }); + + test("Move PS5 → computer deletes the PS5 file only after its copy finished and is there", async ({ page }) => { + const { main, engine } = await openFiles(page, { twoPanes: true }); + await expect(otherRow(page, "patch.pkg")).toBeVisible(); + engine.state.download = "hold"; + await row(main, "notes.txt").getByRole("checkbox").check(); + await page.getByTestId("two-panes-move-other").click(); + const ask = page.getByRole("alertdialog"); + await expect(ask).toContainText("only after its copy is there in full"); + await shot(page, "move-confirm"); + await ask.getByRole("button", { name: "Move", exact: true }).click(); + await expect.poll(() => engine.log.filter((l) => l.startsWith("download")).length).toBe(1); + // The copy is still running: nothing deleted. + await page.waitForTimeout(1500); + expect(engine.log.some((l) => l.startsWith("delete"))).toBe(false); + engine.finish("dl1"); + await expect.poll(() => engine.log, { timeout: 20_000 }).toEqual([ + "download /data/notes.txt -> /srv", + "delete /data/notes.txt", + ]); + await expect(row(main, "notes.txt")).toHaveCount(0, { timeout: 20_000 }); + await expect(otherRow(page, "notes.txt")).toBeVisible(); + }); + + test("a ticked folder can't Move to this computer (Copy only), and says why", async ({ page }) => { + const { main } = await openFiles(page, { twoPanes: true }); + await expect(otherRow(page, "patch.pkg")).toBeVisible(); + await row(main, "notes.txt").getByRole("checkbox").check(); + await expect(page.getByTestId("two-panes-move-other")).toBeEnabled(); + await row(main, "homebrew").getByRole("checkbox").check(); + await expect(page.getByTestId("two-panes-move-other")).toBeDisabled(); + await expect(page.getByTestId("two-panes-copy-other")).toBeEnabled(); + await expect(page.getByTestId("two-panes-actions")).toContainText("Move takes files only here"); + // The PS5 side's selection bar is narrower than the window: its actions wrap, none cut or + // over another. + const boxes = await main + .getByTestId("fs-selection-actions") + .locator(":scope > button") + .evaluateAll((els) => + els.map((el) => { + const r = el.getBoundingClientRect(); + return { l: r.left, r: r.right, t: r.top, b: r.bottom, cut: el.scrollWidth > el.clientWidth + 1 }; + }), + ); + expect(boxes.filter((b) => b.cut)).toEqual([]); + for (let i = 0; i < boxes.length; i++) + for (let j = i + 1; j < boxes.length; j++) { + const [a, b] = [boxes[i], boxes[j]]; + const overlap = a.l < b.r - 1 && b.l < a.r - 1 && a.t < b.b - 1 && b.t < a.b - 1; + expect(overlap, `buttons ${i} and ${j} overlap`).toBe(false); + } + await shot(page, "folder-copy-only"); + }); + + test("Move PS5 → saved server is the engine's own move: files and folders, no delete from the app", async ({ page }) => { + const { main, engine } = await openFiles(page, { twoPanes: true }); + await other(page).getByTestId("two-panes-place").selectOption({ label: "NAS" }); + await expect(otherRow(page, "backups")).toBeVisible(); + await row(main, "homebrew").getByRole("checkbox").check(); + await row(main, "notes.txt").getByRole("checkbox").check(); + await expect(page.getByTestId("two-panes-move-other")).toBeEnabled(); + await page.getByTestId("two-panes-move-other").click(); + await page.getByRole("alertdialog").getByRole("button", { name: "Move", exact: true }).click(); + await expect.poll(() => engine.log, { timeout: 20_000 }).toEqual([ + "download /data/homebrew -> remote://nas (engine move)", + "download /data/notes.txt -> remote://nas (engine move)", + ]); + await expect(row(main, "notes.txt")).toHaveCount(0, { timeout: 20_000 }); + await expect(row(main, "homebrew")).toHaveCount(0); + await expect(otherRow(page, "homebrew")).toBeVisible(); + await expect(otherRow(page, "notes.txt")).toBeVisible(); + }); + + test("a failed copy in a move keeps the PS5 file", async ({ page }) => { + const { main, engine } = await openFiles(page, { twoPanes: true }); + await expect(otherRow(page, "patch.pkg")).toBeVisible(); + engine.state.download = "fail"; + await row(main, "notes.txt").getByRole("checkbox").check(); + await page.getByTestId("two-panes-move-other").click(); + await page.getByRole("alertdialog").getByRole("button", { name: "Move", exact: true }).click(); + await expect.poll(() => engine.log.filter((l) => l.startsWith("download")).length).toBe(1); + await page.waitForTimeout(2000); + expect(engine.log.some((l) => l.startsWith("delete"))).toBe(false); + await expect(row(main, "notes.txt")).toBeVisible(); + }); + + test("Tab goes from a row on one side to the list on the other; Enter opens a folder there", async ({ page }) => { + const { main } = await openFiles(page, { twoPanes: true }); + await expect(otherRow(page, "games")).toBeVisible(); + await row(main, "notes.txt").getByRole("checkbox").focus(); + await page.keyboard.press("Tab"); + await expect(otherRow(page, "games")).toBeFocused(); + await page.keyboard.press("Enter"); + await expect(other(page).getByTestId("two-panes-path")).toHaveText("/srv/games"); + // Enter there did not open anything on the PS5 side. + await expect(row(main, "notes.txt")).toBeVisible(); + await otherRow(page, "big.exfat").focus(); + await page.keyboard.press("Tab"); + await expect(row(main, "homebrew")).toBeFocused(); + }); + + test("right to left: the PS5 side is on the right, the other side on the left", async ({ page }) => { + await openFiles(page, { twoPanes: true, lang: "ar" }); + await expect(otherRow(page, "patch.pkg")).toBeVisible(); + const ps5Box = (await page.locator("[data-pane='ps5']").boundingBox())!; + const otherBox = (await other(page).boundingBox())!; + expect(otherBox.x + otherBox.width).toBeLessThanOrEqual(ps5Box.x + 1); + await shot(page, "rtl-ar"); + }); +}); + +test.describe("wide font", () => { + test.use({ viewport: { width: 1280, height: 800 } }); + + for (const lang of ["en", "de", "ru"]) { + test(`${lang}: the toggle and the Copy and Move buttons show their whole names`, async ({ page }) => { + const { main } = await openFiles(page, { twoPanes: true, lang }); + await page.addStyleTag({ content: WIDE_FONT }); + await expect(other(page).locator("[data-other-row]").first()).toBeVisible(); + const cut = await page + .locator("[data-testid='two-panes-actions'] button > span, [data-testid='fs-two-panes-toggle'] > span") + .evaluateAll((els) => + els.filter((el) => el.scrollWidth > el.clientWidth + 1).map((el) => el.textContent), + ); + expect(cut).toEqual([]); + // The header still holds its buttons on the row (nothing runs off the page). + const toggle = (await main.getByTestId("fs-two-panes-toggle").boundingBox())!; + expect(toggle.x + toggle.width).toBeLessThanOrEqual(1280); + await shot(page, `wide-font-${lang}`); + }); + } +}); + +for (const viewport of [ + { width: 390, height: 844 }, + { width: 820, height: 1180 }, +]) { + test.describe(`${viewport.width} wide, touch`, () => { + test.use({ viewport, hasTouch: true, isMobile: true }); + + test("Files stays one list: no toggle, no second side, even when it was left on", async ({ page }) => { + await openFiles(page, { twoPanes: true }); + await expect(page.getByTestId("fs-two-panes-toggle")).toHaveCount(0); + await expect(page.locator("[data-two-panes]")).toHaveCount(0); + await shot(page, `touch-${viewport.width}`); + }); + }); +} diff --git a/client/e2e/payload-sources.spec.ts b/client/e2e/payload-sources.spec.ts new file mode 100644 index 000000000..f775dcb03 --- /dev/null +++ b/client/e2e/payload-sources.spec.ts @@ -0,0 +1,292 @@ +import { expect, test, type Page, type Request } from "@playwright/test"; + +import { routeEngine, seedConsole } from "./fixtures/engine"; + +// Payloads › Catalog › Your payload sources, against a made-up engine: add a GitHub project, pick +// its file, download it (the card then shows the release, size and SHA-256), send it after a +// confirm that names the file, and remove the source. On a desktop, on a phone, and with a wide +// font. Nothing reaches GitHub or a console. +// +// PS5UPLOAD_SHOTS= also saves screenshots. + +const SHOTS = process.env.PS5UPLOAD_SHOTS; +// A wide font, as Linux CI and some Android phones have (the label specs do the same). +const WIDE_FONT = "*{font-family:Verdana,'DejaVu Sans',sans-serif!important}"; + +const ID = "custom-0a1b2c3d4e5f"; +const URL_ = "https://github.com/someone/a-payload-with-a-rather-long-project-name"; +const FILE = "a-payload-with-a-rather-long-project-name-v1.6.0.elf"; +const SHA = "3f9a".repeat(16); +const PATH = `/home/me/.local/share/ps5upload/payloads/${ID}/${FILE}`; + +const preview = { + id: ID, + name: "a-payload-with-a-rather-long-project-name", + kind: "github", + project_url: URL_, + already_added: false, + current_file: "", + releases: [ + { + tag: "v1.6.0", + name: "v1.6.0", + published_at: "2026-11-01T00:00:00Z", + prerelease: false, + html_url: `${URL_}/releases/tag/v1.6.0`, + files: [ + { name: FILE, size: 412_000, pattern: "a-payload-with-a-rather-long-project-name-v*.elf" }, + { name: "debug-build.elf", size: 900_000, pattern: "debug-build.elf" }, + ], + }, + ], +}; + +const base = { + id: ID, + name: preview.name, + kind: "github", + project_url: URL_, + owner: "someone", + repo: preview.name, + file_name: FILE, + file_pattern: "a-payload-with-a-rather-long-project-name-v*.elf", + update_available: false, +}; +const latest = { + tag: "v1.6.0", + release_name: "v1.6.0", + file_name: FILE, + size: 412_000, + published_at: "2026-11-01T00:00:00Z", + prerelease: false, + html_url: `${URL_}/releases/tag/v1.6.0`, +}; +const have = { + tag: "v1.6.0", + file_name: FILE, + size: 412_000, + sha256: SHA, + published_at: "2026-11-01T00:00:00Z", + downloaded_at: 1_800_000_000, + checksum: "matched", + path: PATH, +}; + +interface Engine { + asked: string[]; + sent: Array>; +} + +/** A made-up engine that keeps the source list: none, added, downloaded, removed. */ +async function open(page: Page, opts: { lang?: string } = {}): Promise { + const engine: Engine = { asked: [], sent: [] }; + let state: "none" | "added" | "downloaded" = "none"; + const current = () => + state === "none" ? [] : [{ ...base, latest, ...(state === "downloaded" ? { have } : {}) }]; + await seedConsole(page); + if (opts.lang) await page.addInitScript((l) => window.localStorage.setItem("ps5upload.lang", l), opts.lang); + await routeEngine(page, async (path, req: Request) => { + const method = req.method(); + if (path.startsWith("/api/payloads/repos")) engine.asked.push(`${method} ${path}`); + if (path === "/api/version") return { version: "12.6.34", caps: {} }; + if (path === "/api/ps5/status") return { ok: true }; + if (path === "/api/payloads") return { payloads: [], local: [] }; + if (path === "/api/payloads/sources") return { sources: [] }; + if (path === "/api/payloads/repos" && method === "GET") return { sources: current() }; + if (path === "/api/payloads/repos/preview") return preview; + if (path === "/api/payloads/repos" && method === "POST") { + state = "added"; + return { ...base }; + } + if (path === `/api/payloads/repos/${ID}/download`) { + state = "downloaded"; + return current()[0]; + } + if (path === `/api/payloads/repos/${ID}` && method === "DELETE") { + state = "none"; + return { removed: true }; + } + if (path === "/api/payload/send") { + engine.sent.push(JSON.parse(req.postData() ?? "{}")); + return { status: "sent", bytes: 412_000 }; + } + return undefined; + }); + await page.goto("/payloads?tab=catalog", { waitUntil: "domcontentloaded" }); + return engine; +} + +function section(page: Page) { + return page.locator("[data-scroll-root]:visible").getByTestId("payload-sources"); +} + +/** Nothing wider than the page, and no text out of the section's cards. */ +async function expectFits(page: Page, what: string) { + const sideways = await page.evaluate(() => document.documentElement.scrollWidth - window.innerWidth); + expect(sideways, `${what}: sideways scroll`).toBeLessThanOrEqual(0); + const out = await section(page) + .locator("[data-source-card], [data-testid='psrc-add']") + .evaluateAll((boxes) => + boxes + .filter((box) => { + const r = box.getBoundingClientRect(); + return [...box.querySelectorAll("span, dd, dt, button, label, p, h3")].some((el) => { + const b = el.getBoundingClientRect(); + return b.width > 0 && (b.left < r.left - 1 || b.right > r.right + 1); + }); + }) + .map((box) => box.textContent?.slice(0, 40)), + ); + expect(out, `${what}: text outside its card`).toEqual([]); + // No button label is cut. + const cut = await section(page) + .locator("button span") + .evaluateAll((els) => + els.filter((el) => el.scrollWidth > el.clientWidth + 1).map((el) => el.textContent), + ); + expect(cut, `${what}: cut labels`).toEqual([]); +} + +async function addPickDownloadSendRemove(page: Page, engine: Engine, shot: string) { + const s = section(page); + await expect(s.getByRole("heading", { name: "Your payload sources" })).toBeVisible({ timeout: 60_000 }); + await expect(s.getByText("Add a GitHub, Gitea or Forgejo project")).toBeVisible(); + // Opening Payloads is a check: the list is asked for with check=1. + await expect.poll(() => engine.asked.filter((a) => a.startsWith("GET /api/payloads/repos")).length).toBeGreaterThan(0); + + // Add: the address, then its files, then the pick. + await s.getByRole("button", { name: "Add a payload source" }).click(); + const form = s.getByTestId("psrc-add"); + await form.getByRole("textbox").fill(URL_); + await form.getByRole("button", { name: "Show its files" }).click(); + await expect(form.getByText("Pick the payload file (release v1.6.0):")).toBeVisible(); + await expect(form.getByRole("note")).toHaveText( + "PS5Upload will download and send whatever this project publishes under that name. Only add projects you trust.", + ); + await expect(form.getByRole("button", { name: "Add source" })).toBeDisabled(); + await form.getByRole("radio", { name: new RegExp(FILE.replace(/\./g, "\\.")) }).check(); + await expect(form.getByText("Newer releases: a file named like a-payload-with-a-rather-long-project-name-v*.elf")).toBeVisible(); + await expectFits(page, `${shot} add`); + if (SHOTS) await page.screenshot({ path: `${SHOTS}/sources-${shot}-add.png` }); + await form.getByRole("button", { name: "Add source" }).click(); + + // The card: the file, not downloaded yet, Download. + const card = s.locator(`[data-source-card="${ID}"]`); + await expect(card).toBeVisible(); + await expect(card.getByText("Not downloaded yet. Newest: v1.6.0")).toBeVisible(); + await card.getByRole("button", { name: "Download" }).click(); + + // Downloaded: exactly what would go to the console. + await expect(card.getByTestId("psrc-sha256")).toHaveText(SHA); + await expect(card.getByText("Matches the checksum its release lists.")).toBeVisible(); + await expect(card.getByRole("button", { name: "Download" })).toHaveCount(0); + await expectFits(page, `${shot} card`); + if (SHOTS) await page.screenshot({ path: `${SHOTS}/sources-${shot}-card.png` }); + + // Send asks first, naming the file, its release and SHA-256; Cancel sends nothing. + await card.getByRole("button", { name: "Send to PS5" }).click(); + const ask = page.getByRole("alertdialog"); + await expect(ask).toContainText(`Send ${FILE} to 192.168.1.100?`); + await expect(ask).toContainText(`SHA-256: ${SHA}`); + await expect(ask).toContainText("Release: v1.6.0"); + if (SHOTS) await page.screenshot({ path: `${SHOTS}/sources-${shot}-send.png` }); + await ask.getByRole("button", { name: "Cancel" }).click(); + expect(engine.sent).toHaveLength(0); + await card.getByRole("button", { name: "Send to PS5" }).click(); + await page.getByRole("alertdialog").getByRole("button", { name: "Send to PS5" }).click(); + await expect.poll(() => engine.sent.length).toBe(1); + expect(engine.sent[0]).toMatchObject({ host: "192.168.1.100", path: PATH }); + + // Remove asks, then the card goes. + await card.getByRole("button", { name: "Remove source" }).click(); + await page.getByRole("alertdialog").getByRole("button", { name: "Remove source" }).click(); + await expect(card).toHaveCount(0); + expect(engine.asked).toContain(`DELETE /api/payloads/repos/${ID}`); +} + +test.describe("desktop", () => { + test.use({ viewport: { width: 1280, height: 900 } }); + + test("add, pick the file, download, send after a confirm, remove", async ({ page }) => { + const engine = await open(page); + await addPickDownloadSendRemove(page, engine, "1280"); + }); + + test("with a wide font", async ({ page }) => { + const engine = await open(page); + await page.addStyleTag({ content: WIDE_FONT }); + await addPickDownloadSendRemove(page, engine, "1280-wide"); + }); + + test("a bad address is said plainly, and the built-in catalogue has no Download", async ({ page }) => { + await seedConsole(page); + await routeEngine(page, (path) => { + if (path === "/api/version") return { version: "12.6.34", caps: {} }; + if (path === "/api/payloads/repos") return { sources: [] }; + return undefined; + }); + // The engine refuses an http:// address with its code. + await page.route("**/api/payloads/repos/preview", (route) => + route.fulfill({ + status: 400, + contentType: "application/json", + body: JSON.stringify({ code: "url_not_https", error: "Only https:// addresses can be added." }), + }), + ); + await page.goto("/payloads?tab=catalog", { waitUntil: "domcontentloaded" }); + const s = section(page); + await s.getByRole("button", { name: "Add a payload source" }).click({ timeout: 60_000 }); + await s.getByRole("textbox").fill("http://github.com/someone/thing"); + await s.getByRole("button", { name: "Show its files" }).click(); + await expect(s.getByRole("alert")).toHaveText("Only https:// addresses can be added."); + }); + + test("a rate limit says when to try again", async ({ page }) => { + await seedConsole(page); + await routeEngine(page, (path) => { + if (path === "/api/version") return { version: "12.6.34", caps: {} }; + if (path === "/api/payloads/repos") + return { + sources: [ + { + ...base, + error: { code: "rate_limited", message: "GitHub is limiting", retry_at: 1_900_000_000 }, + }, + ], + }; + return undefined; + }); + await page.goto("/payloads?tab=catalog", { waitUntil: "domcontentloaded" }); + const card = section(page).locator(`[data-source-card="${ID}"]`); + await expect(card.getByRole("alert")).toContainText("Too many checks for now. Try again after", { timeout: 60_000 }); + }); +}); + +test.describe("phone", () => { + test.use({ viewport: { width: 390, height: 844 }, hasTouch: true, isMobile: true }); + + test("add, pick the file, download, send after a confirm, remove", async ({ page }) => { + const engine = await open(page); + await addPickDownloadSendRemove(page, engine, "390"); + }); + + test("with a wide font, in German", async ({ page }) => { + const engine = await open(page, { lang: "de" }); + await page.addStyleTag({ content: WIDE_FONT }); + const s = section(page); + await expect(s.getByRole("heading", { name: "Deine Payload-Quellen" })).toBeVisible({ timeout: 60_000 }); + await s.getByRole("button", { name: "Payload-Quelle hinzufügen" }).click(); + const form = s.getByTestId("psrc-add"); + await form.getByRole("textbox").fill(URL_); + await form.getByRole("button", { name: "Dateien anzeigen" }).click(); + await form.getByRole("radio").first().check(); + await expectFits(page, "390 de add"); + await form.getByRole("button", { name: "Quelle hinzufügen" }).click(); + const card = s.locator(`[data-source-card="${ID}"]`); + await card.getByRole("button", { name: "Herunterladen" }).click(); + await expect(card.getByTestId("psrc-sha256")).toHaveText(SHA); + await expectFits(page, "390 de card"); + if (SHOTS) await page.screenshot({ path: `${SHOTS}/sources-390-de-wide.png` }); + expect(engine.asked).toContain(`POST /api/payloads/repos/${ID}/download`); + }); +}); diff --git a/client/e2e/workshop-convert-survives-reload.spec.ts b/client/e2e/workshop-convert-survives-reload.spec.ts new file mode 100644 index 000000000..2d17c7668 --- /dev/null +++ b/client/e2e/workshop-convert-survives-reload.spec.ts @@ -0,0 +1,113 @@ +// #954: a convert started in the web UI keeps running in the engine when the page is closed or +// reloaded. The reopened page follows the same job in the same task, never "Interrupted", and +// shows its result when it ends. The engine here is a fake that answers the same routes. +import { expect, test, type Page } from "@playwright/test"; + +type StoredTask = { id: string; kind: string; status: string; engineJobId?: string }; + +async function convertTasks(page: Page): Promise { + return page.evaluate(() => { + const raw = window.localStorage.getItem("ps5upload.tasks.v1"); + const tasks = raw ? (JSON.parse(raw).tasks as StoredTask[]) : []; + return tasks.filter((t) => t.kind === "fpkg-convert"); + }); +} + +test("a convert keeps going through a page reload and is followed again (#954)", async ({ page }) => { + await page.setViewportSize({ width: 1400, height: 1200 }); + const builds: string[] = []; + // The engine's one build job: running until the test lets it finish. + const job = { done: false, polls: 0, startedAt: Date.now() }; + const json = (body: unknown, status = 200) => ({ status, contentType: "application/json", body: JSON.stringify(body) }); + await page.route( + (u) => u.pathname.startsWith("/api/"), + async (route) => { + const req = route.request(); + const path = new URL(req.url()).pathname; + const body = req.postDataJSON?.() as Record | null; + if (path === "/api/fpkg/inspect") + return route.fulfill( + json({ + source: `folder ${String(body?.source ?? "")}`, + files: 3, + bytes: 3 << 20, + content_id: "UP9000-PPSA01234_00-ASTROBOT00000000", + title: "Astro Bot", + planned_size: 3 << 20, + output_free: 1 << 40, + checks: [{ name: "eboot.bin", ok: true, detail: "ok" }], + }), + ); + if (path === "/api/fpkg/estimate") return route.fulfill(json({ error: "no" }, 500)); + if (path === "/api/fpkg/build") { + builds.push(String(body?.source)); + return route.fulfill(json({ job_id: "job-1" })); + } + // The Workshop jobs running now, as the engine lists them for a page that did not start them. + if (path === "/api/workshop/jobs") + return route.fulfill( + json(job.done || !builds.length ? [] : [{ job_id: "job-1", kind: "package", source: "/games/Astro", started_at_ms: job.startedAt }]), + ); + if (path === "/api/jobs/job-1") { + job.polls++; + if (!job.done) + return route.fulfill( + json({ + status: "running", + started_at_ms: job.startedAt, + bytes_sent: job.polls, + total_bytes: 1000, + stage: { id: "write", index: 2, count: 4, done: job.polls, total: 1000 }, + }), + ); + return route.fulfill( + json({ + status: "done", + started_at_ms: job.startedAt, + completed_at_ms: Date.now(), + elapsed_ms: 1, + tx_id_hex: "PPSA01234", + bytes_sent: 1000, + dest: "/out/Astro.pkg", + }), + ); + } + if (path === "/api/local/storage-roots") return route.fulfill(json(["/games"])); + if (path === "/api/local/list-dir") + return route.fulfill(json([{ name: "Astro", path: "/games/Astro", is_dir: true, size: 0 }])); + return route.fulfill(json({ error: "down" }, 503)); + }, + ); + await page.goto("/workshop"); + const main = page.getByRole("main"); + await expect(main.getByText("① Game")).toBeVisible({ timeout: 30_000 }); + + const source = main.locator("#fpkg-source"); + await source.fill("/games/Astro"); + await source.blur(); + await expect(main.getByText("Astro Bot").first()).toBeVisible(); + await main.getByRole("button", { name: "Convert only" }).first().click(); + await expect.poll(() => builds).toEqual(["/games/Astro"]); + await expect.poll(async () => (await convertTasks(page)).map((t) => [t.status, t.engineJobId])).toEqual([ + ["running", "job-1"], + ]); + const [before] = await convertTasks(page); + + // The page goes away mid-build and comes back: the engine's job never stopped. + await page.reload(); + await expect(main.getByText("① Game")).toBeVisible({ timeout: 30_000 }); + // Followed again in the task it had: one task, running, not "Interrupted". + await expect + .poll(async () => (await convertTasks(page)).map((t) => [t.id, t.status]), { timeout: 20_000 }) + .toEqual([[before.id, "running"]]); + await expect(page.getByText("Interrupted")).toHaveCount(0); + const pollsAfterReload = job.polls; + await expect.poll(() => job.polls).toBeGreaterThan(pollsAfterReload); + expect(builds).toEqual(["/games/Astro"]); + + // It ends: the reopened page shows its result, and the task says done. + job.done = true; + await expect(main.getByRole("button", { name: "Convert another game" })).toBeVisible({ timeout: 20_000 }); + await expect.poll(async () => (await convertTasks(page)).map((t) => t.status)).toEqual(["done"]); + expect(builds).toEqual(["/games/Astro"]); +}); diff --git a/client/package-lock.json b/client/package-lock.json index 951c6bde5..76c11fa94 100644 --- a/client/package-lock.json +++ b/client/package-lock.json @@ -1,12 +1,12 @@ { "name": "ps5upload-client", - "version": "12.6.32", + "version": "12.6.33", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "ps5upload-client", - "version": "12.6.32", + "version": "12.6.33", "dependencies": { "@tauri-apps/api": "^2.12.5", "@tauri-apps/plugin-dialog": "^2.8.4", diff --git a/client/package.json b/client/package.json index 8521ea10c..774ec2d18 100644 --- a/client/package.json +++ b/client/package.json @@ -2,7 +2,7 @@ "name": "ps5upload-client", "private": true, "type": "module", - "version": "12.6.32", + "version": "12.6.33", "description": "The all-in-one PS5 companion app.", "homepage": "https://github.com/phantomptr/ps5upload", "author": "PhantomPtr ", diff --git a/client/src-tauri/Cargo.lock b/client/src-tauri/Cargo.lock index a25379b4c..baca8e894 100644 --- a/client/src-tauri/Cargo.lock +++ b/client/src-tauri/Cargo.lock @@ -4743,7 +4743,7 @@ dependencies = [ [[package]] name = "ps5-dump-forge-exfat" -version = "12.6.32" +version = "12.6.33" dependencies = [ "ps5-dump-forge-patch", "ps5upload-fpkg", @@ -4752,14 +4752,14 @@ dependencies = [ [[package]] name = "ps5-dump-forge-patch" -version = "12.6.32" +version = "12.6.33" dependencies = [ "crc32fast", ] [[package]] name = "ps5-dump-forge-pfs" -version = "12.6.32" +version = "12.6.33" dependencies = [ "flate2", "ps5-dump-forge-patch", @@ -4768,7 +4768,7 @@ dependencies = [ [[package]] name = "ps5-dump-forge-ufs2" -version = "12.6.32" +version = "12.6.33" dependencies = [ "ps5-dump-forge-patch", "ps5upload-fpkg", @@ -4777,7 +4777,7 @@ dependencies = [ [[package]] name = "ps5-dump-forge-zstd" -version = "12.6.32" +version = "12.6.33" dependencies = [ "crc32fast", "getrandom 0.4.3", @@ -4788,7 +4788,7 @@ dependencies = [ [[package]] name = "ps5upload-archive" -version = "12.6.32" +version = "12.6.33" dependencies = [ "anyhow", "crc32fast", @@ -4798,7 +4798,7 @@ dependencies = [ [[package]] name = "ps5upload-ava1" -version = "12.6.32" +version = "12.6.33" dependencies = [ "anyhow", "ava1", @@ -4817,7 +4817,7 @@ dependencies = [ [[package]] name = "ps5upload-convert-core" -version = "12.6.32" +version = "12.6.33" dependencies = [ "blake3", "libc", @@ -4834,7 +4834,7 @@ dependencies = [ [[package]] name = "ps5upload-core" -version = "12.6.32" +version = "12.6.33" dependencies = [ "aes 0.9.2", "aes-gcm 0.11.0", @@ -4868,7 +4868,7 @@ dependencies = [ [[package]] name = "ps5upload-desktop" -version = "12.6.32" +version = "12.6.33" dependencies = [ "anyhow", "ava1", @@ -4910,7 +4910,7 @@ dependencies = [ [[package]] name = "ps5upload-engine" -version = "12.6.32" +version = "12.6.33" dependencies = [ "aes 0.9.2", "aes-gcm 0.11.0", @@ -4974,7 +4974,7 @@ dependencies = [ [[package]] name = "ps5upload-fpkg" -version = "12.6.32" +version = "12.6.33" dependencies = [ "aes 0.9.2", "crc32fast", @@ -4997,7 +4997,7 @@ dependencies = [ [[package]] name = "ps5upload-hub" -version = "12.6.32" +version = "12.6.33" dependencies = [ "axum", "base64 0.23.1", @@ -5011,7 +5011,7 @@ dependencies = [ [[package]] name = "ps5upload-pkg" -version = "12.6.32" +version = "12.6.33" dependencies = [ "aes 0.9.2", "blake3", @@ -5023,7 +5023,7 @@ dependencies = [ [[package]] name = "ps5upload-tailnet" -version = "12.6.32" +version = "12.6.33" dependencies = [ "cc", ] diff --git a/client/src-tauri/Cargo.toml b/client/src-tauri/Cargo.toml index 7bc1064c4..4b998f9bf 100644 --- a/client/src-tauri/Cargo.toml +++ b/client/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "ps5upload-desktop" -version = "12.6.32" +version = "12.6.33" description = "The all-in-one PS5 companion app." license = "GPL-3.0-or-later" edition = "2021" diff --git a/client/src-tauri/src/commands/agent_mcp.rs b/client/src-tauri/src/commands/agent_mcp.rs index 546b921d9..a0f0d7b15 100644 --- a/client/src-tauri/src/commands/agent_mcp.rs +++ b/client/src-tauri/src/commands/agent_mcp.rs @@ -665,8 +665,10 @@ mod tests { use std::os::unix::fs::PermissionsExt; fn scratch(name: &str) -> PathBuf { - let dir = std::env::temp_dir() - .join(format!("ps5upload-agent-mcp-{name}-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!( + "ps5upload-agent-mcp-{name}-{}", + std::process::id() + )); std::fs::create_dir_all(&dir).unwrap(); dir } diff --git a/client/src-tauri/src/commands/app_events.rs b/client/src-tauri/src/commands/app_events.rs index c2376e514..e0c0360d7 100644 --- a/client/src-tauri/src/commands/app_events.rs +++ b/client/src-tauri/src/commands/app_events.rs @@ -129,7 +129,7 @@ mod tests { use super::*; fn tmp(tag: &str) -> PathBuf { - let p = std::env::temp_dir().join(format!("appev-{tag}-{}", std::process::id())); + let p = crate::test_tmp::temp_path(format!("appev-{tag}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&p); std::fs::create_dir_all(&p).unwrap(); p diff --git a/client/src-tauri/src/commands/bug_report.rs b/client/src-tauri/src/commands/bug_report.rs index 8c6e97177..f35209625 100644 --- a/client/src-tauri/src/commands/bug_report.rs +++ b/client/src-tauri/src/commands/bug_report.rs @@ -954,7 +954,7 @@ mod tests { /// that the app log is correctly time-windowed. #[test] fn assemble_zip_bundles_everything_and_windows_the_log() { - let root = std::env::temp_dir().join(format!("ps5up-bugreport-{}", std::process::id())); + let root = crate::test_tmp::temp_path(format!("ps5up-bugreport-{}", std::process::id())); let _ = std::fs::remove_dir_all(&root); let logs = root.join("logs"); let engine = root.join("engine"); @@ -1083,7 +1083,7 @@ mod tests { /// Unticking sections drops them; report.json + README are always present. #[test] fn assemble_zip_respects_include_flags() { - let root = std::env::temp_dir().join(format!("ps5up-bugreport2-{}", std::process::id())); + let root = crate::test_tmp::temp_path(format!("ps5up-bugreport2-{}", std::process::id())); let _ = std::fs::remove_dir_all(&root); std::fs::create_dir_all(&root).unwrap(); let dest = root.join("out.zip"); @@ -1124,7 +1124,7 @@ mod tests { fn extras_the_bundle_already_has_do_not_fail_it() { // Every desktop report failed with "Duplicate filename: README.txt": the report // builder sends its own README.txt, and the bundle had already written one. - let root = std::env::temp_dir().join(format!("ps5up-bugreport4-{}", std::process::id())); + let root = crate::test_tmp::temp_path(format!("ps5up-bugreport4-{}", std::process::id())); let _ = std::fs::remove_dir_all(&root); std::fs::create_dir_all(&root).unwrap(); let dest = root.join("out.zip"); @@ -1173,7 +1173,7 @@ mod tests { #[test] fn extra_entries_are_redacted_and_bad_paths_listed_as_missing() { - let root = std::env::temp_dir().join(format!("ps5up-bugreport3-{}", std::process::id())); + let root = crate::test_tmp::temp_path(format!("ps5up-bugreport3-{}", std::process::id())); let _ = std::fs::remove_dir_all(&root); std::fs::create_dir_all(&root).unwrap(); let dest = root.join("out.zip"); @@ -1236,7 +1236,8 @@ mod tests { /// helper's PIN line is gone. #[test] fn logs_are_capped_and_cuts_named() { - let root = std::env::temp_dir().join(format!("ps5up-bugreport-cap-{}", std::process::id())); + let root = + crate::test_tmp::temp_path(format!("ps5up-bugreport-cap-{}", std::process::id())); let _ = std::fs::remove_dir_all(&root); std::fs::create_dir_all(root.join("e")).unwrap(); // Four engine logs of 5 MiB each: three fit at 4 MiB (the 12 MiB total), the oldest is left out. @@ -1363,7 +1364,7 @@ mod tests { #[test] fn engine_log_tail_starts_on_a_line_boundary() { - let root = std::env::temp_dir().join(format!("ps5upload-tail-{}", std::process::id())); + let root = crate::test_tmp::temp_path(format!("ps5upload-tail-{}", std::process::id())); let _ = std::fs::remove_dir_all(&root); std::fs::create_dir_all(&root).unwrap(); let p = root.join("engine.log"); diff --git a/client/src-tauri/src/commands/bug_screenshots.rs b/client/src-tauri/src/commands/bug_screenshots.rs index 2b7c5b58c..c55eda65d 100644 --- a/client/src-tauri/src/commands/bug_screenshots.rs +++ b/client/src-tauri/src/commands/bug_screenshots.rs @@ -192,7 +192,7 @@ mod tests { #[test] fn newest_first_ordering() { - let dir = std::env::temp_dir().join(format!("ps5up-shots-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("ps5up-shots-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); for n in [ @@ -209,7 +209,7 @@ mod tests { #[test] fn delete_removes_named_pngs_and_never_leaves_the_folder() { - let root = std::env::temp_dir().join(format!("ps5up-shots-del-{}", std::process::id())); + let root = crate::test_tmp::temp_path(format!("ps5up-shots-del-{}", std::process::id())); let _ = std::fs::remove_dir_all(&root); let dir = root.join("bug-screenshots"); std::fs::create_dir_all(&dir).unwrap(); diff --git a/client/src-tauri/src/commands/crash_reports.rs b/client/src-tauri/src/commands/crash_reports.rs index 442442465..6229dc051 100644 --- a/client/src-tauri/src/commands/crash_reports.rs +++ b/client/src-tauri/src/commands/crash_reports.rs @@ -139,7 +139,7 @@ mod tests { fn scratch(name: &str) -> PathBuf { let d = - std::env::temp_dir().join(format!("ps5upload-crashzip-{name}-{}", std::process::id())); + crate::test_tmp::temp_path(format!("ps5upload-crashzip-{name}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&d); std::fs::create_dir_all(&d).unwrap(); d diff --git a/client/src-tauri/src/commands/diag_log.rs b/client/src-tauri/src/commands/diag_log.rs index fcd0043e1..fa33216fa 100644 --- a/client/src-tauri/src/commands/diag_log.rs +++ b/client/src-tauri/src/commands/diag_log.rs @@ -263,7 +263,7 @@ mod tests { #[test] fn window_filter_keeps_unparseable_and_recent() { - let dir = std::env::temp_dir().join(format!("ps5up-diaglog-test-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("ps5up-diaglog-test-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); let p = dir.join("app-20260605.jsonl"); diff --git a/client/src-tauri/src/commands/local_fs.rs b/client/src-tauri/src/commands/local_fs.rs index 2c2f16168..2d94d996d 100644 --- a/client/src-tauri/src/commands/local_fs.rs +++ b/client/src-tauri/src/commands/local_fs.rs @@ -284,7 +284,7 @@ mod tests { #[tokio::test] async fn local_list_dir_sorts_dirs_first_then_files_case_insensitive() { - let tmp = std::env::temp_dir().join(format!("ps5_lf_{}", std::process::id())); + let tmp = crate::test_tmp::temp_path(format!("ps5_lf_{}", std::process::id())); let _ = std::fs::remove_dir_all(&tmp); std::fs::create_dir_all(tmp.join("Zsub")).unwrap(); std::fs::create_dir_all(tmp.join("alpha")).unwrap(); @@ -313,7 +313,7 @@ mod tests { } fn inbox_fixture(name: &str) -> (std::path::PathBuf, std::path::PathBuf) { - let tmp = std::env::temp_dir().join(format!("ps5u_inbox_{name}_{}", std::process::id())); + let tmp = crate::test_tmp::temp_path(format!("ps5u_inbox_{name}_{}", std::process::id())); let _ = std::fs::remove_dir_all(&tmp); let inbox = tmp.join("com.app-Inbox"); std::fs::create_dir_all(&inbox).unwrap(); @@ -709,7 +709,8 @@ mod paging_tests { #[test] fn pages_follow_the_listing_order_and_end_cleanly() { - let dir = std::env::temp_dir().join(format!("ps5upload-local-page-{}", std::process::id())); + let dir = + crate::test_tmp::temp_path(format!("ps5upload-local-page-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(dir.join("folder")).unwrap(); for name in ["b.txt", "A.txt", "c.txt"] { diff --git a/client/src-tauri/src/commands/persistence.rs b/client/src-tauri/src/commands/persistence.rs index 7ee5a6afc..7a0fe5dc3 100644 --- a/client/src-tauri/src/commands/persistence.rs +++ b/client/src-tauri/src/commands/persistence.rs @@ -558,7 +558,7 @@ mod tests { impl Scratch { fn new(name: &str) -> Self { - let dir = std::env::temp_dir().join(format!( + let dir = crate::test_tmp::temp_path(format!( "ps5upload-persistence-{name}-{}", std::process::id() )); diff --git a/client/src-tauri/src/commands/ps5_engine.rs b/client/src-tauri/src/commands/ps5_engine.rs index ca3c93dfe..adfb8daea 100644 --- a/client/src-tauri/src/commands/ps5_engine.rs +++ b/client/src-tauri/src/commands/ps5_engine.rs @@ -1605,6 +1605,9 @@ pub struct TransferDownloadReq { /// ops never honor this flag. Default false. #[serde(default)] pub unsafe_read: bool, + /// A move to a saved server: the engine deletes the source once the copy is checked there. + #[serde(default)] + pub remove_source: bool, } /// PS5 → host download streamed straight into a `.zip` (one pass, no scratch @@ -1651,6 +1654,7 @@ pub async fn transfer_download(req: TransferDownloadReq) -> Result std::path::PathBuf { let d = - std::env::temp_dir().join(format!("ps5upload-zip-test-{tag}-{}", std::process::id())); + crate::test_tmp::temp_path(format!("ps5upload-zip-test-{tag}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&d); std::fs::create_dir_all(&d).unwrap(); d diff --git a/client/src-tauri/src/commands/save_text_file.rs b/client/src-tauri/src/commands/save_text_file.rs index c43fb15a9..dec989f6e 100644 --- a/client/src-tauri/src/commands/save_text_file.rs +++ b/client/src-tauri/src/commands/save_text_file.rs @@ -252,8 +252,10 @@ mod replacing_tests { use super::*; fn scratch(name: &str) -> PathBuf { - let d = - std::env::temp_dir().join(format!("ps5upload-replacing-{name}-{}", std::process::id())); + let d = crate::test_tmp::temp_path(format!( + "ps5upload-replacing-{name}-{}", + std::process::id() + )); let _ = std::fs::remove_dir_all(&d); std::fs::create_dir_all(&d).unwrap(); d diff --git a/client/src-tauri/src/commands/self_install.rs b/client/src-tauri/src/commands/self_install.rs index 3e3e81f62..876297892 100644 --- a/client/src-tauri/src/commands/self_install.rs +++ b/client/src-tauri/src/commands/self_install.rs @@ -1656,7 +1656,7 @@ mod tests { } fn scratch(name: &str) -> PathBuf { - let d = std::env::temp_dir().join(format!("ps5upload-swap-{name}-{}", std::process::id())); + let d = crate::test_tmp::temp_path(format!("ps5upload-swap-{name}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&d); std::fs::create_dir_all(&d).unwrap(); d diff --git a/client/src-tauri/src/commands/update_android.rs b/client/src-tauri/src/commands/update_android.rs index 88160b1d0..c0394f4a5 100644 --- a/client/src-tauri/src/commands/update_android.rs +++ b/client/src-tauri/src/commands/update_android.rs @@ -278,7 +278,7 @@ mod tests { #[test] fn a_new_download_keeps_only_its_own_file_and_part() { - let dir = std::env::temp_dir().join(format!("ps5u-apk-others-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("ps5u-apk-others-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); for n in ["new.apk", "new.apk.part", "old.apk", "old.apk.part"] { @@ -297,7 +297,7 @@ mod tests { #[test] fn only_a_zip_counts_as_an_apk() { - let dir = std::env::temp_dir().join(format!("ps5u-apk-head-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("ps5u-apk-head-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); let p = dir.join("x.apk"); diff --git a/client/src-tauri/src/commands/update_fetch.rs b/client/src-tauri/src/commands/update_fetch.rs index edadbaa50..bc6b31787 100644 --- a/client/src-tauri/src/commands/update_fetch.rs +++ b/client/src-tauri/src/commands/update_fetch.rs @@ -411,7 +411,7 @@ mod tests { use std::sync::atomic::{AtomicUsize, Ordering}; fn scratch(name: &str) -> PathBuf { - let d = std::env::temp_dir().join(format!( + let d = crate::test_tmp::temp_path(format!( "ps5upload-update-fetch-{name}-{}", std::process::id() )); diff --git a/client/src-tauri/src/commands/update_files.rs b/client/src-tauri/src/commands/update_files.rs index 722eb1123..e497340e5 100644 --- a/client/src-tauri/src/commands/update_files.rs +++ b/client/src-tauri/src/commands/update_files.rs @@ -498,7 +498,7 @@ mod tests { use super::*; fn tmp(name: &str) -> PathBuf { - let d = std::env::temp_dir().join(format!( + let d = crate::test_tmp::temp_path(format!( "ps5upload-update-files-{name}-{}", std::process::id() )); diff --git a/client/src-tauri/src/commands/updates.rs b/client/src-tauri/src/commands/updates.rs index 3feea2c7f..a96ed79a4 100644 --- a/client/src-tauri/src/commands/updates.rs +++ b/client/src-tauri/src/commands/updates.rs @@ -1258,7 +1258,7 @@ mod checksum_tests { #[test] fn an_install_starts_only_a_checked_file_that_is_unchanged() { use sha2::Digest; - let dir = std::env::temp_dir().join(format!("ps5upload-verified-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("ps5upload-verified-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let file = dir.join("PS5Upload-9.9.9-mac-arm64.dmg"); std::fs::write(&file, b"the release").unwrap(); diff --git a/client/src-tauri/src/commands/usb_autoloader.rs b/client/src-tauri/src/commands/usb_autoloader.rs index ca85cb7c2..8dcba47d8 100644 --- a/client/src-tauri/src/commands/usb_autoloader.rs +++ b/client/src-tauri/src/commands/usb_autoloader.rs @@ -719,7 +719,7 @@ mod tests { struct Temp(PathBuf); impl Temp { fn new(tag: &str) -> Self { - let dir = std::env::temp_dir().join(format!( + let dir = crate::test_tmp::temp_path(format!( "ps5upload-usb-{tag}-{}-{:?}", std::process::id(), std::time::SystemTime::now() diff --git a/client/src-tauri/src/commands/user_config.rs b/client/src-tauri/src/commands/user_config.rs index 729a4ad1f..453a2551d 100644 --- a/client/src-tauri/src/commands/user_config.rs +++ b/client/src-tauri/src/commands/user_config.rs @@ -402,7 +402,8 @@ mod reset_tests { use super::*; fn scratch(name: &str) -> PathBuf { - let d = std::env::temp_dir().join(format!("ps5upload-reset-{name}-{}", std::process::id())); + let d = + crate::test_tmp::temp_path(format!("ps5upload-reset-{name}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&d); std::fs::create_dir_all(&d).unwrap(); d diff --git a/client/src-tauri/src/commands/user_config_tests.rs b/client/src-tauri/src/commands/user_config_tests.rs index ca54429ae..3e2df1b47 100644 --- a/client/src-tauri/src/commands/user_config_tests.rs +++ b/client/src-tauri/src/commands/user_config_tests.rs @@ -8,7 +8,7 @@ struct Scratch(PathBuf); impl Scratch { fn new(name: &str) -> Self { let dir = - std::env::temp_dir().join(format!("ps5upload-config-{name}-{}", std::process::id())); + crate::test_tmp::temp_path(format!("ps5upload-config-{name}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); Self(dir) } diff --git a/client/src-tauri/src/crash_hook.rs b/client/src-tauri/src/crash_hook.rs index 41f2091de..39c49047b 100644 --- a/client/src-tauri/src/crash_hook.rs +++ b/client/src-tauri/src/crash_hook.rs @@ -527,7 +527,7 @@ mod tests { #[test] fn a_report_is_a_txt_the_report_list_finds() { - let dir = std::env::temp_dir().join(format!("ps5upload-hook-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("ps5upload-hook-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let p = write_report_in(&dir, "hello").unwrap(); assert_eq!(std::fs::read_to_string(&p).unwrap(), "hello"); diff --git a/client/src-tauri/src/engine.rs b/client/src-tauri/src/engine.rs index 8cb2d6663..6860155bc 100644 --- a/client/src-tauri/src/engine.rs +++ b/client/src-tauri/src/engine.rs @@ -1561,7 +1561,7 @@ mod engine_log_tests { #[test] fn a_long_session_rotates_the_log_at_the_cap() { - let dir = std::env::temp_dir().join(format!("ps5upload-englog-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("ps5upload-englog-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); let path = dir.join("engine.log"); @@ -1591,7 +1591,7 @@ mod engine_log_tests { #[test] fn a_failed_rotation_is_not_tried_on_every_line() { use std::os::unix::fs::PermissionsExt; - let dir = std::env::temp_dir().join(format!("ps5upload-englog-ro-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("ps5upload-englog-ro-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); let path = dir.join("engine.log"); @@ -1653,7 +1653,8 @@ mod engine_log_generation_tests { #[test] fn rotation_keeps_the_older_files_and_drops_only_the_oldest() { - let dir = std::env::temp_dir().join(format!("ps5upload-englog-gen-{}", std::process::id())); + let dir = + crate::test_tmp::temp_path(format!("ps5upload-englog-gen-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); let path = dir.join("engine.log"); @@ -1807,7 +1808,7 @@ mod reaper_tests { // This test process listens on the port: wrongly killing what holds it would end the run. let held = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap(); let port = held.local_addr().unwrap().port(); - let dir = std::env::temp_dir().join("ps5upload-no-such-engine-folder"); + let dir = crate::test_tmp::temp_path("ps5upload-no-such-engine-folder"); reap_our_orphan_on(port, &dir).await; // Still bound, and the port still counts as taken: `start` moves to a free one. assert!(!loopback_port_free(port)); @@ -1912,7 +1913,7 @@ mod extract_tests { fn scratch(name: &str) -> PathBuf { let d = - std::env::temp_dir().join(format!("ps5upload-extract-{name}-{}", std::process::id())); + crate::test_tmp::temp_path(format!("ps5upload-extract-{name}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&d); std::fs::create_dir_all(&d).unwrap(); d diff --git a/client/src-tauri/src/lib.rs b/client/src-tauri/src/lib.rs index 4ec589a6d..1a644f024 100644 --- a/client/src-tauri/src/lib.rs +++ b/client/src-tauri/src/lib.rs @@ -879,7 +879,7 @@ mod asset_scope_tests { { let p = p.as_str().unwrap(); let raw = match p.strip_prefix("$TEMP/") { - Some(rest) => std::env::temp_dir().join(rest), + Some(rest) => crate::test_tmp::temp_path(rest), None => PathBuf::from(p), }; out.push(glob::Pattern::new(&raw.to_string_lossy()).unwrap()); @@ -930,7 +930,7 @@ mod asset_scope_tests { let clip = scratch.join("sub").join("clip.mp4"); std::fs::write(&clip, b"mp4").unwrap(); // A game folder's cover (Upload), wherever the folder is. - let other = std::env::temp_dir().join(format!("ps5upload-scope-{}", std::process::id())); + let other = crate::test_tmp::temp_path(format!("ps5upload-scope-{}", std::process::id())); let game = other.join("My Game").join("sce_sys"); std::fs::create_dir_all(&game).unwrap(); let icon = game.join("icon0.png"); @@ -960,7 +960,7 @@ mod asset_scope_tests { fn a_cover_is_served_in_any_letter_case_and_nothing_else_is() { let scope = scope(); let root = - std::env::temp_dir().join(format!("ps5upload-scope-case-{}", std::process::id())); + crate::test_tmp::temp_path(format!("ps5upload-scope-case-{}", std::process::id())); let _ = std::fs::remove_dir_all(&root); for (game, dir, icon) in [ ("Upper", "SCE_SYS", "ICON0.PNG"), @@ -1027,3 +1027,8 @@ mod profile_tests { ); } } + +// Test scratch paths removed when the test process exits (engine/test-support/test_tmp.rs). +#[cfg(test)] +#[path = "../../../engine/test-support/test_tmp.rs"] +mod test_tmp; diff --git a/client/src-tauri/src/migrate_6.rs b/client/src-tauri/src/migrate_6.rs index f2dd4b746..d82d2e49e 100644 --- a/client/src-tauri/src/migrate_6.rs +++ b/client/src-tauri/src/migrate_6.rs @@ -61,7 +61,7 @@ mod tests { use super::*; fn temp(tag: &str) -> std::path::PathBuf { - let d = std::env::temp_dir().join(format!("app-migrate6-{tag}-{}", std::process::id())); + let d = crate::test_tmp::temp_path(format!("app-migrate6-{tag}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&d); std::fs::create_dir_all(d.join("payload")).unwrap(); d diff --git a/client/src-tauri/src/mobile_log.rs b/client/src-tauri/src/mobile_log.rs index 459483001..1bae7bfbb 100644 --- a/client/src-tauri/src/mobile_log.rs +++ b/client/src-tauri/src/mobile_log.rs @@ -239,7 +239,7 @@ mod tests { #[test] fn rotates_past_the_cap_and_keeps_writing() { - let dir = std::env::temp_dir().join(format!("ps5u_mobile_log_{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("ps5u_mobile_log_{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); let path = dir.join("engine.log"); @@ -259,7 +259,7 @@ mod tests { #[test] fn appends_to_what_an_earlier_run_left() { - let dir = std::env::temp_dir().join(format!("ps5u_mobile_log2_{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("ps5u_mobile_log2_{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); let path = dir.join("engine.log"); diff --git a/client/src-tauri/src/opened_files.rs b/client/src-tauri/src/opened_files.rs index 45a7e20c3..9cf870066 100644 --- a/client/src-tauri/src/opened_files.rs +++ b/client/src-tauri/src/opened_files.rs @@ -99,7 +99,7 @@ mod tests { fn scratch(name: &str) -> PathBuf { let dir = - std::env::temp_dir().join(format!("ps5upload-opened-{}-{}", name, std::process::id())); + crate::test_tmp::temp_path(format!("ps5upload-opened-{}-{}", name, std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); dir diff --git a/client/src-tauri/src/window_state.rs b/client/src-tauri/src/window_state.rs index bafc2e64b..97608f9d9 100644 --- a/client/src-tauri/src/window_state.rs +++ b/client/src-tauri/src/window_state.rs @@ -603,7 +603,7 @@ mod tests { #[test] fn a_write_then_read_round_trips_and_leaves_no_temporary_file() { - let dir = std::env::temp_dir().join(format!("ps5u-window-state-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("ps5u-window-state-{}", std::process::id())); let path = dir.join(FILE_NAME); let s = saved(10.0, 20.0, 1300.0, 850.0); write(&path, &s).unwrap(); diff --git a/client/src-tauri/tauri.conf.json b/client/src-tauri/tauri.conf.json index cd1bc4a7c..54dd15d59 100644 --- a/client/src-tauri/tauri.conf.json +++ b/client/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "PS5Upload", - "version": "12.6.32", + "version": "12.6.33", "identifier": "com.phantomptr.ps5upload", "build": { "beforeDevCommand": "npm run dev:vite", diff --git a/client/src/api/collection.ts b/client/src/api/collection.ts index 2cb228686..f5e3b0322 100644 --- a/client/src/api/collection.ts +++ b/client/src/api/collection.ts @@ -86,8 +86,12 @@ export interface CopyCheck { path: string; state: "queued" | "running" | "ok" | "problems" | "failed" | "cancelled"; method: "" | "package" | "archive" | "files" | "bytes"; + /** Of the whole check: a package's two reads (its blocks, then the PlayGo chunk CRCs) count + * in one total (#951). */ bytes_done: number; bytes_total: number; + /** A package check while it runs: which read it is on. Absent from an engine that doesn't say. */ + phase?: "blocks" | "playgo"; files_done: number; files_total: number; problems: CopyProblem[]; diff --git a/client/src/api/payloadSources.ts b/client/src/api/payloadSources.ts new file mode 100644 index 000000000..0aa9c3d2a --- /dev/null +++ b/client/src/api/payloadSources.ts @@ -0,0 +1,156 @@ +// Payload sources the user adds (a GitHub, Gitea or Forgejo project that publishes payload files in +// its releases), through the engine's /api/payloads/repos routes (engine payloads_api.rs, core +// payload_library/user_sources.rs). Plain fetches against the engine origin, so the desktop app, +// the phones and the browser build take the same path, and the file lands in the engine's +// payload folder, which the send reads. + +import { getEngineUrl } from "../state/engine"; + +/** Why a source call failed: `code` is stable (the app words it), `message` is the engine's + * English. `retry_at`: when the host said to ask again (seconds since the Unix epoch). */ +export interface SourceProblem { + code: string; + message: string; + retry_at?: number; +} + +export interface SourceHaveCopy { + /** The release it came from; empty for a copy an older version saved. */ + tag: string; + file_name: string; + size: number; + /** SHA-256 of the file as it is on disk: what a send gives the console. */ + sha256: string; + published_at: string; + downloaded_at: number; + /** "matched", "none", or "" for a copy from an older version. */ + checksum: string; + /** Where it is, on the engine's computer: what Send uses. */ + path: string; +} + +export interface SourceLatestFile { + tag: string; + release_name: string; + file_name: string; + size: number; + published_at: string; + prerelease: boolean; + html_url: string; +} + +export interface PayloadSource { + id: string; + name: string; + kind: "github" | "gitea"; + project_url: string; + owner: string; + repo: string; + /** The picked file; "" for a source added before 12.6.0, which asks for it. */ + file_name: string; + /** Which names newer releases may use: the picked name with `*` for each version part. */ + file_pattern: string; + have?: SourceHaveCopy; + latest?: SourceLatestFile; + update_available: boolean; + checked_age_secs?: number; + error?: SourceProblem; +} + +export interface SourcePreviewFile { + name: string; + size: number; + pattern: string; +} + +export interface SourcePreviewRelease { + tag: string; + name: string; + published_at: string; + prerelease: boolean; + html_url: string; + files: SourcePreviewFile[]; +} + +export interface SourcePreview { + id: string; + name: string; + kind: "github" | "gitea"; + project_url: string; + already_added: boolean; + current_file: string; + /** Newest first; only releases with a .elf or .bin file. */ + releases: SourcePreviewRelease[]; +} + +/** A refused source call, with the engine's code and, for a rate limit, when to try again. */ +export class PayloadSourceError extends Error { + readonly code: string; + readonly retryAt: number | null; + constructor(problem: SourceProblem) { + super(problem.message); + this.name = "PayloadSourceError"; + this.code = problem.code; + this.retryAt = typeof problem.retry_at === "number" ? problem.retry_at : null; + } + + get problem(): SourceProblem { + return { code: this.code, message: this.message, retry_at: this.retryAt ?? undefined }; + } +} + +/** A download can take a while on a slow line; the engine ends a stalled one itself. */ +const DOWNLOAD_TIMEOUT_MS = 10 * 60_000; + +async function call(method: string, path: string, body?: unknown, timeoutMs = 45_000): Promise { + const res = await fetch(`${getEngineUrl()}${path}`, { + method, + headers: body === undefined ? undefined : { "content-type": "application/json" }, + body: body === undefined ? undefined : JSON.stringify(body), + signal: AbortSignal.timeout(timeoutMs), + }); + const v = (await res.json().catch(() => ({}))) as T & { error?: string; code?: string; retry_at?: number }; + if (!res.ok) { + throw new PayloadSourceError({ + code: v.code ?? `http_${res.status}`, + message: v.error || `request failed (${res.status})`, + retry_at: v.retry_at, + }); + } + return v; +} + +/** The sources. `check`: read each one's newest releases (kept ten minutes unless `force`); + * without it nothing asks the network. */ +export async function listPayloadSources(check = false, force = false): Promise { + const q = check ? `?check=1${force ? "&force=1" : ""}` : ""; + const v = await call<{ sources?: PayloadSource[] }>("GET", `/api/payloads/repos${q}`, undefined, 120_000); + return Array.isArray(v.sources) ? v.sources : []; +} + +/** A project's newest releases with payload files, for picking the file. Saves nothing. */ +export function previewPayloadSource(url: string): Promise { + return call("POST", "/api/payloads/repos/preview", { url }); +} + +/** Add a project with the picked file (adding one again changes its file). Asks no network. */ +export function addPayloadSource(url: string, fileName: string): Promise { + return call("POST", "/api/payloads/repos", { url, file_name: fileName }); +} + +/** Change a source's file, or pick it for one added before 12.6.0. */ +export function setPayloadSourceFile(id: string, fileName: string): Promise { + return call("PUT", `/api/payloads/repos/${encodeURIComponent(id)}/file`, { file_name: fileName }); +} + +/** Download the newest release's file into the payload folder (checked before it replaces the + * copy there). */ +export function downloadPayloadSource(id: string): Promise { + return call("POST", `/api/payloads/repos/${encodeURIComponent(id)}/download`, {}, DOWNLOAD_TIMEOUT_MS); +} + +/** Remove a source and its downloaded file. */ +export async function removePayloadSource(id: string): Promise { + const v = await call<{ removed?: boolean }>("DELETE", `/api/payloads/repos/${encodeURIComponent(id)}`); + return v.removed === true; +} diff --git a/client/src/api/ps5.ts b/client/src/api/ps5.ts index 39fbcc1d1..3436b15d1 100644 --- a/client/src/api/ps5.ts +++ b/client/src/api/ps5.ts @@ -1095,6 +1095,9 @@ export async function startTransferDownload( transferAddr: string, kind: "file" | "folder", unsafeRead: boolean = false, + /** A move to a saved server (`destDir` is `remote://…`): the engine deletes the source on the + * PS5 only once the copy is complete and checked there. */ + removeSource: boolean = false, ): Promise { const res = await invoke<{ job_id: string }>("transfer_download", { req: { @@ -1103,6 +1106,7 @@ export async function startTransferDownload( addr: transferAddr, kind, unsafe_read: unsafeRead, + ...(removeSource ? { remove_source: true } : {}), }, }); return res.job_id; diff --git a/client/src/components/LocalPathPicker.tsx b/client/src/components/LocalPathPicker.tsx index c4966970b..f27521fa0 100644 --- a/client/src/components/LocalPathPicker.tsx +++ b/client/src/components/LocalPathPicker.tsx @@ -16,11 +16,11 @@ import { import { Button } from "."; import { localFs, storageAccessUsesPrompt } from "../api/localFs"; -import { remoteApi, RemoteApiError } from "../api/remote"; +import { RemoteApiError } from "../api/remote"; import { parentOf, fmtSize } from "../lib/pathBrowser"; import { displayPath, remotePath } from "../lib/remotePath"; -import { hostOf, transferAddr } from "../lib/addr"; -import { fsListDir } from "../api/ps5"; +import { hostOf } from "../lib/addr"; +import { CONSOLE_ROOTS, listPlace, serverParent, type Place } from "../lib/placeList"; import { useConnectionsStore } from "../state/connections"; import { useLocalPickerStore } from "../state/localPicker"; import { usePackageViewer } from "../state/packageViewer"; @@ -389,26 +389,12 @@ function writeLastDir(id: string, dir: string) { } } -/** "/games/ps5" → "/games"; "/" has no parent. */ -function serverParent(path: string): string | null { - const t = path.replace(/\/+$/, ""); - if (!t) return null; - const i = t.lastIndexOf("/"); - return i <= 0 ? "/" : t.slice(0, i); -} - -/** Where a game can live on the console: internal storage and the external drives. */ -const CONSOLE_ROOTS = ["/data", "/mnt/ext0", "/mnt/ext1", "/mnt/usb0", "/mnt/usb1"]; /** A pick on the console, as the converter reads it: `ps5://`. */ export function consolePickResult(host: string, path: string): string { return `ps5://${hostOf(host)}${path.startsWith("/") ? path : `/${path}`}`; } -function joinServer(dir: string, name: string): string { - return `${dir.replace(/\/+$/, "")}/${name}`; -} - /** Whether the picker steps aside for the package viewer. It does only for a View pressed in * the picker itself, and only while that viewer is open: closing the viewer returns to the * picker in the folder it was left in, instead of making the user find the folder again. */ @@ -457,33 +443,15 @@ export function LocalPathPicker() { setError(null); setHint(null); try { - if (consoleHost) { - const list = await fsListDir(transferAddr(consoleHost), path); - setEntries( - list.map((e) => ({ - name: e.name, - path: joinServer(path, e.name), - is_dir: e.kind === "dir", - size: e.size ?? 0, - })), - ); - setCursor(null); - } else if (connectionId) { - const page = await remoteApi.listDir(remotePath(connectionId, path), more); - const list = page.entries.map((e) => ({ - name: e.name, - path: joinServer(path, e.name), - is_dir: e.is_dir, - size: e.size, - })); - setEntries((prev) => (more ? [...prev, ...list] : list)); - setCursor(page.next_cursor); - writeLastDir(connectionId, path); - } else { - const page = await localFs.listDirPage(path, more ? Number(more) : 0); - setEntries((prev) => (more ? [...prev, ...page.entries] : page.entries)); - setCursor(page.next === null ? null : String(page.next)); - } + const place: Place = consoleHost + ? { kind: "console", host: consoleHost } + : connectionId + ? { kind: "server", id: connectionId } + : { kind: "computer" }; + const page = await listPlace(place, path, more); + setEntries((prev) => (more ? [...prev, ...page.entries] : page.entries)); + setCursor(page.more); + if (connectionId) writeLastDir(connectionId, path); setCwd(path); if (!more) setRevealed(childToReveal(from, path)); cwdRef.current = path; diff --git a/client/src/console/files/Files.test.tsx b/client/src/console/files/Files.test.tsx index 6a84d5e65..03aa53180 100644 --- a/client/src/console/files/Files.test.tsx +++ b/client/src/console/files/Files.test.tsx @@ -19,6 +19,7 @@ import { ConflictDialog } from "./ConflictDialog"; import { IntoItselfError, renameEntry } from "./move"; import { TextPrompt } from "./TextPrompt"; import { PickerWait } from "./PathPicker"; +import { ReplaceError } from "./replace"; import { UploadDialog } from "./UploadDialog"; import type { DirState, Entry } from "./useDir"; @@ -434,6 +435,12 @@ describe("Files listing controls", () => { expect(pasteMessage({ ...base, halted: ["/data/a/G"], skipped: ["/data/a/G", "/data/a/H"] })?.text).toBe( `${t("cw_files_paste_halted", { name: "G" })} ${t("cw_files_batch_stopped", { n: 1 })}`, ); + // A move to a share that kept the original says so, and why when the tree held links (#953). + const kept = (why: string | null) => + pasteMessage({ ...base, done: ["/data/g"], notes: [new ReplaceError("moved_left", "g", { why })] })?.text; + expect(kept(null)).toContain(t("cw_files_move_source_left", { name: "g" })); + expect(kept(null)).not.toContain(t("cw_files_move_has_links")); + expect(kept("links")).toContain(`${t("cw_files_move_source_left", { name: "g" })} ${t("cw_files_move_has_links")}`); }); }); diff --git a/client/src/console/files/Files.tsx b/client/src/console/files/Files.tsx index d1c9436c1..bc3fc1005 100644 --- a/client/src/console/files/Files.tsx +++ b/client/src/console/files/Files.tsx @@ -240,6 +240,8 @@ function replaceErrorText(e: ReplaceError): string { return t("cw_files_replace_old_left", { name: e.item, old: baseName(e.old ?? "") }); case "source_left": return t("cw_files_replace_source_left", { name: e.item }); + case "moved_left": + return t("cw_files_move_source_left", { name: e.item }) + (e.why ? ` ${t("cw_files_move_has_links")}` : ""); case "temp_left": return t("cw_files_replace_temp_left", { temp: baseName(e.temp ?? "") }); } @@ -923,6 +925,7 @@ function askView(p: FilesViewProps) { title={t(a.op === "copy" ? "cw_files_copy_to" : "cw_files_move_to")} subtitle={namesTitle(a.names)} volumes={p.volumes ?? []} + shares={isSmbPath(path) ? undefined : (p.shares ?? undefined)} start={isSmbPath(path) ? null : path} onPick={(d) => p.onPicked(a.op, a.names, d)} onCancel={p.onDismiss} @@ -1672,16 +1675,16 @@ export function Files({ ctx }: { ctx: SectionContext }) { * in the status line, Stop cancels the item running. Conflicts are asked like a paste's. */ const runTransfer = useCallback( - (items: { path: string; dir: boolean }[], dest: string) => { + (items: { path: string; dir: boolean }[], dest: string, move = false) => { if (currentBatch() || !items.length) return; setMessage(null); setSelecting(false); setSelected([]); const run = startBatch( - "copy", + move ? "move" : "copy", items.length, (ctl) => - transferItems(items, dest, { decide: askConflict, onBytes: ctl.onBytes }, batchOptions(ctl)), + transferItems(items, dest, { decide: askConflict, onBytes: ctl.onBytes, move }, batchOptions(ctl)), items.map((i) => i.path).concat(dest), true, ); @@ -1700,16 +1703,16 @@ export function Files({ ctx }: { ctx: SectionContext }) { const onPicked = useCallback( (op: "copy" | "move", names: string[], destDir: string) => { setAsk(null); + if (path == null) return; + const kinds = new Map(dir.entries.map((e) => [e.name, e.kind])); + const items = () => names.map((n) => ({ path: joinPath(path, n), dir: kinds.get(n) === "dir" })); if (isSmbPath(path)) { // Copy to… from a share: a console folder (the picker shows only the console's drives). - if (op !== "copy" || isSmbPath(destDir)) return; - const kinds = new Map(dir.entries.map((e) => [e.name, e.kind])); - runTransfer( - names.map((n) => ({ path: joinPath(path, n), dir: kinds.get(n) === "dir" })), - destDir, - ); + if (op === "copy" && !isSmbPath(destDir)) runTransfer(items(), destDir); return; } + // To a share (#953): a move deletes each original once its copy is complete. + if (isSmbPath(destDir)) return runTransfer(items(), destDir, op === "move"); runBatch(op, names, (items, opts) => (op === "copy" ? copyItems : moveItems)(items, destDir, opts), destDir); }, [runBatch, runTransfer, path, dir.entries], diff --git a/client/src/console/files/PathPicker.tsx b/client/src/console/files/PathPicker.tsx index 3f114f50b..678953afe 100644 --- a/client/src/console/files/PathPicker.tsx +++ b/client/src/console/files/PathPicker.tsx @@ -1,11 +1,12 @@ import { useCallback, useEffect, useRef, useState } from "react"; -import { ArrowUp, Check, File as FileIcon, Folder, HardDrive, RotateCw } from "lucide-react"; +import { ArrowUp, Check, File as FileIcon, Folder, HardDrive, Network, RotateCw } from "lucide-react"; import { isDrive, volumeLabel, type Volume } from "../home/Home"; import { focusElement } from "../nav"; import { t } from "../strings"; import { Modal } from "../ui/Modal"; import { filesErrorText } from "./Files"; import { joinPath, upFrom } from "./move"; +import { isSmbPath, smbSegments, smbUp, type SmbShare } from "./smb"; import { useDir, type DirState } from "./useDir"; /** A folder still being read, or why it could not be, with Retry (it said "Loading…" for good). */ @@ -37,6 +38,7 @@ export function PathPicker({ onPick, onCancel, pickFile, + shares, }: { title: string; /** What is being copied or moved (a name, or "3 items"). */ @@ -48,6 +50,8 @@ export function PathPicker({ onCancel: () => void; /** Files with a name it accepts are listed too, and picked (their path) when pressed. */ pickFile?: (name: string) => boolean; + /** Saved network shares, offered after the drives (a copy or move to one: #953). */ + shares?: SmbShare[]; }) { const [path, setPath] = useState(start); const dir = useDir(path); @@ -73,7 +77,7 @@ export function PathPicker({ if (path == null) onCancel(); else { moved.current = true; - setPath(upFrom(path, volumes)); + setPath(isSmbPath(path) ? smbUp(path) : upFrom(path, volumes)); } }, [path, volumes, onCancel]); @@ -83,7 +87,7 @@ export function PathPicker({

{subtitle}

- {path ?? t("cw_files_pick_drive")} + {path == null ? t("cw_files_pick_drive") : isSmbPath(path) ? smbSegments(path, shares ?? []).map((x) => x.label).join("/") : path} {path != null ? ( - )) + )).concat( + (shares ?? []).map((s) => ( +
  • + +
  • + )), + ) : folders.map((e) => (
  • + {onServer && servers.length > 0 && ( +
    +
    + {tr("fs_move_servers", undefined, "Saved servers")} +
    +
    + {servers.map((c) => ( +
    + + {c.name} + + +
    + ))} +
    +

    + {tr( + "fs_move_server_hint", + undefined, + "A move copies to the server, checks the copy, then removes the originals from the PS5.", + )} +

    +
    + )} + Promise; + /** Files' Add files, into the folder shown. */ + upload: (paths: string[], known: FsPickedItem[]) => Promise; + clearSelection: () => void; + refresh: () => void; +} + +const join = (dir: string, name: string) => `${dir === "/" ? "" : dir.replace(/\/+$/, "")}/${name}`; + +function blockText(tr: ReturnType, block: PaneBlock): string { + if (block === "no-delete-server") + return tr("two_panes_no_move_server", undefined, "No Move from here: the app doesn't delete files on saved servers."); + if (block === "files-only") + return tr( + "two_panes_move_files_only", + undefined, + "Move takes files only here: the app can't check every file of a copied folder. Copy folders.", + ); + return isTauriEnv() + ? tr("two_panes_no_move_computer", undefined, "No Move from here: the app never deletes files on this computer.") + : tr("two_panes_no_move_app_computer", undefined, "No Move from here: the app never deletes files on its computer."); +} + +/** The PS5 listing (children) and the other side, with Copy and Move between them. */ +export function TwoPanes({ + ps, + servers, + hidden, + children, +}: { + ps: PsSide; + servers: Connection[]; + /** A view (search, space, snapshots) covers the listing: the other side steps aside too. */ + hidden: boolean; + children: ReactNode; +}) { + const tr = useTr(); + const { confirm, dialog: confirmNode } = useConfirm(); + const profiles = useRosterStore((s) => s.profiles); + const here = hostOf(ps.host); + const consoles = useMemo(() => profiles.filter((p) => hostOf(p.host) !== here), [profiles, here]); + const nameOfConsole = useCallback( + (h: string) => profiles.find((p) => hostOf(p.host) === hostOf(h))?.name || hostOf(h), + [profiles], + ); + + const pane = useOtherPane(here, servers); + const { place, dir } = pane; + const placeName = !place + ? "" + : place.kind === "computer" + ? computerLabel(tr) + : place.kind === "server" + ? (servers.find((s) => s.id === place.id)?.name ?? place.id) + : nameOfConsole(place.host); + const psName = nameOfConsole(here); + + const [starting, setStarting] = useState(false); + const sourceOf = (toward: Toward): PaneItem[] => + toward === "other" + ? ps.selected + : pane.entries + .filter((e) => pane.selected.has(e.name)) + .map((e) => ({ name: e.name, path: e.path, isDir: e.is_dir, size: e.size })); + + const run = async (toward: Toward, op: PaneOp) => { + if (!place || dir === null) return; + const items = sourceOf(toward); + const route = paneRoute(place, toward, op, items.some((i) => i.isDir)); + if (!route.ok) return; + if (items.length === 0) return; + const fromDir = ps.path; + const toDir = toward === "other" ? dir : ps.path; + setStarting(true); + try { + // Names already in the destination are named before anything runs. Into the PS5 from + // this computer or a server, Add files asks about each itself. + if (route.via !== "upload") { + const destNames = toward === "other" ? pane.entries.map((e) => e.name) : ps.names; + const clash = namesAlreadyThere(items.map((i) => i.name), destNames); + if (clash.length > 0) { + const ok = await confirm({ + title: tr("two_panes_replace_title", undefined, "Replace what is already there?"), + message: tr( + "two_panes_replace_body", + undefined, + "These are already in the folder they go to, and are replaced:", + ), + details: clash, + confirmLabel: tr("two_panes_replace_ok", undefined, "Replace"), + destructive: true, + }); + if (!ok) return; + } + } + if (op === "move") { + const srcHost = toward === "other" ? here : place.kind === "console" ? place.host : null; + const kept = srcHost + ? await krakenKeptPaths(srcHost, items.map((i) => ({ path: i.path, isDir: i.isDir }))).catch(() => []) + : []; + const ok = await confirm({ + title: tr("two_panes_move_ask", undefined, "Move the ticked items?"), + message: + tr( + "two_panes_move_body", + undefined, + "Each item is copied first. The original is deleted only after its copy is there in full.", + ) + + (kept.length > 0 + ? `\n\n${tr( + "fs_delete_kraken_warning", + { n: kept.length }, + "Kraken Mount uses {n} of these as games: deleting them removes those games from the PS5.", + )}` + : ""), + details: items.map((i) => i.name), + confirmLabel: tr("two_panes_move_ok", undefined, "Move"), + }); + if (!ok) return; + } + } finally { + setStarting(false); + } + + if (route.via === "upload") { + ps.clearSelection(); + pane.clearSelection(); + await ps.upload( + items.map((i) => placeTransferPath(place, i.path)), + items.map((i) => ({ src: placeTransferPath(place, i.path), kind: i.isDir ? "folder" : "file" })), + ); + return; + } + + // Each copy, how it ends, and how it is checked. + let copy: (item: PaneItem) => Promise; + const unsettled = new Set(); + let destPlace: Place; + if (route.via === "console-send") { + const otherHost = (place as { kind: "console"; host: string }).host; + const from = toward === "other" ? here : otherHost; + const to = toward === "other" ? otherHost : here; + destPlace = { kind: "console", host: to }; + const ids = queueConsoleSend( + from, + to, + items.map((i) => ({ path: i.path, name: i.name, size: i.isDir ? 0 : i.size, isDir: i.isDir })), + items.map((i) => join(toDir, i.name)), + ); + pushNotification( + "info", + tr("fs_send_queued", { n: items.length, name: nameOfConsole(to) }, `${items.length} queued for ${nameOfConsole(to)}`), + ); + const ends = new Map(items.map((it, i) => [it, whenQueueRowEnds(ids[i])])); + copy = async (item) => { + const end = await ends.get(item)!; + if (end.status !== "done") return "failed"; + // The console has not confirmed saving every file: the source stays, to send again. + if (!mayDeleteSourceAfterUpload({ deleteSourceAfterUpload: true }, end.row.live)) unsettled.add(item.path); + return "done"; + }; + } else { + destPlace = place; + const server = route.via === "download-server" ? servers.find((s) => s.id === (place as { id: string }).id) : undefined; + // A move to a saved server is the engine's own (#953): it checks every file's size and + // every folder on the server, and only then deletes the source. A job that ends done has + // done all of that; one that fails keeps the source. + const into = { dir: placeTransferPath(place, dir), from: fromDir, move: !!route.engineMoves }; + copy = (item) => ps.download(item, into, server); + } + if (toward === "other") ps.clearSelection(); + else pane.clearSelection(); + + const srcAddr = consoleAddr(toward === "other" ? here : (place as { host: string }).host); + const result = await runPaneTransfer(items, route.engineMoves ? "copy" : op, { + copy, + verify: async (item) => { + if (unsettled.has(item.path)) return false; + const found = await findInPlace(destPlace, toDir, item.name); + return copyLooksWhole(item, found); + }, + removeSource: (item) => fsDelete(srcAddr, item.path), + }); + + // What landed shows on both sides: the copy where it went, and a move's gap where it was. + if (toward === "other" || op === "move") void pane.reload(); + if (toward === "ps5" || op === "move") ps.refresh(); + if (op !== "move") return; + const names = (list: PaneItem[]) => list.map((i) => i.name).join(", "); + const srcHostForNote = toward === "other" ? here : (place as { host: string }).host; + if (result.unverified.length > 0) + pushNotification( + "warning", + withConsolePrefix( + srcHostForNote, + tr("two_panes_unverified", undefined, "Copied, but the original was kept: the copy could not be checked"), + ), + { body: names(result.unverified) }, + ); + if (result.notRemoved.length > 0) + pushNotification( + "warning", + withConsolePrefix( + srcHostForNote, + tr("two_panes_not_removed", undefined, "Copied, but the original could not be deleted"), + ), + { body: names(result.notRemoved) }, + ); + if (result.finished.length > 0) + pushNotification( + "success", + tr("two_panes_moved", { count: result.finished.length, place: toward === "other" ? placeName : psName }, "Moved {count} items to {place}"), + ); + }; + + // Tab from a row on one side goes to the list on the other (and Shift+Tab back). + const rootRef = useRef(null); + const onKeyDown = (ev: React.KeyboardEvent) => { + if (ev.key !== "Tab" || ev.altKey || ev.ctrlKey || ev.metaKey || hidden) return; + const t = ev.target as HTMLElement; + const inLeft = !!t.closest("[data-fs-name]") && !!t.closest("[data-pane='ps5']"); + const inRight = !!t.closest("[data-other-row]"); + if (!inLeft && !inRight) return; + const root = rootRef.current; + if (!root) return; + const target = inLeft + ? (root.querySelector("[data-other-row][data-ticked]") ?? + root.querySelector("[data-other-row]") ?? + root.querySelector("[data-other-list]")) + : (root.querySelector("[data-pane='ps5'] [data-fs-name] input:checked")?.closest("[data-fs-name]") ?? + root.querySelector("[data-pane='ps5'] [data-fs-name]")); + if (!target) return; + ev.preventDefault(); + target.focus(); + }; + + const actions: { toward: Toward; op: PaneOp }[] = [ + { toward: "other", op: "copy" }, + { toward: "other", op: "move" }, + { toward: "ps5", op: "copy" }, + { toward: "ps5", op: "move" }, + ]; + + return ( +
    + {confirmNode} + {/* The PS5 side keeps the larger share: its rows carry their own action buttons. */} + {/* Narrower than the window, the selection bar's actions wrap onto more lines, each with + its whole label, instead of squeezing over each other. */} +
    + {children} +
    + {!hidden && ( + <> +
    + {actions.map(({ toward, op }) => { + // A ticked folder can make a Move "files only": the reason shows while it is ticked. + const route = place ? paneRoute(place, toward, op, sourceOf(toward).some((i) => i.isDir)) : null; + const count = toward === "other" ? ps.selected.length : pane.selected.size; + const usesDownload = route?.ok && (route.via === "download" || route.via === "download-server"); + const disabled = + !route?.ok || count === 0 || dir === null || starting || (usesDownload && ps.downloadBusy); + const dest = toward === "other" ? placeName : psName; + const label = op === "copy" ? tr("two_panes_copy", undefined, "Copy") : tr("two_panes_move", undefined, "Move"); + const reasonId = `two-panes-why-${toward}-${op}`; + return ( +
    + + {route && !route.ok && ( + // w-0 min-w-full: the note wraps to the buttons' width instead of widening them. +

    + {blockText(tr, route.block)} +

    + )} +
    + ); + })} +
    + + + )} +
    + ); +} + +/** The two panes when `on`; otherwise the PS5 listing alone, exactly as it is without them. */ +export function TwoPanesFrame({ on, ...rest }: { on: boolean } & Parameters[0]) { + return on ? : <>{rest.children}; +} + +function computerLabel(tr: ReturnType): string { + return isTauriEnv() + ? tr("two_panes_this_computer", undefined, "This computer") + : tr("two_panes_app_computer", undefined, "The app's computer"); +} + +type OtherPaneState = ReturnType; + +/** The other side's place, folder, listing and ticks; remembered per device. */ +function useOtherPane(here: string, servers: Connection[]) { + const [place, setPlace] = useState(() => { + const m = readOtherPane(); + return m?.place ?? { kind: "computer" }; + }); + const [dir, setDir] = useState(() => readOtherPane()?.path ?? null); + const [roots, setRoots] = useState([]); + const [entries, setEntries] = useState([]); + const [more, setMore] = useState(null); + const [loading, setLoading] = useState(false); + const [error, setError] = useState(null); + const [selected, setSelected] = useState>(new Set()); + const seq = useRef(0); + + // The console Files is on is never the other side too. + const usable = place && !(place.kind === "console" && hostOf(place.host) === here) ? place : null; + + const load = useCallback( + async (p: Place, path: string, after?: string | null) => { + const mine = ++seq.current; + setLoading(true); + setError(null); + try { + const page = await listPlace(p, path, after); + if (mine !== seq.current) return; + setEntries((prev) => (after ? [...prev, ...page.entries] : page.entries)); + setMore(page.more); + } catch (e) { + if (mine !== seq.current) return; + setEntries([]); + setMore(null); + setError(humanizeCaught(e)); + } finally { + if (mine === seq.current) setLoading(false); + } + }, + [], + ); + + // A new place starts at its usual first folder unless one is remembered for it. + const startOf = useCallback( + async (p: Place): Promise<{ start: string; roots: string[] }> => { + if (p.kind === "console") return { start: CONSOLE_ROOTS[0], roots: CONSOLE_ROOTS }; + if (p.kind === "server") { + const s = servers.find((c) => c.id === p.id)?.start_path || "/"; + return { start: s.startsWith("/") ? s : `/${s}`, roots: [] }; + } + const rs = await localFs.storageRoots().catch(() => [] as string[]); + return { start: rs[0] ?? "/", roots: rs }; + }, + [servers], + ); + + const placeKey = usable ? JSON.stringify(usable) : ""; + useEffect(() => { + if (!usable) return; + let live = true; + void (async () => { + const { start, roots: rs } = await startOf(usable); + if (!live) return; + setRoots(rs); + const remembered = readOtherPane(); + const path = + remembered && JSON.stringify(remembered.place) === placeKey && remembered.path ? remembered.path : start; + setDir(path); + setSelected(new Set()); + void load(usable, path); + })(); + return () => { + live = false; + }; + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [placeKey]); + + const open = (path: string) => { + if (!usable) return; + setDir(path); + setSelected(new Set()); + writeOtherPane({ place: usable, path }); + void load(usable, path); + }; + + return { + place: usable, + dir: usable ? dir : null, + roots, + entries, + more, + loading, + error, + selected, + choose: (p: Place) => { + writeOtherPane({ place: p, path: "" }); + setEntries([]); + setError(null); + setPlace(p); + }, + open, + up: () => { + if (!usable || dir === null) return; + const parent = placeParent(usable, dir); + if (parent) open(parent); + }, + reload: async () => { + if (usable && dir !== null) await load(usable, dir); + }, + loadMore: () => { + if (usable && dir !== null && more) void load(usable, dir, more); + }, + toggle: (name: string) => + setSelected((cur) => { + const next = new Set(cur); + if (next.has(name)) next.delete(name); + else next.add(name); + return next; + }), + setAll: (on: boolean) => setSelected(on ? new Set(entries.map((e) => e.name)) : new Set()), + clearSelection: () => setSelected(new Set()), + }; +} + +const placeValue = (p: Place | null) => + !p ? "" : p.kind === "computer" ? "computer" : p.kind === "server" ? `server:${p.id}` : `console:${p.host}`; + +function OtherPane({ + pane, + servers, + consoles, +}: { + pane: OtherPaneState; + servers: Connection[]; + consoles: { name: string; host: string }[]; +}) { + const tr = useTr(); + const { place, dir, entries, selected } = pane; + const parent = place && dir !== null ? placeParent(place, dir) : null; + const listRef = useRef(null); + const focusRow = (name: string) => + listRef.current?.querySelector(`[data-other-row="${CSS.escape(name)}"]`)?.focus(); + const allTicked = entries.length > 0 && entries.every((e) => selected.has(e.name)); + + return ( +
    +
    + + {pane.roots.length > 1 && ( + + )} +
    +
    + pane.setAll(e.target.checked)} + aria-label={tr("fs_select_all", undefined, "Select all")} + title={tr("fs_select_all", undefined, "Select all")} + /> + + + {dir ?? ""} + + {selected.size > 0 && ( + + {tr("fs_selected_count", { count: selected.size }, "{count} selected")} + + )} + +
    +
    + {pane.loading && entries.length === 0 ? ( +

    + {tr("picker_loading", undefined, "Loading…")} +

    + ) : pane.error ? ( +
    + {pane.error} + +
    + ) : entries.length === 0 ? ( +

    + + {place + ? tr("picker_empty", undefined, "This folder is empty.") + : tr("two_panes_choose_place", undefined, "Choose a place")} +

    + ) : ( +
      { + const row = (ev.target as HTMLElement).closest("[data-other-row]"); + if (!row || ev.altKey || ev.ctrlKey || ev.metaKey) return; + const at = entries.findIndex((x) => x.name === row.dataset.otherRow); + if (ev.key === "ArrowDown" || ev.key === "ArrowUp") { + const next = entries[at + (ev.key === "ArrowDown" ? 1 : -1)]; + if (!next) return; + ev.preventDefault(); + focusRow(next.name); + } else if (ev.key === "Backspace" && parent && ev.target === row) { + ev.preventDefault(); + pane.up(); + } + }} + > + {entries.map((e) => { + const ticked = selected.has(e.name); + return ( +
    • { + if (ev.target !== ev.currentTarget) return; + if (ev.key === "Enter" && e.is_dir) { + ev.preventDefault(); + pane.open(e.path); + } else if (ev.key === " ") { + ev.preventDefault(); + pane.toggle(e.name); + } + }} + onDoubleClick={(ev) => { + if ((ev.target as HTMLElement).closest("input,button")) return; + if (e.is_dir) pane.open(e.path); + }} + className={ + "flex items-center gap-2 rounded-[var(--radius-card)] border px-2.5 py-1 text-sm focus-visible:outline-2 focus-visible:outline-[var(--color-accent)] " + + (ticked + ? "border-[color-mix(in_srgb,var(--color-accent)_40%,transparent)] bg-[var(--color-accent-soft)]" + : "border-[var(--glass-edge)] bg-[var(--color-surface-raised)] hover:bg-[var(--color-float)]") + } + > + pane.toggle(e.name)} + aria-label={e.name} + className="h-3.5 w-3.5 shrink-0" + /> + {e.is_dir ? ( + + ) : ( + + )} + + {!e.is_dir && ( + + {formatBytes(e.size)} + + )} +
    • + ); + })} + {pane.more && ( +
    • + +
    • + )} +
    + )} +
    +
    + ); +} + diff --git a/client/src/screens/FileSystem/fsBrowse.test.ts b/client/src/screens/FileSystem/fsBrowse.test.ts index 8e6f4ccf3..ea0ca1c26 100644 --- a/client/src/screens/FileSystem/fsBrowse.test.ts +++ b/client/src/screens/FileSystem/fsBrowse.test.ts @@ -1,6 +1,22 @@ import { describe, expect, it } from "vitest"; -import { fsKeyAction, nextSort, normalizeTypedPath, sortEntries } from "./fsBrowse"; +import { fsKeyAction, keysBelongElsewhere, nextSort, normalizeTypedPath, sortEntries } from "./fsBrowse"; + +describe("keysBelongElsewhere", () => { + // Just enough of an element: its tag and which of the selectors it sits inside. + const el = (tagName: string, inside: string[] = []) => ({ + tagName, + isContentEditable: false, + closest: (sel: string) => (sel.split(",").some((s) => inside.includes(s)) ? {} : null), + }); + + it("the list keeps a row's keys; a field, a dialog and the two panes' other side keep their own", () => { + expect(keysBelongElsewhere(el("LI") as unknown as EventTarget)).toBe(false); + expect(keysBelongElsewhere(el("INPUT") as unknown as EventTarget)).toBe(true); + expect(keysBelongElsewhere(el("BUTTON", ['[role="dialog"]']) as unknown as EventTarget)).toBe(true); + expect(keysBelongElsewhere(el("LI", ["[data-keys-own]"]) as unknown as EventTarget)).toBe(true); + }); +}); const key = (k: string, mods: Partial<{ ctrl: boolean; meta: boolean; alt: boolean }> = {}) => ({ key: k, diff --git a/client/src/screens/FileSystem/fsBrowse.ts b/client/src/screens/FileSystem/fsBrowse.ts index 8dd5fb974..bc299420f 100644 --- a/client/src/screens/FileSystem/fsBrowse.ts +++ b/client/src/screens/FileSystem/fsBrowse.ts @@ -96,13 +96,14 @@ export function fsKeyAction(e: KeyLike): FsKeyAction | null { } } -/** True when keystrokes belong to a text field or an open dialog, not the file list. */ +/** True when keystrokes belong to a text field, an open dialog, or a part of the page that keeps + * its own keys (`data-keys-own`: the other side of the two panes), not the file list. */ export function keysBelongElsewhere(target: EventTarget | null): boolean { const el = target as HTMLElement | null; if (!el || typeof el.closest !== "function") return false; const tag = el.tagName; if (tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT" || el.isContentEditable) return true; - return !!el.closest('[role="dialog"],[role="menu"]'); + return !!el.closest('[role="dialog"],[role="menu"],[data-keys-own]'); } /** Normalizes a typed path: absolute, single slashes, no trailing slash (except "/"). */ diff --git a/client/src/screens/FileSystem/index.tsx b/client/src/screens/FileSystem/index.tsx index f0195e76e..c33ee85a1 100644 --- a/client/src/screens/FileSystem/index.tsx +++ b/client/src/screens/FileSystem/index.tsx @@ -29,8 +29,7 @@ import { fileSystemTargetFor } from "../Search/searchLink"; import { isMeshInternal, MESH_MARKER } from "../../lib/meshFiles"; import { DiskUsagePanel } from "../DiskUsage"; import { SnapshotsPanel, type SnapshotPrefill } from "../Backup"; -import { useC2cRoutes } from "../../state/c2cRoutes"; -import { useUploadQueueStore } from "../../state/uploadQueue"; +import { queueConsoleSend } from "../../state/consoleSendQueue"; import type { SendItem } from "../../lib/consoleSend"; import { queueLinkFor } from "../../lib/gamePage"; import { @@ -80,7 +79,11 @@ import { Network, ListChecks, Server, + Columns2, } from "lucide-react"; +import { TwoPanesFrame, type PsSide } from "./TwoPanes"; +import { readTwoPanes, TWO_PANES_QUERY, writeTwoPanes, type CopyOutcome } from "./panePlan"; +import { useMediaQuery } from "../../lib/phoneLayout"; import type { Connection } from "../../api/remote"; import { useConnectionsStore } from "../../state/connections"; import { pickLocalPath } from "../../state/localPicker"; @@ -143,7 +146,7 @@ import { type SearchHit, type Volume, } from "../../api/ps5"; -import { baseNameOf, kindsOf, namesPreview, planFsUpload } from "../../state/fsUploadPlan"; +import { baseNameOf, kindsOf, namesPreview, planFsUpload, type FsPickedItem } from "../../state/fsUploadPlan"; import { useConflictAsk } from "./ConflictAsk"; import { loadFsLastPath, @@ -1710,7 +1713,12 @@ export default function FileSystemScreen() { * Two or more local files then go up as ONE job, a folder as its own job, all of it one * run (one task, one progress bar, one Cancel). `kind`: what the picker returned, when it * only returns one kind (a drop is asked about). */ - const addPicked = async (picked: string[], kind?: "file" | "folder") => { + const addPicked = async ( + picked: string[], + kind?: "file" | "folder", + // What each pick is, when the caller has listed it already (the two panes, #952). + known?: FsPickedItem[], + ) => { if (picked.length === 0) return; setError(null); // The console can change while this waits on the listing or on the user: the plan is @@ -1718,7 +1726,7 @@ export default function FileSystemScreen() { const probe = guard.capture(); const addr = consoleAddr(host); const destDir = path; - const items = await kindsOf(picked, pathKind, kind); + const items = known ?? (await kindsOf(picked, pathKind, kind)); let existing: Awaited>; try { existing = await fsListDir(addr, destDir); @@ -1958,6 +1966,10 @@ export default function FileSystemScreen() { const rowsListRef = useRef(null); // The phone layout (#936). const phone = usePhoneLayout(); + // Two panes (#952): a wide window with a mouse only; a phone or a tablet keeps the one list. + const wideEnough = useMediaQuery(TWO_PANES_QUERY); + const [twoPanesWanted, setTwoPanesWanted] = useState(readTwoPanes); + const twoPanes = wideEnough && twoPanesWanted && !phone; const { start: rowsStart, end: rowsEnd, before: rowsBefore, after: rowsAfter, scrollToRow } = useWindowedRows( sortedEntries.length, rowsListRef, @@ -1988,31 +2000,10 @@ export default function FileSystemScreen() { }; const confirmSend = (target: string, _destDir: string, dests: string[]) => { const items = sendItems ?? []; - const route = useC2cRoutes.getState().routeFor(hostOf(host), target); setSendItems(null); if (items.length === 0) return; setSelected(new Set()); - const q = useUploadQueueStore.getState(); - const ids = items.map((it, i) => - q.add({ - sourceKind: "ps5", - fromConsole: hostOf(host), - route: route.mode, - directAddr: route.directAddr || null, - sourcePath: it.path, - displayName: it.name, - resolvedDest: dests[i], - addr: target, - strategy: "overwrite", - reconcileMode: "fast", - excludes: [], - mountAfterUpload: false, - mountReadOnly: true, - registerAfterUpload: false, - estimatedBytes: it.size, - }), - ); - q.startAdded(target, ids); + queueConsoleSend(host, target, items, dests); const name = profileNameForAddr(target, useRosterStore.getState().profiles) || target; pushNotification( "info", @@ -2912,13 +2903,22 @@ export default function FileSystemScreen() { /** Save a file or folder under the current dir to the host. Same * flow as Library's per-row Download — pick a host folder, kick * off `transfer_download`, poll jobStatus to terminal. Single- - * flight at the screen level: only one download at a time. */ - const runDownload = async (entry: DirEntry, asZip = false, server?: Connection) => { + * flight at the screen level: only one download at a time. + * `to`: a folder already picked (on `server`, or on this computer for the two panes), and + * `move` to delete the source once the engine checked the copy on the server (#953); `from` + * is the PS5 folder the entry is in when it is not the one shown (the two panes, #952). + * How it ended: done, failed, or stopped (also a cancelled picker). */ + const runDownload = async ( + entry: DirEntry, + asZip = false, + server?: Connection, + to?: { dir: string; move?: boolean; from?: string }, + ): Promise => { // Single-flight per console: only one download at a time on THIS // console (others download concurrently into their own slots). - if (fsDownload.active) return; + if (fsDownload.active) return "failed"; const addr = consoleAddr(host); - const remote = joinPath(path, entry.name); + const remote = joinPath(to?.from ?? path, entry.name); const kind: "file" | "folder" = entry.kind === "dir" ? "folder" : "file"; // asZip: pick a .zip save path and stream-zip into it (no scratch dir). @@ -2936,14 +2936,16 @@ export default function FileSystemScreen() { 'Save "{name}" as a .zip', ), }); - if (!destZip || typeof destZip !== "string") return; + if (!destZip || typeof destZip !== "string") return "stopped"; dest = destZip; rootName = destZip.split(/[\\/]/).pop() || `${entry.name}.zip`; start = () => startTransferDownloadZip(remote, destZip, addr, kind, systemFileRead); } else { // A saved server (8.0.0): the engine pulls it off the console and writes it there. - const picked = server + const picked = to + ? to.dir + : server ? await pickLocalPath({ mode: "folder", source: { connectionId: server.id }, @@ -2967,11 +2969,11 @@ export default function FileSystemScreen() { 'Pick a destination folder for "{name}"', ), }); - if (typeof picked !== "string") return; + if (typeof picked !== "string") return "stopped"; dest = picked; rootName = entry.name; start = () => - startTransferDownload(remote, picked, addr, kind, systemFileRead); + startTransferDownload(remote, picked, addr, kind, systemFileRead, !!to?.move); } setError(null); let jobId: string; @@ -2994,7 +2996,7 @@ export default function FileSystemScreen() { { body: friendly }, ); fsDownload.end(friendly); - return; + return "failed"; } labelEngineJob(jobId, "download", rootName); const myRunId = fsDownload.begin({ @@ -3027,20 +3029,53 @@ export default function FileSystemScreen() { }; // A failed status read keeps polling (the engine is still downloading); // the banner says contact is lost and its Cancel still stops the job. + let outcome: CopyOutcome = "stopped"; await pollFsDownload( jobId, { isLive, onProgress: (p) => fsDownload.setProgress(p), onLostContact: (e) => fsDownload.setLostContact(e), - onDone: () => fsDownload.end(null), - onFailed: (error) => + onDone: () => { + outcome = "done"; + fsDownload.end(null); + }, + onFailed: (error) => { + outcome = "failed"; fail( tr("fs_download_failed", { error }, "Download failed: {error}"), - ), + ); + }, }, { jobStatus: (id) => jobStatus(id) }, ); + return outcome; + }; + + /** Copy or move `list` into one folder picked on `server` (#953), one item after another: a + * failed, cancelled or refused item stops the rest. A move deletes each source on the PS5 + * only after the engine checked its copy on the server. */ + const runServerTransfer = async (list: DirEntry[], server: Connection, move: boolean) => { + if (list.length === 0 || fsDownload.active) return; + const what = + list.length === 1 + ? list[0].name + : tr("fs_move_n_items", { count: list.length }, `${list.length} items`); + const dir = await pickLocalPath({ + mode: "folder", + source: { connectionId: server.id }, + title: tr( + "fs_download_server_title", + { name: what, server: server.name }, + 'Pick a folder on {server} for "{name}"', + ), + }); + if (typeof dir !== "string") return; + setSelected(new Set()); + for (const entry of list) { + if ((await runDownload(entry, false, server, { dir, move })) !== "done") break; + } + if (move) void refresh(); }; const selectionActive = selected.size > 0; @@ -3515,6 +3550,27 @@ export default function FileSystemScreen() { ], }; + // What the two panes (#952) use of this screen: its ticks, and its own Download and Add files. + const psSide: PsSide = { + host, + path, + selected: selectedEntries + .filter((e) => e.kind === "file" || e.kind === "dir") + .map((e) => ({ + name: e.name, + path: joinPath(path, e.name), + isDir: e.kind === "dir", + size: e.kind === "dir" ? 0 : e.size, + })), + names: (entries ?? []).map((e) => e.name), + downloadBusy: downloadOp.active, + download: (item, into, server) => + runDownload({ name: item.name, kind: item.isDir ? "dir" : "file", size: item.size }, false, server, into), + upload: (paths, known) => addPicked(paths, undefined, known), + clearSelection: () => setSelected(new Set()), + refresh: () => void refresh(), + }; + return (
    {properties && ( @@ -3554,6 +3610,19 @@ export default function FileSystemScreen() { startPath={parent(moveItems[0]?.path ?? path)} onCancel={() => setMoveItems(null)} onConfirm={confirmMove} + servers={savedServers} + onServer={(id, move) => { + const server = savedServers.find((c) => c.id === id); + const names = new Set(moveItems.map((i) => i.name)); + setMoveItems(null); + if (server) { + void runServerTransfer( + (entries ?? []).filter((e) => names.has(e.name)), + server, + move, + ); + } + }} /> )} {rowMenu && menuEntry && ( @@ -3947,6 +4016,26 @@ export default function FileSystemScreen() { > {tr("fs_refresh", "Refresh")} + {wideEnough && ( + + )}
    ); diff --git a/client/src/screens/FileSystem/panePlan.test.ts b/client/src/screens/FileSystem/panePlan.test.ts new file mode 100644 index 000000000..122354222 --- /dev/null +++ b/client/src/screens/FileSystem/panePlan.test.ts @@ -0,0 +1,190 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +import { installWindowStub } from "../../test-utils/storage"; +import { + copyLooksWhole, + namesAlreadyThere, + paneRoute, + readOtherPane, + readTwoPanes, + runPaneTransfer, + TWO_PANES_KEY, + writeOtherPane, + writeTwoPanes, + type CopyOutcome, +} from "./panePlan"; +import type { Place } from "../../lib/placeList"; + +const computer: Place = { kind: "computer" }; +const server: Place = { kind: "server", id: "nas" }; +const otherConsole: Place = { kind: "console", host: "192.168.0.6" }; + +describe("which transfer each pair of places uses (#952)", () => { + it("PS5 → this computer is Download, PS5 → a saved server is Download to the server", () => { + expect(paneRoute(computer, "other", "copy")).toEqual({ ok: true, via: "download" }); + expect(paneRoute(server, "other", "copy")).toEqual({ ok: true, via: "download-server" }); + }); + + it("this computer or a saved server → PS5 is Add files", () => { + expect(paneRoute(computer, "ps5", "copy")).toEqual({ ok: true, via: "upload" }); + expect(paneRoute(server, "ps5", "copy")).toEqual({ ok: true, via: "upload" }); + }); + + it("console ↔ console is the send to another console, both ways, copy and move", () => { + for (const toward of ["other", "ps5"] as const) + for (const op of ["copy", "move"] as const) + expect(paneRoute(otherConsole, toward, op)).toEqual({ ok: true, via: "console-send" }); + }); + + it("files move off the PS5 to this computer and to a saved server", () => { + expect(paneRoute(computer, "other", "move")).toEqual({ ok: true, via: "download" }); + // To a saved server the engine checks the copy and deletes the source itself (#953). + expect(paneRoute(server, "other", "move")).toEqual({ ok: true, via: "download-server", engineMoves: true }); + expect(paneRoute(server, "other", "copy")).toEqual({ ok: true, via: "download-server" }); + }); + + it("a folder moves only where every file of its copy is checked: to a saved server", () => { + expect(paneRoute(server, "other", "move", true)).toEqual({ ok: true, via: "download-server", engineMoves: true }); + expect(paneRoute(computer, "other", "move", true)).toEqual({ ok: false, block: "files-only" }); + expect(paneRoute(otherConsole, "other", "move", true)).toEqual({ ok: false, block: "files-only" }); + expect(paneRoute(otherConsole, "ps5", "move", true)).toEqual({ ok: false, block: "files-only" }); + // Copying a folder is fine everywhere. + expect(paneRoute(computer, "other", "copy", true)).toEqual({ ok: true, via: "download" }); + expect(paneRoute(otherConsole, "ps5", "copy", true)).toEqual({ ok: true, via: "console-send" }); + }); + + it("no move from this computer or a saved server: nothing in the app deletes files there", () => { + expect(paneRoute(computer, "ps5", "move")).toEqual({ ok: false, block: "no-delete-computer" }); + expect(paneRoute(server, "ps5", "move")).toEqual({ ok: false, block: "no-delete-server" }); + expect(paneRoute(computer, "ps5", "move", true)).toEqual({ ok: false, block: "no-delete-computer" }); + }); +}); + +type Item = { name: string }; +const a: Item = { name: "a" }; +const b: Item = { name: "b" }; +const c: Item = { name: "c" }; + +function recorder(outcomes: Record, whole: Record = {}) { + const log: string[] = []; + return { + log, + deps: { + copy: vi.fn(async (i: Item) => { + log.push(`copy ${i.name}`); + return outcomes[i.name] ?? "done"; + }), + verify: vi.fn(async (i: Item) => { + log.push(`verify ${i.name}`); + return whole[i.name] ?? true; + }), + removeSource: vi.fn(async (i: Item) => { + log.push(`delete ${i.name}`); + }), + }, + }; +} + +describe("runPaneTransfer: a move is copy, check, then delete", () => { + it("a copy never checks or deletes anything", async () => { + const r = recorder({}); + const out = await runPaneTransfer([a, b], "copy", r.deps); + expect(r.log).toEqual(["copy a", "copy b"]); + expect(out.finished).toEqual([a, b]); + expect(r.deps.removeSource).not.toHaveBeenCalled(); + }); + + it("a move deletes each source only after its own copy finished and was checked", async () => { + const r = recorder({}); + const out = await runPaneTransfer([a, b], "move", r.deps); + expect(r.log).toEqual(["copy a", "verify a", "delete a", "copy b", "verify b", "delete b"]); + expect(out.finished).toEqual([a, b]); + }); + + it("a failed copy keeps its source, and the next item still runs", async () => { + const r = recorder({ a: "failed" }); + const out = await runPaneTransfer([a, b], "move", r.deps); + expect(r.log).toEqual(["copy a", "copy b", "verify b", "delete b"]); + expect(out.failed).toEqual([a]); + expect(out.finished).toEqual([b]); + }); + + it("a copy that throws counts as failed and keeps its source", async () => { + const r = recorder({}); + r.deps.copy.mockRejectedValueOnce(new Error("engine gone")); + const out = await runPaneTransfer([a], "move", r.deps); + expect(out.failed).toEqual([a]); + expect(r.deps.removeSource).not.toHaveBeenCalled(); + }); + + it("a copy that can't be found whole keeps its source", async () => { + const r = recorder({}, { a: false }); + const out = await runPaneTransfer([a], "move", r.deps); + expect(out.unverified).toEqual([a]); + expect(r.deps.removeSource).not.toHaveBeenCalled(); + }); + + it("a check that throws keeps the source", async () => { + const r = recorder({}); + r.deps.verify.mockRejectedValueOnce(new Error("listing failed")); + const out = await runPaneTransfer([a], "move", r.deps); + expect(out.unverified).toEqual([a]); + expect(r.deps.removeSource).not.toHaveBeenCalled(); + }); + + it("a stop ends the run: the stopped item and the ones after it are left alone", async () => { + const r = recorder({ b: "stopped" }); + const out = await runPaneTransfer([a, b, c], "move", r.deps); + expect(r.log).toEqual(["copy a", "verify a", "delete a", "copy b"]); + expect(out.stopped).toBe(true); + expect(out.finished).toEqual([a]); + }); + + it("a source that won't delete is reported, the copy stays", async () => { + const r = recorder({}); + r.deps.removeSource.mockRejectedValueOnce(new Error("busy")); + const out = await runPaneTransfer([a, b], "move", r.deps); + expect(out.notRemoved).toEqual([a]); + expect(out.finished).toEqual([b]); + }); +}); + +describe("checking a copy", () => { + it("a file needs its name and its size", () => { + expect(copyLooksWhole({ isDir: false, size: 10 }, { is_dir: false, size: 10 })).toBe(true); + expect(copyLooksWhole({ isDir: false, size: 10 }, { is_dir: false, size: 9 })).toBe(false); + expect(copyLooksWhole({ isDir: false, size: 10 }, null)).toBe(false); + }); + + it("a folder needs to be there as a folder", () => { + expect(copyLooksWhole({ isDir: true, size: 0 }, { is_dir: true, size: 4096 })).toBe(true); + expect(copyLooksWhole({ isDir: true, size: 0 }, { is_dir: false, size: 0 })).toBe(false); + }); + + it("names already in the destination are found", () => { + expect(namesAlreadyThere(["a", "b", "c"], ["c", "x", "a"])).toEqual(["a", "c"]); + }); +}); + +describe("remembered per device", () => { + beforeEach(() => installWindowStub()); + afterEach(() => vi.unstubAllGlobals()); + + it("the toggle is off until turned on, and stays as set", () => { + expect(readTwoPanes()).toBe(false); + writeTwoPanes(true); + expect(window.localStorage.getItem(TWO_PANES_KEY)).toBe("1"); + expect(readTwoPanes()).toBe(true); + writeTwoPanes(false); + expect(readTwoPanes()).toBe(false); + }); + + it("the other side's place and folder come back; a broken memory is no memory", () => { + writeOtherPane({ place: server, path: "/games" }); + expect(readOtherPane()).toEqual({ place: server, path: "/games" }); + window.localStorage.setItem("ps5upload.files.otherPane", "{nope"); + expect(readOtherPane()).toBeNull(); + window.localStorage.setItem("ps5upload.files.otherPane", JSON.stringify({ place: { kind: "server" }, path: "/" })); + expect(readOtherPane()).toBeNull(); + }); +}); diff --git a/client/src/screens/FileSystem/panePlan.ts b/client/src/screens/FileSystem/panePlan.ts new file mode 100644 index 000000000..d03071342 --- /dev/null +++ b/client/src/screens/FileSystem/panePlan.ts @@ -0,0 +1,199 @@ +// Files' two panes (#952): the PS5 on one side, another place on the other, and Copy / Move +// between them. Every transfer here is one the app already had (upload, download, download to a +// saved server, send to another console); this file only says which one a pair of places uses, +// and runs a move as copy, check, then delete. Pure, so it is tested without a screen. + +import type { Place } from "../../lib/placeList"; + +/** Whether the two panes are on, per device. */ +export const TWO_PANES_KEY = "ps5upload.files.twoPanes"; +/** The other pane's place and folder, per device. */ +export const OTHER_PANE_KEY = "ps5upload.files.otherPane"; + +/** Wide enough for two lists side by side, with a mouse: the desktop app and the web UI on a + * computer. Phones and tablets keep the one list. */ +export const TWO_PANES_QUERY = "(min-width: 1100px) and (pointer: fine)"; + +export function readTwoPanes(): boolean { + try { + return window.localStorage.getItem(TWO_PANES_KEY) === "1"; + } catch { + return false; + } +} + +export function writeTwoPanes(on: boolean): void { + try { + if (on) window.localStorage.setItem(TWO_PANES_KEY, "1"); + else window.localStorage.removeItem(TWO_PANES_KEY); + } catch { + /* remembered as a convenience */ + } +} + +export interface OtherPaneMemory { + place: Place; + path: string; +} + +export function readOtherPane(): OtherPaneMemory | null { + try { + const raw = window.localStorage.getItem(OTHER_PANE_KEY); + if (!raw) return null; + const v = JSON.parse(raw) as OtherPaneMemory; + const k = v?.place?.kind; + if (typeof v.path !== "string") return null; + if (k === "computer") return { place: { kind: "computer" }, path: v.path }; + if (k === "server" && typeof (v.place as { id?: unknown }).id === "string") return v; + if (k === "console" && typeof (v.place as { host?: unknown }).host === "string") return v; + return null; + } catch { + return null; + } +} + +export function writeOtherPane(m: OtherPaneMemory): void { + try { + window.localStorage.setItem(OTHER_PANE_KEY, JSON.stringify(m)); + } catch { + /* remembered as a convenience */ + } +} + +/** Which way a transfer goes: from the PS5 to the other pane, or into the PS5. */ +export type Toward = "other" | "ps5"; +export type PaneOp = "copy" | "move"; + +/** The existing operation a pair of places maps to. */ +export type PaneVia = + /** PS5 → this computer: Files' Download. */ + | "download" + /** PS5 → a saved server: Files' "Download to {server}". */ + | "download-server" + /** This computer or a saved server → PS5: Files' Add files. */ + | "upload" + /** Console ↔ console: "Send to another console", queued. */ + | "console-send"; + +/** Why an action is not offered for a pair of places. */ +export type PaneBlock = + /** Nothing in the app deletes files on this computer, so it can't move from it. */ + | "no-delete-computer" + /** Nothing in the app deletes files on a saved server, so it can't move from one. */ + | "no-delete-server" + /** A folder's copy here can't be checked file by file before its original goes: files only. */ + | "files-only"; + +export type PaneRoute = + /** `engineMoves`: the engine itself checks the copy and deletes the source (a move to a + * saved server, #953); otherwise a move is copy, check here, then delete. */ + | { ok: true; via: PaneVia; engineMoves?: boolean } + | { ok: false; block: PaneBlock }; + +/** The operation `op` toward `toward` uses with the other pane on `place`, or why there is none. + * `folders`: the items to send include a folder. + * + * A move deletes the source only after its copy was checked whole. Never from this computer or + * a saved server: the app deletes files on neither. To a saved server the engine checks every + * file and folder and deletes the source itself. To this computer and between consoles the app + * checks a file by its size, but has no cheap way to check every file of a folder, so a folder + * there is copied, not moved. */ +export function paneRoute(place: Place, toward: Toward, op: PaneOp, folders = false): PaneRoute { + if (op === "move" && toward === "ps5" && place.kind !== "console") + return { ok: false, block: place.kind === "server" ? "no-delete-server" : "no-delete-computer" }; + if (op === "move" && folders && place.kind !== "server") return { ok: false, block: "files-only" }; + if (place.kind === "console") return { ok: true, via: "console-send" }; + if (toward === "ps5") return { ok: true, via: "upload" }; + if (place.kind === "server") + return op === "move" ? { ok: true, via: "download-server", engineMoves: true } : { ok: true, via: "download-server" }; + return { ok: true, via: "download" }; +} + +/** How one copy ended: landed, failed, or stopped by the user (nothing after it runs). */ +export type CopyOutcome = "done" | "failed" | "stopped"; + +export interface PaneTransferDeps { + /** Copies one item to the other side. Resolves when that copy has ended. */ + copy: (item: T) => Promise; + /** After a copy reported done: the copy is there, and whole (a file has its size). */ + verify: (item: T) => Promise; + /** Deletes the item where it came from. Only ever after `verify` said yes. */ + removeSource: (item: T) => Promise; +} + +export interface PaneTransferResult { + /** Copied, and for a move also deleted where it came from. */ + finished: T[]; + failed: T[]; + /** A move whose copy could not be checked: the source is kept. */ + unverified: T[]; + /** A move whose copy is there but whose source could not be deleted. */ + notRemoved: T[]; + /** The user stopped a copy: it and the items after it were left alone. */ + stopped: boolean; +} + +/** + * Copies each item in turn; a move then checks the copy and deletes the source, item by item. + * The source is never touched before its own copy has finished and been checked: a failed or + * stopped copy, or a copy that can't be found whole, keeps it. A stop ends the run. + */ +export async function runPaneTransfer( + items: T[], + op: PaneOp, + deps: PaneTransferDeps, +): Promise> { + const out: PaneTransferResult = { finished: [], failed: [], unverified: [], notRemoved: [], stopped: false }; + for (const item of items) { + let outcome: CopyOutcome; + try { + outcome = await deps.copy(item); + } catch { + outcome = "failed"; + } + if (outcome === "stopped") { + out.stopped = true; + break; + } + if (outcome === "failed") { + out.failed.push(item); + continue; + } + if (op === "copy") { + out.finished.push(item); + continue; + } + let whole: boolean; + try { + whole = await deps.verify(item); + } catch { + whole = false; + } + if (!whole) { + out.unverified.push(item); + continue; + } + try { + await deps.removeSource(item); + out.finished.push(item); + } catch { + out.notRemoved.push(item); + } + } + return out; +} + +/** A copy found where it should be: a folder by its name, a file by its name and size. */ +export function copyLooksWhole( + source: { isDir: boolean; size: number }, + found: { is_dir: boolean; size: number } | null, +): boolean { + if (!found || found.is_dir !== source.isDir) return false; + return source.isDir || found.size === source.size; +} + +/** The names among `names` already in the destination folder: a copy there replaces them. */ +export function namesAlreadyThere(names: string[], destNames: Iterable): string[] { + const there = new Set(destNames); + return names.filter((n) => there.has(n)); +} diff --git a/client/src/screens/FpkgConvert/QueueCard.tsx b/client/src/screens/FpkgConvert/QueueCard.tsx index f5a289cfc..f37e09b1a 100644 --- a/client/src/screens/FpkgConvert/QueueCard.tsx +++ b/client/src/screens/FpkgConvert/QueueCard.tsx @@ -23,6 +23,8 @@ import { QueueItemOptions } from "./QueueItemOptions"; export interface QueueCardProps { items: ConvertItem[]; running: boolean; + /** The queue was making a game when its page was closed or reloaded: it waits for Start. */ + stoppedByClose?: boolean; /** The game being made is paused (#631): the rest wait for it. */ paused?: boolean; /** Open Upload & Install, where a made game installs or uploads. */ @@ -164,6 +166,24 @@ export function QueueCard(p: QueueCardProps) { )} + {p.running ? ( +
    + {tr( + "cq_page_close_note", + undefined, + "Closing this page does not stop the game being made. The next game starts only while this page is open.", + )} +
    + ) : p.stoppedByClose && pending > 0 ? ( +
    + {tr( + "cq_stopped_by_close", + undefined, + "The queue stopped when this page was closed. The game it was making went on. Start the queue again to continue.", + )} +
    + ) : null} + {sent && (
    - )}
    {catalogText(tr, info).role} diff --git a/client/src/screens/Payloads/PayloadSources.test.tsx b/client/src/screens/Payloads/PayloadSources.test.tsx new file mode 100644 index 000000000..1889ca37b --- /dev/null +++ b/client/src/screens/Payloads/PayloadSources.test.tsx @@ -0,0 +1,226 @@ +import { renderToStaticMarkup } from "react-dom/server"; +import { describe, expect, it } from "vitest"; + +import type { PayloadSource, SourcePreview } from "../../api/payloadSources"; +import { + AddSourceView, + patternText, + SourceCardView, + sourceProblemText, + type AddSourceProps, + type SourceCardProps, +} from "./PayloadSources"; + +// No DOM here (vitest runs in node): static markup, asserting on what is shown. +const tr = ((_k: string, vars: Record | undefined, fallback: string) => + fallback.replace(/\{(\w+)\}/g, (_, n) => String(vars?.[n] ?? ""))) as never; +const noop = () => undefined; +const SHA = "ab".repeat(32); + +const source = (over: Partial = {}): PayloadSource => ({ + id: "custom-0a1b2c3d4e5f", + name: "kstuff", + kind: "github", + project_url: "https://github.com/me/kstuff", + owner: "me", + repo: "kstuff", + file_name: "kstuff-v1.6.0.elf", + file_pattern: "kstuff-v*.elf", + update_available: false, + ...over, +}); + +const have = { + tag: "v1.6.0", + file_name: "kstuff-v1.6.0.elf", + size: 2048, + sha256: SHA, + published_at: "", + downloaded_at: 0, + checksum: "matched", + path: "/data/payloads/custom-0a1b2c3d4e5f/kstuff-v1.6.0.elf", +}; + +const latest = (tag: string) => ({ + tag, + release_name: tag, + file_name: `kstuff-${tag}.elf`, + size: 4096, + published_at: "", + prerelease: false, + html_url: "", +}); + +const card = (over: Partial = {}) => + renderToStaticMarkup( + , + ); + +const buttons = (html: string) => [...html.matchAll(/]*>(?:<[^>]+>)*([^<]*)/g)].map((m) => m[1].trim()).filter(Boolean); + +describe("a payload source's card", () => { + it("before a download: the file, its rule, the newest release and Download", () => { + const out = card({ source: source({ latest: latest("v1.6.0") }) }); + expect(out).toContain("kstuff-v1.6.0.elf"); + expect(out).toContain("Newer releases: a file named like kstuff-v*.elf (* is the version)."); + expect(out).toContain("Not downloaded yet. Newest: v1.6.0"); + expect(buttons(out)).toEqual(["me/kstuff", "Download", "Change file", "Remove source"]); + expect(out).not.toContain("SHA-256"); + }); + + it("downloaded: shows exactly what goes to the console, and Send", () => { + const out = card({ source: source({ have, latest: latest("v1.6.0") }) }); + expect(out).toContain('data-testid="psrc-sha256"'); + expect(out).toContain(SHA); + expect(out).toContain("2.00 KiB"); + expect(out).toContain("v1.6.0"); + expect(out).toContain("Matches the checksum its release lists."); + expect(buttons(out)).toEqual(["me/kstuff", "Send to PS5", "Change file", "Remove source"]); + }); + + it("a newer release: New version available and Update", () => { + const out = card({ source: source({ have, latest: latest("v1.7.0"), update_available: true }) }); + expect(out).toContain("New version available: v1.7.0"); + expect(buttons(out)).toEqual(["me/kstuff", "Update", "Send to PS5", "Change file", "Remove source"]); + }); + + it("an entry from before 12.6.0 asks for its file and keeps its copy", () => { + const out = card({ source: source({ file_name: "", file_pattern: "", have: { ...have, tag: "", checksum: "" } }) }); + expect(out).toContain("Added before this version: pick the file this source downloads."); + expect(out).toContain("unknown"); + expect(buttons(out)).toEqual(["me/kstuff", "Send to PS5", "Pick the file", "Remove source"]); + }); + + it("says why a check failed, in words", () => { + const out = card({ + source: source({ error: { code: "no_matching_file", message: "x" } }), + }); + expect(out).toContain("None of the newest releases has a file named like kstuff-v*.elf."); + expect(buttons(out)).toEqual(["me/kstuff", "Change file", "Remove source"]); + }); + + it("busy: every button waits", () => { + const out = card({ source: source({ have, latest: latest("v1.7.0"), update_available: true }), busy: "download" }); + const disabled = [...out.matchAll(/]*disabled=""/g)].length; + expect(disabled).toBe(4); + }); +}); + +describe("source errors", () => { + const at = (s: number) => `T${s}`; + it("a rate limit says when to try again", () => { + expect(sourceProblemText(tr, { code: "rate_limited", message: "", retry_at: 99 }, "", at)).toBe( + "Too many checks for now. Try again after T99.", + ); + expect(sourceProblemText(tr, { code: "rate_limited", message: "" }, "", at)).toBe( + "Too many checks for now. Try again in a few minutes.", + ); + }); + + it("address refusals are plain", () => { + expect(sourceProblemText(tr, { code: "url_not_https", message: "" })).toBe("Only https:// addresses can be added."); + expect(sourceProblemText(tr, { code: "url_host_not_allowed", message: "" })).toContain("this computer"); + expect(sourceProblemText(tr, { code: "something_new", message: "The engine's words." })).toBe("The engine's words."); + }); + + it("the file rule in words", () => { + expect(patternText(tr, "kstuff.elf", "kstuff.elf")).toBe("Newer releases: a file with this exact name."); + expect(patternText(tr, "k-1.0.elf", "k-*.elf")).toContain("k-*.elf"); + }); +}); + +const preview: SourcePreview = { + id: "custom-0a1b2c3d4e5f", + name: "kstuff", + kind: "github", + project_url: "https://github.com/me/kstuff", + already_added: false, + current_file: "", + releases: [ + { + tag: "v1.6.0", + name: "v1.6.0", + published_at: "", + prerelease: false, + html_url: "", + files: [ + { name: "kstuff-v1.6.0.elf", size: 2048, pattern: "kstuff-v*.elf" }, + { name: "kstuff-v1.6.0-debug.elf", size: 4096, pattern: "kstuff-v*-debug.elf" }, + ], + }, + ], +}; + +const addForm = (over: Partial = {}) => + renderToStaticMarkup( + , + ); + +describe("adding a source", () => { + it("starts with the address", () => { + const out = addForm(); + expect(out).toContain("Add a payload source"); + expect(out).toContain('type="url"'); + expect(out).toContain("Show its files"); + expect(out).not.toContain("Only add projects you trust"); + }); + + it("then lists the newest release's files, with the trust note, and waits for a pick", () => { + const out = addForm({ preview }); + expect(out).toContain("Pick the payload file (release v1.6.0):"); + expect([...out.matchAll(/type="radio"/g)]).toHaveLength(2); + expect(out).toContain( + "PS5Upload will download and send whatever this project publishes under that name. Only add projects you trust.", + ); + expect(out).toMatch(/]*disabled=""[^>]*>(?:<[^>]+>)*Add source/); + }); + + it("a picked file shows its rule and can be added", () => { + const out = addForm({ preview, picked: "kstuff-v1.6.0.elf" }); + expect(out).toContain("Newer releases: a file named like kstuff-v*.elf"); + expect(out).not.toMatch(/]*disabled=""[^>]*>(?:<[^>]+>)*Add source/); + }); + + it("a project without payload files says so", () => { + const out = addForm({ preview: { ...preview, releases: [] } }); + expect(out).toContain("The newest releases of this project have no .elf or .bin file."); + expect(out).not.toContain("Add source"); + }); + + it("changing the file: no address, no note, Use this file", () => { + const out = addForm({ changing: { name: "kstuff" }, preview, picked: "kstuff-v1.6.0.elf" }); + expect(out).toContain("Pick the file for kstuff"); + expect(out).not.toContain('type="url"'); + expect(out).not.toContain("Only add projects you trust"); + expect(out).toContain("Use this file"); + }); + + it("shows a refusal", () => { + expect(addForm({ error: "Only https:// addresses can be added." })).toContain('role="alert"'); + }); +}); diff --git a/client/src/screens/Payloads/PayloadSources.tsx b/client/src/screens/Payloads/PayloadSources.tsx new file mode 100644 index 000000000..1585ec59c --- /dev/null +++ b/client/src/screens/Payloads/PayloadSources.tsx @@ -0,0 +1,643 @@ +import { useCallback, useEffect, useState } from "react"; +import { AlertTriangle, CheckCircle2, Download, ExternalLink, FileCog, Plus, RefreshCw, Send, Trash2 } from "lucide-react"; + +import { + addPayloadSource, + downloadPayloadSource, + listPayloadSources, + PayloadSourceError, + previewPayloadSource, + removePayloadSource, + setPayloadSourceFile, + type PayloadSource, + type SourcePreview, + type SourceProblem, +} from "../../api/payloadSources"; +import { sendPayloadChecked } from "../../api/ps5"; +import { Badge, Button, Input } from "../../components"; +import { useConfirm } from "../../components/ConfirmDialog"; +import { formatBytes } from "../../lib/format"; +import { openExternalUrl } from "../../lib/openExternalUrl"; +import { payloadSendRefusalText } from "../../lib/payloadSendRefusal"; +import { useConnectionStore } from "../../state/connection"; +import { pushNotification } from "../../state/notifications"; +import { withConsolePrefix } from "../../state/roster"; +import { useTr } from "../../state/lang"; + +type Tr = ReturnType; + +/** + * Payload sources the user adds: a GitHub, Gitea or Forgejo project that publishes payload files. + * The user picks the file once; the app reads the project's releases when Payloads opens or on + * Check (the engine keeps what it read for ten minutes), downloads only on Download or Update, and + * sends only on Send, after a confirm that shows exactly which file goes. Nothing runs in the + * background. The built-in catalogue below stays a list of links. + */ + +/** The text for a source call's failure, in the user's language. `pattern`: the source's file + * pattern, for "no matching file". `timeOf` formats a retry time (seconds since the epoch). */ +export function sourceProblemText( + tr: Tr, + p: SourceProblem, + pattern = "", + timeOf: (secs: number) => string = (s) => new Date(s * 1000).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }), +): string { + switch (p.code) { + case "url_not_https": + return tr("psrc_err_not_https", undefined, "Only https:// addresses can be added."); + case "url_has_credentials": + return tr("psrc_err_credentials", undefined, "Remove the user name or password from the address."); + case "url_not_a_project": + return tr( + "psrc_err_not_project", + undefined, + "That isn't a project address. Paste the project's page, like https://github.com/owner/project.", + ); + case "url_gitlab": + return tr("psrc_err_gitlab", undefined, "GitLab projects aren't supported. Use a GitHub, Gitea or Forgejo project."); + case "url_host_not_allowed": + return tr( + "psrc_err_host", + undefined, + "That address is this computer or a link-local address. Use the server's address on your network.", + ); + case "rate_limited": + return p.retry_at + ? tr("psrc_err_rate_at", { time: timeOf(p.retry_at) }, `Too many checks for now. Try again after ${timeOf(p.retry_at)}.`) + : tr("psrc_err_rate", undefined, "Too many checks for now. Try again in a few minutes."); + case "project_not_found": + return tr("psrc_err_not_found", undefined, "The project wasn't found, or it isn't public."); + case "no_matching_file": + return tr( + "psrc_err_no_file", + { pattern }, + `None of the newest releases has a file named like ${pattern}. Change the file if the project renamed it.`, + ); + case "unreachable": + return tr("psrc_err_unreachable", undefined, "Couldn't reach the project's site. Check the network and try again."); + case "checksum_mismatch": + return tr("psrc_err_checksum", undefined, "The download didn't match its release's checksum, so it was not kept."); + case "checksum_unreadable": + return tr("psrc_err_checksum_read", undefined, "The release's checksum file couldn't be read, so nothing was downloaded."); + case "download_cut_short": + return tr("psrc_err_cut_short", undefined, "The download stopped before the end. Try again."); + case "asset_not_payload": + return tr("psrc_err_not_payload", undefined, "The release's file isn't a payload, so it was not kept."); + case "redirect_refused": + return tr("psrc_err_redirect", undefined, "The project's site sent the download to an address that isn't allowed."); + case "custom_repos_unreadable": + return tr( + "payloads_err_custom_repos_unreadable", + { detail: p.message }, + `Your list of added repos can't be read, so it was left as it is. Fix or delete this file: ${p.message}`, + ); + default: + return p.message; + } +} + +function problemOf(e: unknown): SourceProblem { + if (e instanceof PayloadSourceError) return e.problem; + return { code: "", message: e instanceof Error ? e.message : String(e) }; +} + +/** What newer releases may be called, in words. */ +export function patternText(tr: Tr, fileName: string, pattern: string): string { + return pattern && pattern !== fileName + ? tr("psrc_pattern_version", { pattern }, `Newer releases: a file named like ${pattern} (* is the version).`) + : tr("psrc_pattern_exact", undefined, "Newer releases: a file with this exact name."); +} + +// ── A source's card ────────────────────────────────────────────────────────────────────────────── + +export interface SourceCardProps { + tr: Tr; + source: PayloadSource; + busy: "download" | "send" | "remove" | null; + /** A failure of the last action on this card (download, send). */ + actionError: string | null; + onDownload: () => void; + onSend: () => void; + onChangeFile: () => void; + onRemove: () => void; + onOpenProject: () => void; +} + +export function SourceCardView({ + tr, + source: s, + busy, + actionError, + onDownload, + onSend, + onChangeFile, + onRemove, + onOpenProject, +}: SourceCardProps) { + const needsFile = !s.file_name; + const have = s.have; + const checkError = s.error && !needsFile ? sourceProblemText(tr, s.error, s.file_pattern) : null; + const canDownload = !needsFile && !!s.latest && (!have || s.update_available); + return ( +
    +
    +

    {s.name}

    + + {s.update_available && s.latest && ( + + {tr("psrc_new_version", { version: s.latest.tag }, `New version available: ${s.latest.tag}`)} + + )} +
    + + {needsFile ? ( +

    + + + {tr( + "psrc_needs_file", + undefined, + "Added before this version: pick the file this source downloads.", + )} + +

    + ) : ( +
    +
    + {tr("psrc_file", undefined, "File")}: + {s.file_name} +
    +
    {patternText(tr, s.file_name, s.file_pattern)}
    +
    + )} + + {have ? ( +
    +
    {tr("psrc_have_file", undefined, "Downloaded")}
    +
    {have.file_name}
    +
    {tr("psrc_release", undefined, "Release")}
    +
    {have.tag || tr("psrc_release_unknown", undefined, "unknown")}
    +
    {tr("psrc_size", undefined, "Size")}
    +
    {formatBytes(have.size)}
    +
    {"SHA-256"}
    +
    {have.sha256}
    +
    + ) : ( + !needsFile && ( +

    + {s.latest + ? tr( + "psrc_not_downloaded_latest", + { version: s.latest.tag, size: formatBytes(s.latest.size) }, + `Not downloaded yet. Newest: ${s.latest.tag} (${formatBytes(s.latest.size)}).`, + ) + : tr("psrc_not_downloaded", undefined, "Not downloaded yet.")} +

    + ) + )} + {have?.checksum === "matched" && ( +

    + + {tr("psrc_checksum_matched", undefined, "Matches the checksum its release lists.")} +

    + )} + + {(checkError || actionError) && ( +

    + + {actionError ?? checkError} +

    + )} + +
    + {canDownload && ( + + )} + {have && ( + + )} + + +
    +
    + ); +} + +// ── Adding a source, or picking its file ──────────────────────────────────────────────────────── + +export interface AddSourceProps { + tr: Tr; + /** Changing the file of a source added already: its address is fixed. */ + changing: { name: string } | null; + url: string; + preview: SourcePreview | null; + picked: string; + busy: boolean; + error: string | null; + onUrl: (url: string) => void; + onLookUp: () => void; + onPick: (name: string) => void; + onAdd: () => void; + onCancel: () => void; +} + +export function AddSourceView({ tr, changing, url, preview, picked, busy, error, onUrl, onLookUp, onPick, onAdd, onCancel }: AddSourceProps) { + const release = preview?.releases[0]; + const file = release?.files.find((f) => f.name === picked); + return ( +
    +

    + {changing + ? tr("psrc_change_title", { name: changing.name }, `Pick the file for ${changing.name}`) + : tr("psrc_add_title", undefined, "Add a payload source")} +

    + {!changing && ( +
    { + e.preventDefault(); + if (!busy && url.trim()) onLookUp(); + }} + > + + +
    + )} + + {preview && ( +
    +

    + {preview.project_url} +

    + {!release ? ( +

    + {tr("psrc_no_files", undefined, "The newest releases of this project have no .elf or .bin file.")} +

    + ) : ( +
    + + {tr("psrc_pick_legend", { release: release.tag }, `Pick the payload file (release ${release.tag}):`)} + +
      + {release.files.map((f) => ( +
    • + +
    • + ))} +
    + {file &&

    {patternText(tr, file.name, file.pattern)}

    } +
    + )} + {!changing && ( +

    + + + {tr( + "psrc_trust_note", + undefined, + "PS5Upload will download and send whatever this project publishes under that name. Only add projects you trust.", + )} + +

    + )} +
    + )} + + {error && ( +

    + {error} +

    + )} + +
    + {preview && release && ( + + )} + +
    +
    + ); +} + +// ── The section ────────────────────────────────────────────────────────────────────────────────── + +type Busy = { id: string; what: "download" | "send" | "remove" } | null; + +interface AddState { + changing: PayloadSource | null; + url: string; + preview: SourcePreview | null; + picked: string; + busy: boolean; + error: string | null; +} + +export default function PayloadSourcesSection() { + const tr = useTr(); + const host = useConnectionStore((s) => s.host); + const [sources, setSources] = useState(null); + const [listError, setListError] = useState(null); + const [checking, setChecking] = useState(false); + const [busy, setBusy] = useState(null); + const [cardErrors, setCardErrors] = useState>({}); + const [add, setAdd] = useState(null); + const { confirm, dialog } = useConfirm(); + + const load = useCallback( + async (check: boolean, force: boolean) => { + setChecking(check); + try { + setSources(await listPayloadSources(check, force)); + setListError(null); + } catch (e) { + setListError(sourceProblemText(tr, problemOf(e))); + setSources((prev) => prev ?? []); + } finally { + setChecking(false); + } + }, + [tr], + ); + + // Opening Payloads is a check (the engine answers from what it read in the last ten minutes). + useEffect(() => { + void load(true, false); + }, [load]); + + const replace = (s: PayloadSource) => setSources((prev) => (prev ?? []).map((x) => (x.id === s.id ? s : x))); + + const setCardError = (id: string, text: string | null) => + setCardErrors((prev) => { + const next = { ...prev }; + if (text) next[id] = text; + else delete next[id]; + return next; + }); + + /** The add step's "Show its files": the project's newest release with payload files. */ + async function lookUp() { + if (!add || add.changing) return; + setAdd({ ...add, busy: true, error: null, preview: null }); + try { + const preview = await previewPayloadSource(add.url.trim()); + const first = preview.releases[0]?.files ?? []; + // A project added already opens on its current file. + const keep = preview.current_file; + const picked = first.some((f) => f.name === keep) ? keep : first.length === 1 ? first[0].name : ""; + setAdd((a) => a && { ...a, preview, picked, busy: false }); + } catch (e) { + setAdd((a) => a && { ...a, busy: false, preview: null, error: sourceProblemText(tr, problemOf(e)) }); + } + } + + async function confirmAdd() { + if (!add?.preview || !add.picked) return; + setAdd({ ...add, busy: true, error: null }); + try { + const saved = add.changing + ? await setPayloadSourceFile(add.changing.id, add.picked) + : await addPayloadSource(add.preview.project_url, add.picked); + setAdd(null); + setCardError(saved.id, null); + // The new file's newest release: from the list the preview just read. + await load(true, false); + } catch (e) { + setAdd((a) => a && { ...a, busy: false, error: sourceProblemText(tr, problemOf(e)) }); + } + } + + function openChange(s: PayloadSource) { + const state: AddState = { changing: s, url: s.project_url, preview: null, picked: s.file_name, busy: true, error: null }; + setAdd(state); + void (async () => { + try { + const preview = await previewPayloadSource(s.project_url); + const first = preview.releases[0]?.files ?? []; + const picked = first.some((f) => f.name === s.file_name) ? s.file_name : first.length === 1 ? first[0].name : ""; + setAdd((a) => a && a.changing?.id === s.id ? { ...a, preview, picked, busy: false } : a); + } catch (e) { + setAdd((a) => a && a.changing?.id === s.id ? { ...a, busy: false, error: sourceProblemText(tr, problemOf(e)) } : a); + } + })(); + } + + async function download(s: PayloadSource) { + setBusy({ id: s.id, what: "download" }); + setCardError(s.id, null); + try { + replace(await downloadPayloadSource(s.id)); + } catch (e) { + setCardError(s.id, sourceProblemText(tr, problemOf(e), s.file_pattern)); + } finally { + setBusy(null); + } + } + + async function send(s: PayloadSource) { + const have = s.have; + const h = host?.trim() ?? ""; + if (!have) return; + if (!h) { + setCardError(s.id, tr("payloads_no_host", undefined, "No PS5 host set. Connect on the Connection screen first.")); + return; + } + const ok = await confirm({ + title: tr("psrc_send_title", { file: have.file_name, host: h }, `Send ${have.file_name} to ${h}?`), + message: tr( + "psrc_send_body", + undefined, + "This file runs on the console with full access to it. Check that it is the one you expect.", + ), + details: [ + `${tr("psrc_release", undefined, "Release")}: ${have.tag || tr("psrc_release_unknown", undefined, "unknown")}`, + `${tr("psrc_size", undefined, "Size")}: ${formatBytes(have.size)}`, + `SHA-256: ${have.sha256}`, + ], + confirmLabel: tr("psrc_send", undefined, "Send to PS5"), + }); + if (!ok) return; + setBusy({ id: s.id, what: "send" }); + setCardError(s.id, null); + try { + const { viaPayloadManager } = await sendPayloadChecked(h, have.path); + pushNotification( + "success", + withConsolePrefix(h, tr("psrc_sent", { file: have.file_name }, `Sent ${have.file_name}`)), + { + body: viaPayloadManager + ? tr("psrc_sent_pm", undefined, "Port 9021 didn't answer, so it was launched through Payload Manager. Check the PS5 for its notification.") + : tr("psrc_sent_body", undefined, "Sent to the loader on port 9021. Check the PS5 for its notification."), + }, + ); + } catch (e) { + const why = payloadSendRefusalText(e); + setCardError(s.id, why); + pushNotification("error", withConsolePrefix(h, tr("payloads_send_failed", { id: have.file_name }, `Send failed: ${have.file_name}`)), { + body: why, + link: "/payloads", + }); + } finally { + setBusy(null); + } + } + + async function remove(s: PayloadSource) { + const ok = await confirm({ + title: tr("psrc_remove_title", { name: s.name }, `Remove ${s.name}?`), + message: tr("psrc_remove_body", undefined, "Its downloaded file is deleted from this computer too."), + confirmLabel: tr("psrc_remove", undefined, "Remove source"), + destructive: true, + }); + if (!ok) return; + setBusy({ id: s.id, what: "remove" }); + try { + await removePayloadSource(s.id); + setSources((prev) => (prev ?? []).filter((x) => x.id !== s.id)); + setCardError(s.id, null); + } catch (e) { + setCardError(s.id, sourceProblemText(tr, problemOf(e))); + } finally { + setBusy(null); + } + } + + const list = sources ?? []; + return ( +
    +
    +

    + {tr("psrc_title", undefined, "Your payload sources")} +

    +
    + {list.some((s) => s.file_name) && ( + + )} + {!add && ( + + )} +
    +
    + {list.length === 0 && !add && ( +

    + {tr( + "psrc_intro", + undefined, + "Add a GitHub, Gitea or Forgejo project that publishes payload files. PS5Upload downloads the file you pick only when you press Download, and sends it only when you press Send.", + )} +

    + )} + {listError && ( +

    + {listError} +

    + )} +
    + {add && ( + setAdd((a) => a && { ...a, url, preview: null, picked: "", error: null })} + onLookUp={() => void lookUp()} + onPick={(picked) => setAdd((a) => a && { ...a, picked })} + onAdd={() => void confirmAdd()} + onCancel={() => setAdd(null)} + /> + )} + {list.map((s) => ( + void download(s)} + onSend={() => void send(s)} + onChangeFile={() => openChange(s)} + onRemove={() => void remove(s)} + onOpenProject={() => void openExternalUrl(s.project_url)} + /> + ))} +
    + {dialog} +
    + ); +} diff --git a/client/src/state/consoleSendQueue.ts b/client/src/state/consoleSendQueue.ts new file mode 100644 index 000000000..a9917debc --- /dev/null +++ b/client/src/state/consoleSendQueue.ts @@ -0,0 +1,57 @@ +// "Send to another console" (#433) as queue rows: one copy per item, from one console to another, +// on the target console's queue. Files' Send dialog and its two panes (#952) both queue here. + +import { hostOf } from "../lib/addr"; +import type { SendItem } from "../lib/consoleSend"; +import { useC2cRoutes } from "./c2cRoutes"; +import { useUploadQueueStore, type QueueItem } from "./uploadQueue"; + +/** Queues each item from `fromHost` to `target` at its `dests[i]` and starts them; the row ids. */ +export function queueConsoleSend(fromHost: string, target: string, items: SendItem[], dests: string[]): string[] { + const from = hostOf(fromHost); + const to = hostOf(target); + const route = useC2cRoutes.getState().routeFor(from, to); + const q = useUploadQueueStore.getState(); + const ids = items.map((it, i) => + q.add({ + sourceKind: "ps5", + fromConsole: from, + route: route.mode, + directAddr: route.directAddr || null, + sourcePath: it.path, + displayName: it.name, + resolvedDest: dests[i], + addr: to, + strategy: "overwrite", + reconcileMode: "fast", + excludes: [], + mountAfterUpload: false, + mountReadOnly: true, + registerAfterUpload: false, + estimatedBytes: it.size, + }), + ); + q.startAdded(to, ids); + return ids; +} + +/** How a queued row ended: its last state, or "gone" when it was removed from the queue first. */ +export type QueueRowEnd = { status: "done" | "failed"; row: QueueItem } | { status: "gone" }; + +/** Resolves once the queue row `id` has ended (done or failed) or left the queue. */ +export function whenQueueRowEnds(id: string): Promise { + return new Promise((resolve) => { + let settled = false; + let unsub: () => void = () => {}; + const check = (items: QueueItem[]) => { + if (settled) return; + const row = items.find((r) => r.id === id); + if (row && row.status !== "done" && row.status !== "failed") return; + settled = true; + unsub(); + resolve(row ? { status: row.status as "done" | "failed", row } : { status: "gone" }); + }; + unsub = useUploadQueueStore.subscribe((s) => check(s.items)); + check(useUploadQueueStore.getState().items); + }); +} diff --git a/client/src/state/convertQueue.reload.test.ts b/client/src/state/convertQueue.reload.test.ts new file mode 100644 index 000000000..eeb287921 --- /dev/null +++ b/client/src/state/convertQueue.reload.test.ts @@ -0,0 +1,48 @@ +import { describe, expect, it, vi } from "vitest"; + +// A queue saved while it was making a game, as a page closed mid-build leaves it (#954). +vi.hoisted(() => { + const mem = new Map([ + [ + "ps5upload.convert_queue.v1", + JSON.stringify([ + { id: "a", source: "/games/A", compression: "balanced", then: "keep", host: null, status: "running" }, + { id: "b", source: "/games/B", compression: "balanced", then: "keep", host: null, status: "pending" }, + ]), + ], + ]); + (globalThis as { window?: unknown }).window = { + localStorage: { + getItem: (k: string) => (mem.has(k) ? (mem.get(k) as string) : null), + setItem: (k: string, v: string) => void mem.set(k, String(v)), + removeItem: (k: string) => void mem.delete(k), + clear: () => mem.clear(), + }, + addEventListener: () => {}, + removeEventListener: () => {}, + }; +}); +vi.mock("@tauri-apps/api/core", () => ({ invoke: vi.fn() })); + +import { setConvertRunner, useConvertQueue } from "./convertQueue"; + +describe("a Convert queue whose page was closed mid-build (#954)", () => { + it("waits for Start, says so, and runs from the game it was on when started", async () => { + const q = useConvertQueue.getState(); + expect(q.running).toBe(false); + expect(q.stoppedByClose).toBe(true); + expect(q.items.map((i) => i.status)).toEqual(["pending", "pending"]); + const built: string[] = []; + setConvertRunner({ + build: async (item) => { + built.push(item.source); + return { ok: true, packagePath: `/out/${item.id}.pkg` }; + }, + handOff: async () => ({ ok: true }), + }); + await q.start(); + expect(useConvertQueue.getState().stoppedByClose).toBe(false); + expect(built).toEqual(["/games/A", "/games/B"]); + expect(useConvertQueue.getState().items.map((i) => i.status)).toEqual(["done", "done"]); + }); +}); diff --git a/client/src/state/convertQueue.ts b/client/src/state/convertQueue.ts index 44bad51f7..926cd209c 100644 --- a/client/src/state/convertQueue.ts +++ b/client/src/state/convertQueue.ts @@ -279,13 +279,19 @@ export function savedItems(items: ConvertItem[]): Omit kept); } -function load(): ConvertItem[] { +/** The saved queue, and whether it was making a game when its page went (#954). */ +function load(): { items: ConvertItem[]; stoppedByClose: boolean } { try { const raw = safeGetItem(KEY); + if (!raw) return { items: [], stoppedByClose: false }; + const saved = JSON.parse(raw) as ConvertItem[]; // Whatever a saved queue says, no game comes back set to delete its archive. - return raw ? hydrateConvertQueue(savedItems(JSON.parse(raw) as ConvertItem[])) : []; + return { + items: hydrateConvertQueue(savedItems(saved)), + stoppedByClose: saved.some((i) => i.status === "running"), + }; } catch { - return []; + return { items: [], stoppedByClose: false }; } } @@ -297,6 +303,10 @@ interface ConvertQueueState { * source), so the result's buttons stay until then; never after a build that failed. Start * starts it at once. */ armed: boolean; + /** The queue was making a game when its page was closed or reloaded (#954). The queue is run + * by the page: the build itself goes on in the engine (and is picked up again when the page + * opens), but the next game starts only once Start is pressed again. Cleared by Start. */ + stoppedByClose: boolean; /** False (and nothing added) when this source is already waiting or building. */ add: (item: NewConvertItem) => boolean; remove: (id: string) => void; @@ -347,10 +357,12 @@ export const useConvertQueue = create((set, get) => { save(); }; + const loaded = typeof window === "undefined" ? { items: [], stoppedByClose: false } : load(); return { - items: typeof window === "undefined" ? [] : load(), + items: loaded.items, running: false, armed: false, + stoppedByClose: loaded.stoppedByClose, add: (item) => { // The same game for the same console once; another console may have it too. const busy = get().items.some( @@ -389,7 +401,7 @@ export const useConvertQueue = create((set, get) => { save(); }, start: async () => { - set({ armed: false }); + set({ armed: false, stoppedByClose: false }); if (get().running || !runner) return; const r0 = runner; stopRequested = false; diff --git a/client/src/state/copyChecks.ts b/client/src/state/copyChecks.ts index 49729d426..c5c5d27f4 100644 --- a/client/src/state/copyChecks.ts +++ b/client/src/state/copyChecks.ts @@ -83,10 +83,12 @@ export function useCopyCheck(path: string): CopyCheck | undefined { return useCopyChecks((s) => s.byPath[path]); } -/** Percent through a running check, or null when its size is not known yet. */ +/** Percent through a running check, or null when its size is not known yet. Never 100: a + * check that is still running has something left to do (#951: an older engine's package check + * reached its byte total and then read the whole package again). */ export function checkPercent( c: Pick, ): number | null { if (!c.bytes_total) return null; - return Math.min(100, Math.floor((c.bytes_done / c.bytes_total) * 100)); + return Math.min(99, Math.floor((c.bytes_done / c.bytes_total) * 100)); } diff --git a/client/src/state/fpkgConversion.test.ts b/client/src/state/fpkgConversion.test.ts index fadd8c2b3..21b42d756 100644 --- a/client/src/state/fpkgConversion.test.ts +++ b/client/src/state/fpkgConversion.test.ts @@ -101,7 +101,7 @@ import { useFpkgConversion, } from "./fpkgConversion"; import { commandTask, taskCapabilities } from "./taskControls"; -import { useTaskStore } from "./tasks"; +import { interruptedAtLoad, useTaskStore } from "./tasks"; const req = { source: "/games/a", outputDir: "/out" }; const tick = () => vi.advanceTimersByTimeAsync(POLL_MS + 50); @@ -1080,6 +1080,122 @@ describe("fpkg pipeline", () => { }); }); + /** As a reload leaves things: the page's run is gone, and its task (which a fresh start-up + * loads from storage) is marked interrupted. */ + const reload = async () => { + useFpkgConversion.setState({ pipeline: { phase: "idle" } }); + // The closed page's poll ends with it. + await tick(); + useTaskStore.setState((s) => ({ + tasks: s.tasks.map((t) => { + if (t.status !== "running" && t.status !== "paused") return t; + interruptedAtLoad.add(t.id); + return { ...t, status: "interrupted" as const, endedAtMs: t.updatedAtMs }; + }), + })); + }; + const convertTasks = () => useTaskStore.getState().tasks.filter((t) => t.kind === "fpkg-convert"); + + it("a build still running after the page was closed goes on in its own task (#954)", async () => { + const running = { status: "running", started_at_ms: 1000, stage: { id: "write", index: 2, count: 4, done: 5, total: 10 } }; + jobStatus.mockResolvedValue(running); + await useFpkgConversion.getState().start(req, { install: false, host: null }); + await tick(); + const [task] = convertTasks(); + expect(task).toMatchObject({ engineJobId: "j1", payload: { jobKind: "build", source: "/games/a" } }); + await reload(); + expect(convertTasks()[0].status).toBe("interrupted"); + // The engine lists it as a Workshop run too: followed once, in the task it had. + runningJobs.mockResolvedValueOnce([{ job_id: "j1", kind: "package", source: "/games/a", started_at_ms: 1000 }]); + await useFpkgConversion.getState().attachRunning(); + expect(useFpkgConversion.getState().pipeline).toMatchObject({ + phase: "running", + source: "/games/a", + jobId: "j1", + attached: true, + taskId: task.id, + startedMs: 1000, + }); + expect(convertTasks()).toHaveLength(1); + expect(convertTasks()[0]).toMatchObject({ id: task.id, status: "running" }); + expect(interruptedAtLoad.has(task.id)).toBe(false); + await tick(); + expect(convertTasks()[0].progress).toMatchObject({ current: 5, total: 10 }); + jobStatus.mockResolvedValue({ status: "done", dest: "/out/a.pkg", bytes_sent: 9 }); + await tick(); + expect(useFpkgConversion.getState().pipeline).toMatchObject({ phase: "done", packagePath: "/out/a.pkg", attached: true }); + expect(convertTasks()[0].status).toBe("done"); + }); + + it("a build that finished while the page was closed shows as finished, with its result (#954)", async () => { + jobStatus.mockResolvedValue({ status: "running" }); + await useFpkgConversion.getState().start(req, { install: false, host: null }); + await tick(); + await reload(); + jobStatus.mockResolvedValue({ status: "done", dest: "/out/a.pkg", bytes_sent: 9, started_at_ms: 1 }); + await useFpkgConversion.getState().attachRunning(); + await tick(); + expect(useFpkgConversion.getState().pipeline).toMatchObject({ + phase: "done", + source: "/games/a", + packagePath: "/out/a.pkg", + attached: true, + }); + expect(convertTasks()).toHaveLength(1); + expect(convertTasks()[0].status).toBe("done"); + }); + + it("a build that failed while the page was closed says why (#954)", async () => { + jobStatus.mockResolvedValue({ status: "running" }); + await useFpkgConversion.getState().start(req, { install: false, host: null }); + await tick(); + await reload(); + jobStatus.mockResolvedValue({ status: "failed", error: "disk full" }); + await useFpkgConversion.getState().attachRunning(); + await tick(); + expect(convertTasks()[0]).toMatchObject({ status: "failed", lastError: { message: "disk full" } }); + }); + + it("a failed read is asked again before a run is called interrupted (#954)", async () => { + jobStatus.mockResolvedValue({ status: "running" }); + await useFpkgConversion.getState().start(req, { install: false, host: null }); + await tick(); + await reload(); + jobStatus.mockReset().mockRejectedValueOnce(new Error("HTTP 503")).mockResolvedValue({ status: "running" }); + const attached = useFpkgConversion.getState().attachRunning(); + await vi.advanceTimersByTimeAsync(1500); + await attached; + expect(useFpkgConversion.getState().pipeline).toMatchObject({ phase: "running", jobId: "j1", attached: true }); + expect(convertTasks()).toHaveLength(1); + expect(convertTasks()[0].status).toBe("running"); + }); + + it("a run the engine no longer knows stays interrupted (#954)", async () => { + jobStatus.mockResolvedValue({ status: "running" }); + await useFpkgConversion.getState().start(req, { install: false, host: null }); + await tick(); + await reload(); + // The engine restarted (the desktop app quit, the container was recreated): the job died. + jobStatus.mockReset().mockRejectedValue(new Error("job not found")); + await useFpkgConversion.getState().attachRunning(); + expect(useFpkgConversion.getState().pipeline.phase).toBe("idle"); + expect(convertTasks()).toHaveLength(1); + expect(convertTasks()[0].status).toBe("interrupted"); + expect(jobStatus).toHaveBeenCalledTimes(1); + }); + + it("a Convert & install found after a reload is followed as a build: Install waits for the user (#954)", async () => { + jobStatus.mockResolvedValue({ status: "running" }); + await useFpkgConversion.getState().start(req, { install: true, host: "10.0.0.2", method: "stream" }); + await tick(); + await reload(); + jobStatus.mockResolvedValue({ status: "done", dest: "/out/a.pkg", bytes_sent: 9 }); + await useFpkgConversion.getState().attachRunning(); + await tick(); + expect(useFpkgConversion.getState().pipeline).toMatchObject({ phase: "done", mode: "convert", packagePath: "/out/a.pkg" }); + expect(installStream).not.toHaveBeenCalled(); + }); + it("does not take over a window that is already busy", async () => { await useFpkgConversion.getState().start(req, { install: false, host: null }); runningJobs.mockResolvedValueOnce([{ job_id: "j9", kind: "image", source: "/g/A", started_at_ms: 5 }]); diff --git a/client/src/state/fpkgConversion.ts b/client/src/state/fpkgConversion.ts index 40ccf8a2b..386331381 100644 --- a/client/src/state/fpkgConversion.ts +++ b/client/src/state/fpkgConversion.ts @@ -30,13 +30,13 @@ import { type WorkshopRun, type ZstdPacks, } from "../api/fpkg"; -import { jobCancel, jobPause, jobResume, jobStatus } from "../api/ps5"; +import { jobCancel, jobPause, jobResume, jobStatus, type JobSnapshot } from "../api/ps5"; import { useConnectionStore } from "./connection"; import { useRosterStore } from "./roster"; import { hostOf } from "../lib/addr"; import { pushNotification } from "./notifications"; import { pkgLibraryStore, type PkgLibraryStore } from "./pkgLibrary"; -import { useTaskStore } from "./tasks"; +import { interruptedAtLoad, useTaskStore, type Task } from "./tasks"; import { remoteApi } from "../api/remote"; import { fetchRemote } from "../lib/materialize"; import { isRemotePath, parseRemotePath } from "../lib/remotePath"; @@ -328,6 +328,21 @@ function update(patch: Partial) { if (p) useFpkgConversion.setState({ pipeline: { ...p, ...patch } }); } +/** What a run's engine job is: a build (followed by `poll`) or an archive's unpack. */ +type JobKind = "build" | "extract"; + +/** The run follows the engine job `jobId` from now on. Its task keeps the job's id and kind, so + * a page closed or reloaded meanwhile finds the job again (`attachRunning`, #954): the engine + * runs it by itself, whether a page watches or not. */ +function follow(jobId: string, kind: JobKind) { + update({ jobId }); + const p = running(); + if (p?.taskId) + useTaskStore + .getState() + .updateTask(p.taskId, { engineJobId: jobId, payload: { mode: p.mode, source: p.source, jobKind: kind } }); +} + /** Time this run has spent paused up to `now`, the current pause included. */ export function pausedSoFar(p: Running, now: number): number { return (p.pausedMs ?? 0) + (p.pausedAtMs != null ? Math.max(0, now - p.pausedAtMs) : 0); @@ -791,10 +806,13 @@ function poll(jobId: string, install: InstallMethod | null, failures = 0) { } -function beginRun(mode: PipelineMode, source: string, host: string | null, stage: PipelineStage) { +/** `taskId`: the task of a run this page started before it was closed or reloaded (#954), which + * goes on in place of a new one. */ +function beginRun(mode: PipelineMode, source: string, host: string | null, stage: PipelineStage, taskId0?: string) { const now = Date.now(); const taskId = - mode === "install" + taskId0 ?? + (mode === "install" ? null : useTaskStore.getState().registerTask({ kind: "fpkg-convert", @@ -802,8 +820,9 @@ function beginRun(mode: PipelineMode, source: string, host: string | null, stage label: `${mode === "image" ? "Make image of" : mode === "folder" ? "Make folder of" : "Convert"} ${baseName(source)}`, detail: source, consoleId: host ?? "", + payload: { mode, source }, control: { owner: "fpkg-convert" }, - }); + })); reportStage(taskId, stage, 0, 0); useFpkgConversion.setState({ pipeline: { @@ -940,7 +959,7 @@ export function failureText(p: Extract): string { * `free`, the archive is deleted as it unpacks. */ async function extractArchive(archive: string, outputDir: string | undefined, password?: string, free?: boolean) { const { job_id } = await fpkg.extract(archive, outputDir, password, ...(free ? [true as const] : [])); - update({ jobId: job_id }); + follow(job_id, "extract"); for (;;) { const s = await readWithRetries(() => jobStatus(job_id)); if (running()?.jobId === job_id) markPaused(s.status === "running" && s.paused === true); @@ -985,7 +1004,7 @@ async function prepareThenStart( enterStage("check"); try { const { job_id } = await inPlace(local); - update({ jobId: job_id }); + follow(job_id, "build"); poll(job_id, install); return; } catch (error) { @@ -1019,7 +1038,7 @@ async function prepareThenStart( enterStage("check"); try { const { job_id } = await startJob(local); - update({ jobId: job_id }); + follow(job_id, "build"); poll(job_id, install); } catch (error) { fail("check", error instanceof Error ? error.message : String(error), null); @@ -1099,6 +1118,61 @@ function modeOfKind(kind: WorkshopRun["kind"]): PipelineMode { return kind === "image" ? "image" : kind === "folder" ? "folder" : "convert"; } +/** A run this page left going when it was closed or reloaded, as the engine answers for its job. */ +interface LeftRun { + task: Task; + jobId: string; + kind: JobKind; + snap: JobSnapshot; +} + +/** The Convert tasks this start-up found running and marked interrupted, with their engine job's + * state now; those the engine does not know (it restarted) or did not answer for are left out + * and stay interrupted. */ +async function leftRunning(): Promise { + const tasks = useTaskStore + .getState() + .tasks.filter((t) => t.kind === "fpkg-convert" && t.status === "interrupted" && interruptedAtLoad.has(t.id)); + const found = await Promise.all( + tasks.map(async (task): Promise => { + const jobId = task.engineJobId; + if (!jobId) return null; + try { + const snap = await readWithRetries(() => jobStatus(jobId)); + return { task, jobId, kind: task.payload.jobKind === "extract" ? "extract" : "build", snap }; + } catch { + return null; + } + }), + ); + return found.filter((l): l is LeftRun => l !== null); +} + +/** A left run this screen does not follow (it follows one run at a time): a build that ended has + * its task say how; one still running, or an unpack whose build was lost, stays interrupted. */ +function settleLeft({ task, kind, snap }: LeftRun) { + if (kind !== "build" || (snap.status !== "done" && snap.status !== "failed")) return; + const tasks = useTaskStore.getState(); + if (!tasks.reopenTask(task.id)) return; + if (snap.status === "done") tasks.finishTask(task.id, "done", snap.dest ? { detail: snap.dest } : undefined); + else if (isCancelMessage(snap.error ?? "")) tasks.finishTask(task.id, "cancelled"); + else + tasks.finishTask(task.id, "failed", { + lastError: { code: "FPKG_FAILED", message: snap.error ?? "The build failed.", recoverable: false }, + }); +} + +/** The run mode a left task is followed in: what it makes. An install that was to follow a build + * is not started from here (another window may be doing it): the result offers Install. */ +function modeOfTask(task: Task): PipelineMode { + const mode = task.payload.mode; + return mode === "image" || mode === "folder" ? mode : "convert"; +} + +function sourceOfTask(task: Task): string { + return typeof task.payload.source === "string" ? task.payload.source : (task.detail ?? ""); +} + /** Follow an unpack whose page was closed: the build that was to follow it died with the page, so * its folder is dropped and the user is told to start again. */ async function followLostUnpack(jobId: string) { @@ -1206,7 +1280,7 @@ export const useFpkgConversion = create((set, get) => ({ beginRun(install ? "convert-install" : "convert", req.source, host, "check"); try { const { job_id } = await fpkg.build({ ...req, fullVerify }); - update({ jobId: job_id }); + follow(job_id, "build"); poll(job_id, then); } catch (error) { fail("check", error instanceof Error ? error.message : String(error), null); @@ -1289,7 +1363,7 @@ export const useFpkgConversion = create((set, get) => ({ // Only when it goes to the PS5: a local build's call stays as it was. ...buildTail(toConsole ? await consoleDestination(toConsole) : toServer, own?.update, extrasOf(own)), ); - update({ jobId: job_id }); + follow(job_id, "build"); poll(job_id, null); } catch (error) { fail(lz4 ? "pack" : "write", error instanceof Error ? error.message : String(error), null); @@ -1347,7 +1421,7 @@ export const useFpkgConversion = create((set, get) => ({ withLz4(extras), ), ); - update({ jobId: job_id }); + follow(job_id, "build"); poll(job_id, null); } catch (error) { fail(first, error instanceof Error ? error.message : String(error), null); @@ -1395,11 +1469,31 @@ export const useFpkgConversion = create((set, get) => ({ attachRunning: async () => { if (get().pipeline.phase !== "idle") return; + // This page's own runs that were going when it was closed or reloaded (#954). The engine + // runs a job by itself, so each is asked about: still running, or ended while the page was + // away, its task goes on instead of staying "interrupted". A failed read is asked again + // (readWithRetries); only an engine that no longer knows the job (it restarted), or no + // answer at all, leaves the task interrupted. + const left = await leftRunning(); const runs: WorkshopRun[] | null = await fpkg.runningJobs().catch(() => null); - // An engine that answers with no list has nothing to follow. - const run = Array.isArray(runs) ? runs[0] : undefined; - // Started by hand meanwhile, or nothing to follow. - if (!run || get().pipeline.phase !== "idle") return; + // An engine that answers with no list has nothing else to follow. + const others = (Array.isArray(runs) ? runs : []).filter((r) => !left.some((l) => l.jobId === r.job_id)); + // Followed on this screen: a run of ours still going, else one from another window, else + // one of ours that ended meanwhile (its result and Install, Delete... as if never away). + const mine = left.find((l) => l.snap.status === "running") ?? (others.length ? undefined : left[0]); + const followed = get().pipeline.phase === "idle" ? mine ?? others[0] : undefined; + for (const l of left) if (l !== followed) settleLeft(l); + if (!followed) return; + if ("task" in followed) { + const { task, jobId, kind, snap } = followed; + useTaskStore.getState().reopenTask(task.id); + beginRun(modeOfTask(task), sourceOfTask(task), task.consoleId || null, kind === "extract" ? "extract" : "check", task.id); + update({ jobId, attached: true, startedMs: snap.started_at_ms || Date.now() }); + if (kind === "extract") void followLostUnpack(jobId); + else poll(jobId, null); + return; + } + const run = followed; const stage: PipelineStage = run.kind === "extract" ? "extract" : "check"; beginRun(modeOfKind(run.kind), run.source, null, stage); update({ jobId: run.job_id, attached: true, startedMs: run.started_at_ms || Date.now() }); diff --git a/client/src/state/tasks.ts b/client/src/state/tasks.ts index 8d0d28e96..58a021d97 100644 --- a/client/src/state/tasks.ts +++ b/client/src/state/tasks.ts @@ -20,8 +20,10 @@ * * Persistence: active + recently-finished tasks persist to localStorage * so the Tasks tab survives reloads. On reload, any task still in a - * non-terminal state is marked "interrupted" (a flavor of failed) — the - * underlying engine op didn't actually keep running. + * non-terminal state is marked "interrupted" (a flavor of failed). An + * engine job can outlive the page (the web UI's tab, a reloaded window): + * its owner asks the engine and `reopenTask`s one that is still going or + * ended while the page was away (#954: Convert). */ import { create } from "zustand"; @@ -447,6 +449,11 @@ interface TaskState { /** Look up a task by id. Returns undefined if not found (including * terminal history evicted by MAX_TASK_HISTORY). */ getTask: (id: string) => Task | undefined; + + /** A task this start-up marked interrupted whose engine job turned out to be still running, + * or to have ended while the page was away (#954): it is running again, so its owner can + * follow the job and finish it as it ends. False (nothing changed) for any other task. */ + reopenTask: (id: string) => boolean; } export const useTaskStore = create((set, get) => ({ @@ -543,4 +550,19 @@ export const useTaskStore = create((set, get) => ({ }, getTask: (id) => get().tasks.find((t) => t.id === id), + + reopenTask: (id) => { + const existing = get().tasks.find((t) => t.id === id); + if (!existing || existing.status !== "interrupted" || !interruptedAtLoad.has(id)) return false; + interruptedAtLoad.delete(id); + set((s) => { + const now = Date.now(); + const tasks = s.tasks.map((t) => + t.id === id ? { ...t, status: "running" as TaskStatus, endedAtMs: null, updatedAtMs: now } : t, + ); + persist(tasks); + return { tasks }; + }); + return true; + }, })); diff --git a/client/vite.pageCss.test.ts b/client/vite.pageCss.test.ts index dffa4cd91..4a6265af5 100644 --- a/client/vite.pageCss.test.ts +++ b/client/vite.pageCss.test.ts @@ -1,13 +1,22 @@ -import { mkdtempSync, mkdirSync, writeFileSync } from "node:fs"; +import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; -import { describe, expect, it } from "vitest"; +import { afterAll, describe, expect, it } from "vitest"; import { pageFiles, scopedCss } from "./vite.pageCss"; +// Temp folders are removed when the file's tests end, pass or fail (PS5UPLOAD_KEEP_TEST_TMP=1 keeps +// them to look at). +const tempDirs: string[] = []; +afterAll(() => { + if (process.env.PS5UPLOAD_KEEP_TEST_TMP) return; + for (const dir of tempDirs) rmSync(dir, { recursive: true, force: true }); +}); + describe("pageFiles", () => { it("walks relative imports, follows a swap, and leaves packages and styles out", () => { const dir = mkdtempSync(path.join(tmpdir(), "page-css-")); + tempDirs.push(dir); mkdirSync(path.join(dir, "join")); mkdirSync(path.join(dir, "components")); const put = (name: string, text: string) => diff --git a/engine/Cargo.lock b/engine/Cargo.lock index 4ebb8a349..8fd1115c1 100644 --- a/engine/Cargo.lock +++ b/engine/Cargo.lock @@ -2561,7 +2561,7 @@ dependencies = [ [[package]] name = "ps5-dump-forge-exfat" -version = "12.6.32" +version = "12.6.33" dependencies = [ "ps5-dump-forge-patch", "ps5upload-fpkg", @@ -2570,14 +2570,14 @@ dependencies = [ [[package]] name = "ps5-dump-forge-patch" -version = "12.6.32" +version = "12.6.33" dependencies = [ "crc32fast", ] [[package]] name = "ps5-dump-forge-pfs" -version = "12.6.32" +version = "12.6.33" dependencies = [ "flate2", "ps5-dump-forge-patch", @@ -2587,7 +2587,7 @@ dependencies = [ [[package]] name = "ps5-dump-forge-ufs2" -version = "12.6.32" +version = "12.6.33" dependencies = [ "ps5-dump-forge-patch", "ps5upload-fpkg", @@ -2597,7 +2597,7 @@ dependencies = [ [[package]] name = "ps5-dump-forge-zstd" -version = "12.6.32" +version = "12.6.33" dependencies = [ "crc32fast", "getrandom 0.4.3", @@ -2608,7 +2608,7 @@ dependencies = [ [[package]] name = "ps5upload-apidoc" -version = "12.6.32" +version = "12.6.33" dependencies = [ "proc-macro2", "quote", @@ -2618,7 +2618,7 @@ dependencies = [ [[package]] name = "ps5upload-archive" -version = "12.6.32" +version = "12.6.33" dependencies = [ "anyhow", "crc32fast", @@ -2628,7 +2628,7 @@ dependencies = [ [[package]] name = "ps5upload-ava1" -version = "12.6.32" +version = "12.6.33" dependencies = [ "anyhow", "ava1", @@ -2651,7 +2651,7 @@ dependencies = [ [[package]] name = "ps5upload-convert" -version = "12.6.32" +version = "12.6.33" dependencies = [ "libc", "ps5upload-archive", @@ -2666,7 +2666,7 @@ dependencies = [ [[package]] name = "ps5upload-convert-core" -version = "12.6.32" +version = "12.6.33" dependencies = [ "blake3", "flate2", @@ -2686,7 +2686,7 @@ dependencies = [ [[package]] name = "ps5upload-core" -version = "12.6.32" +version = "12.6.33" dependencies = [ "aes 0.9.4", "aes-gcm 0.11.1", @@ -2720,7 +2720,7 @@ dependencies = [ [[package]] name = "ps5upload-ctest" -version = "12.6.32" +version = "12.6.33" dependencies = [ "anyhow", "ava1", @@ -2736,7 +2736,7 @@ dependencies = [ [[package]] name = "ps5upload-engine" -version = "12.6.32" +version = "12.6.33" dependencies = [ "aes 0.9.4", "aes-gcm 0.11.1", @@ -2804,7 +2804,7 @@ dependencies = [ [[package]] name = "ps5upload-fpkg" -version = "12.6.32" +version = "12.6.33" dependencies = [ "aes 0.9.4", "blake3", @@ -2828,7 +2828,7 @@ dependencies = [ [[package]] name = "ps5upload-hub" -version = "12.6.32" +version = "12.6.33" dependencies = [ "axum", "base64 0.23.1", @@ -2843,7 +2843,7 @@ dependencies = [ [[package]] name = "ps5upload-lab" -version = "12.6.32" +version = "12.6.33" dependencies = [ "anyhow", "ava1", @@ -2861,7 +2861,7 @@ dependencies = [ [[package]] name = "ps5upload-pkg" -version = "12.6.32" +version = "12.6.33" dependencies = [ "aes 0.9.4", "blake3", @@ -2873,14 +2873,14 @@ dependencies = [ [[package]] name = "ps5upload-tailnet" -version = "12.6.32" +version = "12.6.33" dependencies = [ "cc", ] [[package]] name = "ps5upload-tests" -version = "12.6.32" +version = "12.6.33" dependencies = [ "anyhow", "ava1", @@ -2898,7 +2898,7 @@ dependencies = [ [[package]] name = "ps5upload-unrar" -version = "12.6.32" +version = "12.6.33" dependencies = [ "serde", "serde_json", diff --git a/engine/Cargo.toml b/engine/Cargo.toml index 028d8ead3..489a2ad0c 100644 --- a/engine/Cargo.toml +++ b/engine/Cargo.toml @@ -32,7 +32,7 @@ resolver = "2" [workspace.package] edition = "2021" license = "GPL-3.0-or-later" -version = "12.6.32" +version = "12.6.33" [workspace.dependencies] # AVA1 (github.com/phantomptr/ava1): the Rust crate from crates.io; the payload builds the C side diff --git a/engine/crates/ps5-dump-forge-exfat/tests/edit.rs b/engine/crates/ps5-dump-forge-exfat/tests/edit.rs index 5145dcfd9..d2c405598 100644 --- a/engine/crates/ps5-dump-forge-exfat/tests/edit.rs +++ b/engine/crates/ps5-dump-forge-exfat/tests/edit.rs @@ -17,7 +17,7 @@ impl TempDir { fn new(tag: &str) -> Self { static N: AtomicU32 = AtomicU32::new(0); let n = N.fetch_add(1, Ordering::Relaxed); - let dir = std::env::temp_dir().join(format!( + let dir = crate::test_tmp::temp_path(format!( "ps5-dump-forge-exfat-edit-{tag}-{}-{n}", std::process::id() )); @@ -482,3 +482,7 @@ fn every_op_in_one_plan() { std::fs::create_dir_all(tree.join("data")).unwrap(); std::fs::copy(&image, keep.join("every-op.exfat")).unwrap(); } + +// Test scratch paths removed when the test process exits (engine/test-support/test_tmp.rs). +#[path = "../../../test-support/test_tmp.rs"] +mod test_tmp; diff --git a/engine/crates/ps5-dump-forge-patch/src/lib.rs b/engine/crates/ps5-dump-forge-patch/src/lib.rs index 23679bb3c..8e1b6028a 100644 --- a/engine/crates/ps5-dump-forge-patch/src/lib.rs +++ b/engine/crates/ps5-dump-forge-patch/src/lib.rs @@ -966,7 +966,7 @@ mod tests { fn image() -> (Tmp, PathBuf, Vec) { static N: AtomicUsize = AtomicUsize::new(0); let n = N.fetch_add(1, Ordering::Relaxed); - let dir = std::env::temp_dir().join(format!("forge-patch-{}-{n}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("forge-patch-{}-{n}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); let path = dir.join("game.ffpkg"); @@ -1467,3 +1467,8 @@ mod tests { } } } + +// Test scratch paths removed when the test process exits (engine/test-support/test_tmp.rs). +#[cfg(test)] +#[path = "../../../test-support/test_tmp.rs"] +mod test_tmp; diff --git a/engine/crates/ps5-dump-forge-pfs/src/edit.rs b/engine/crates/ps5-dump-forge-pfs/src/edit.rs index 6913f84d7..ce036d775 100644 --- a/engine/crates/ps5-dump-forge-pfs/src/edit.rs +++ b/engine/crates/ps5-dump-forge-pfs/src/edit.rs @@ -1617,7 +1617,7 @@ mod tests { static N: AtomicU32 = AtomicU32::new(0); let n = N.fetch_add(1, Ordering::Relaxed); let path = - std::env::temp_dir().join(format!("forge-pfs-edit-{}-{n}.ffpfs", std::process::id())); + crate::test_tmp::temp_path(format!("forge-pfs-edit-{}-{n}.ffpfs", std::process::id())); File::create(&path)?.write_all(img)?; let mut f = File::open(&path)?; let v = Volume::open_within(&mut f, limit); @@ -1862,7 +1862,7 @@ mod tests { files.extend([("A_", 3), ("B@", 4), ("eboot.bin", 5)]); let img = build(&files, &["empty"]); let path = - std::env::temp_dir().join(format!("forge-pfs-peak-{}.ffpfs", std::process::id())); + crate::test_tmp::temp_path(format!("forge-pfs-peak-{}.ffpfs", std::process::id())); std::fs::write(&path, &img).unwrap(); let mut f = File::open(&path).unwrap(); let (v, top) = counting::peak_of(|| Volume::open(&mut f).unwrap().unwrap()); @@ -1892,7 +1892,7 @@ mod tests { static N: AtomicU32 = AtomicU32::new(0); let n = N.fetch_add(1, Ordering::Relaxed); let path = - std::env::temp_dir().join(format!("forge-pfs-plan-{}-{n}.ffpfs", std::process::id())); + crate::test_tmp::temp_path(format!("forge-pfs-plan-{}-{n}.ffpfs", std::process::id())); File::create(&path).unwrap().write_all(img).unwrap(); let mut f = File::open(&path).unwrap(); let out = super::plan(&mut f, ops); diff --git a/engine/crates/ps5-dump-forge-pfs/src/lib.rs b/engine/crates/ps5-dump-forge-pfs/src/lib.rs index 08c03d8a2..213781f8e 100644 --- a/engine/crates/ps5-dump-forge-pfs/src/lib.rs +++ b/engine/crates/ps5-dump-forge-pfs/src/lib.rs @@ -229,3 +229,8 @@ fn le32(b: &[u8], at: usize) -> u32 { fn le64(b: &[u8], at: usize) -> u64 { u64::from_le_bytes(b[at..at + 8].try_into().unwrap_or([0; 8])) } + +// Test scratch paths removed when the test process exits (engine/test-support/test_tmp.rs). +#[cfg(test)] +#[path = "../../../test-support/test_tmp.rs"] +mod test_tmp; diff --git a/engine/crates/ps5-dump-forge-pfs/src/wrap.rs b/engine/crates/ps5-dump-forge-pfs/src/wrap.rs index 5995f193d..57c0a0abd 100644 --- a/engine/crates/ps5-dump-forge-pfs/src/wrap.rs +++ b/engine/crates/ps5-dump-forge-pfs/src/wrap.rs @@ -1123,7 +1123,7 @@ mod tests { use std::time::Duration; fn temp(tag: &str) -> PathBuf { - let d = std::env::temp_dir().join(format!("pfs-wrap-{tag}-{}", std::process::id())); + let d = crate::test_tmp::temp_path(format!("pfs-wrap-{tag}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&d); std::fs::create_dir_all(&d).unwrap(); d diff --git a/engine/crates/ps5-dump-forge-pfs/tests/roundtrip.rs b/engine/crates/ps5-dump-forge-pfs/tests/roundtrip.rs index ff41281e6..0f888ef7a 100644 --- a/engine/crates/ps5-dump-forge-pfs/tests/roundtrip.rs +++ b/engine/crates/ps5-dump-forge-pfs/tests/roundtrip.rs @@ -24,7 +24,7 @@ impl TempDir { fn new(tag: &str) -> Self { static N: AtomicU32 = AtomicU32::new(0); let n = N.fetch_add(1, Ordering::Relaxed); - let dir = std::env::temp_dir().join(format!( + let dir = crate::test_tmp::temp_path(format!( "ps5-dump-forge-pfs-{tag}-{}-{n}", std::process::id() )); @@ -1110,3 +1110,7 @@ fn real_game_sample_round_trips_at_every_level() { ); } } + +// Test scratch paths removed when the test process exits (engine/test-support/test_tmp.rs). +#[path = "../../../test-support/test_tmp.rs"] +mod test_tmp; diff --git a/engine/crates/ps5-dump-forge-ufs2/src/edit.rs b/engine/crates/ps5-dump-forge-ufs2/src/edit.rs index 5806beb76..5bf5fcda1 100644 --- a/engine/crates/ps5-dump-forge-ufs2/src/edit.rs +++ b/engine/crates/ps5-dump-forge-ufs2/src/edit.rs @@ -2772,7 +2772,7 @@ mod tests { /// The cylinder groups count against the budget: past it, the open is a finding. #[test] fn past_the_budget_is_refused() { - let dir = std::env::temp_dir().join(format!("forge-ufs2-budget-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("forge-ufs2-budget-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(dir.join("src/sce_sys")).unwrap(); std::fs::write(dir.join("src/eboot.bin"), b"x").unwrap(); diff --git a/engine/crates/ps5-dump-forge-ufs2/src/lib.rs b/engine/crates/ps5-dump-forge-ufs2/src/lib.rs index 3531db7c1..353d53336 100644 --- a/engine/crates/ps5-dump-forge-ufs2/src/lib.rs +++ b/engine/crates/ps5-dump-forge-ufs2/src/lib.rs @@ -554,3 +554,8 @@ mod tests { } } } + +// Test scratch paths removed when the test process exits (engine/test-support/test_tmp.rs). +#[cfg(test)] +#[path = "../../../test-support/test_tmp.rs"] +mod test_tmp; diff --git a/engine/crates/ps5upload-archive/src/lib.rs b/engine/crates/ps5upload-archive/src/lib.rs index 47c612e05..53eb436e8 100644 --- a/engine/crates/ps5upload-archive/src/lib.rs +++ b/engine/crates/ps5upload-archive/src/lib.rs @@ -5,3 +5,8 @@ pub mod names; pub mod stream; + +// Test scratch paths removed when the test process exits (engine/test-support/test_tmp.rs). +#[cfg(test)] +#[path = "../../../test-support/test_tmp.rs"] +mod test_tmp; diff --git a/engine/crates/ps5upload-archive/src/stream.rs b/engine/crates/ps5upload-archive/src/stream.rs index 07cc3d714..e0c4ff947 100644 --- a/engine/crates/ps5upload-archive/src/stream.rs +++ b/engine/crates/ps5upload-archive/src/stream.rs @@ -1552,8 +1552,10 @@ mod tests { use std::io::Write; fn dir(name: &str) -> PathBuf { - let d = - std::env::temp_dir().join(format!("ps5u-archive-stream-{name}-{}", std::process::id())); + let d = crate::test_tmp::temp_path(format!( + "ps5u-archive-stream-{name}-{}", + std::process::id() + )); let _ = std::fs::remove_dir_all(&d); std::fs::create_dir_all(&d).unwrap(); d diff --git a/engine/crates/ps5upload-ava1/src/console.rs b/engine/crates/ps5upload-ava1/src/console.rs index 497348ed2..3a5a4ef04 100644 --- a/engine/crates/ps5upload-ava1/src/console.rs +++ b/engine/crates/ps5upload-ava1/src/console.rs @@ -353,7 +353,7 @@ mod tests { #[test] fn nothing_listening_is_helper_not_ava1_with_the_exact_message() { - let d = std::env::temp_dir().join(format!("p5a-console-{}", std::process::id())); + let d = crate::test_tmp::temp_path(format!("p5a-console-{}", std::process::id())); let _ = std::fs::remove_dir_all(&d); // Port 1 is never a listener: the attempt is refused at once. let p = Pool::new(d.join("ava")).with_addr("127.0.0.1:1"); @@ -436,7 +436,7 @@ mod tests { /// A pool whose every console refuses at once (port 1) and whose DDP answers `code`; /// the counter is how many times DDP was asked. fn refusing(tag: &str, code: Option) -> (Pool, Arc, std::path::PathBuf) { - let d = std::env::temp_dir().join(format!("p5a-rest-{tag}-{}", std::process::id())); + let d = crate::test_tmp::temp_path(format!("p5a-rest-{tag}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&d); let asked = Arc::new(AtomicUsize::new(0)); let n = asked.clone(); @@ -493,7 +493,7 @@ mod tests { #[test] fn a_timeout_with_no_ddp_reply_is_unreachable_in_plain_words() { let (_l, addr) = silent_listener(); - let d = std::env::temp_dir().join(format!("p5a-rest-timeout-{}", std::process::id())); + let d = crate::test_tmp::temp_path(format!("p5a-rest-timeout-{}", std::process::id())); let _ = std::fs::remove_dir_all(&d); let p = Pool::new(d.join("ava")) .with_addr(addr) diff --git a/engine/crates/ps5upload-ava1/src/download.rs b/engine/crates/ps5upload-ava1/src/download.rs index 4b68f0306..516a91799 100644 --- a/engine/crates/ps5upload-ava1/src/download.rs +++ b/engine/crates/ps5upload-ava1/src/download.rs @@ -1501,7 +1501,7 @@ mod tests { #[test] fn landed_files_keep_the_ps5_times() { // #812: a clip downloaded from the PS5 was dated when it arrived. - let d = std::env::temp_dir().join(format!("p5a-mtime-{}", std::process::id())); + let d = crate::test_tmp::temp_path(format!("p5a-mtime-{}", std::process::id())); let _ = std::fs::remove_dir_all(&d); std::fs::create_dir_all(d.join("Clips/sub")).unwrap(); std::fs::write(d.join("Clips/a.mp4"), b"a").unwrap(); @@ -1579,7 +1579,7 @@ mod tests { /// against what the disk under the temp folder really does. #[test] fn names_that_differ_only_in_case_are_refused_where_the_disk_merges_them() { - let dir = std::env::temp_dir().join(format!("ps5u-dl-case-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("ps5u-dl-case-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(dir.join("probe")).unwrap(); let really = dir.join("PROBE").exists(); @@ -1613,7 +1613,7 @@ mod tests { /// `VOL` and said the disk folds case. #[test] fn the_case_question_is_asked_inside_the_destination_never_above_it() { - let dir = std::env::temp_dir().join(format!("ps5u-dl-case-at-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("ps5u-dl-case-at-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(dir.join("vol")).unwrap(); let folds = std::fs::create_dir(dir.join("VOL")).is_err(); @@ -1824,7 +1824,7 @@ mod tests { #[test] fn a_descriptor_shortage_is_waited_out_not_terminal() { - let d = std::env::temp_dir().join(format!("p5a-emfile-{}", std::process::id())); + let d = crate::test_tmp::temp_path(format!("p5a-emfile-{}", std::process::id())); let _ = std::fs::remove_dir_all(&d); std::fs::create_dir_all(d.join("share/G")).unwrap(); for i in 0..3u8 { @@ -1900,7 +1900,7 @@ mod tests { // download as a bad manifest. #[test] fn a_zip_download_restarts_when_a_file_is_sent_again() { - let d = std::env::temp_dir().join(format!("p5a-zip-retry-{}", std::process::id())); + let d = crate::test_tmp::temp_path(format!("p5a-zip-retry-{}", std::process::id())); let _ = std::fs::remove_dir_all(&d); std::fs::create_dir_all(d.join("share/G")).unwrap(); for i in 0..3u8 { @@ -2043,7 +2043,7 @@ mod tests { bps: u64, damage: Option, ) -> (u64, u64, u64) { - let d = std::env::temp_dir().join(format!("p5a-zip-{tag}-{}", std::process::id())); + let d = crate::test_tmp::temp_path(format!("p5a-zip-{tag}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&d); std::fs::create_dir_all(d.join("share/G")).unwrap(); let mut want = Vec::new(); @@ -2252,7 +2252,7 @@ mod tests { // delivered, in (file, offset) order, with no gaps. #[test] fn a_fresh_ordered_job_delivers_every_byte_in_order() { - let d = std::env::temp_dir().join(format!("p5a-ord-{}", std::process::id())); + let d = crate::test_tmp::temp_path(format!("p5a-ord-{}", std::process::id())); let _ = std::fs::remove_dir_all(&d); std::fs::create_dir_all(d.join("share/G")).unwrap(); let sizes = [3 << 20, 100, (2 << 20) + 17, 1 << 20, 5]; @@ -2309,7 +2309,7 @@ mod tests { #[test] fn a_rewrite_from_offset_zero_is_a_restart_and_a_gap_is_not() { - let d = std::env::temp_dir().join(format!("p5a-zip-sink-rw-{}", std::process::id())); + let d = crate::test_tmp::temp_path(format!("p5a-zip-sink-rw-{}", std::process::id())); let _ = std::fs::remove_dir_all(&d); std::fs::create_dir_all(&d).unwrap(); let mut m = files(&["a", "b"]); @@ -2331,7 +2331,7 @@ mod tests { #[test] fn a_recoverable_local_failure_keeps_its_journal_and_staging() { - let d = std::env::temp_dir().join(format!("p5a-keep-{}", std::process::id())); + let d = crate::test_tmp::temp_path(format!("p5a-keep-{}", std::process::id())); let _ = std::fs::remove_dir_all(&d); let (job, part) = (d.join("job"), d.join("Game.ava-part")); let fill = || { @@ -2400,7 +2400,7 @@ mod tests { #[test] fn a_stale_staging_path_is_cleared_only_for_a_fresh_journal() { - let d = std::env::temp_dir().join(format!("p5a-stale-{}", std::process::id())); + let d = crate::test_tmp::temp_path(format!("p5a-stale-{}", std::process::id())); let _ = std::fs::remove_dir_all(&d); std::fs::create_dir_all(d.join("j")).unwrap(); assert!(journal_is_empty(&d.join("missing"))); @@ -2421,7 +2421,7 @@ mod tests { /// finish must take the folder that is there as its own. #[test] fn a_retry_after_the_folder_was_renamed_into_place_finishes() { - let d = std::env::temp_dir().join(format!("p5a-landed-{}", std::process::id())); + let d = crate::test_tmp::temp_path(format!("p5a-landed-{}", std::process::id())); let _ = std::fs::remove_dir_all(&d); std::fs::create_dir_all(&d).unwrap(); let target = d.join("Game"); @@ -2465,7 +2465,7 @@ mod tests { /// part file). Into a new folder (staged whole, no part names) the same tree is fine. #[test] fn a_tree_holding_x_and_x_ava_part_is_refused_into_an_existing_folder_only() { - let d = std::env::temp_dir().join(format!("p5a-partname-{}", std::process::id())); + let d = crate::test_tmp::temp_path(format!("p5a-partname-{}", std::process::id())); let _ = std::fs::remove_dir_all(&d); let (job, target) = (d.join("job"), d.join("Game")); std::fs::create_dir_all(&job).unwrap(); @@ -2569,7 +2569,7 @@ mod tests { } // And through the real clean-up: only the safe file's part goes. - let d = std::env::temp_dir().join(format!("p5a-hostile-{}", std::process::id())); + let d = crate::test_tmp::temp_path(format!("p5a-hostile-{}", std::process::id())); let _ = std::fs::remove_dir_all(&d); let (job, target) = (d.join("job"), d.join("in").join("Game")); std::fs::create_dir_all(&job).unwrap(); @@ -2594,7 +2594,7 @@ mod tests { #[test] fn a_final_failure_into_an_existing_folder_removes_its_in_place_part_files_only() { - let d = std::env::temp_dir().join(format!("p5a-inplace-{}", std::process::id())); + let d = crate::test_tmp::temp_path(format!("p5a-inplace-{}", std::process::id())); let _ = std::fs::remove_dir_all(&d); let (job, target) = (d.join("job"), d.join("Game")); std::fs::create_dir_all(&job).unwrap(); diff --git a/engine/crates/ps5upload-ava1/src/lib.rs b/engine/crates/ps5upload-ava1/src/lib.rs index 6543179df..cdd59a34d 100644 --- a/engine/crates/ps5upload-ava1/src/lib.rs +++ b/engine/crates/ps5upload-ava1/src/lib.rs @@ -91,3 +91,8 @@ mod step_tests { assert_eq!(super::step(0, 4096), 0); } } + +// Test scratch paths removed when the test process exits (engine/test-support/test_tmp.rs). +#[cfg(test)] +#[path = "../../../test-support/test_tmp.rs"] +mod test_tmp; diff --git a/engine/crates/ps5upload-ava1/src/pool.rs b/engine/crates/ps5upload-ava1/src/pool.rs index 5a7958154..610f52dd1 100644 --- a/engine/crates/ps5upload-ava1/src/pool.rs +++ b/engine/crates/ps5upload-ava1/src/pool.rs @@ -1290,7 +1290,7 @@ mod identity_summary_tests { #[test] fn the_startup_summary_names_the_key_and_the_paired_count() { - let d = std::env::temp_dir().join(format!("p5a-summary-{}", std::process::id())); + let d = crate::test_tmp::temp_path(format!("p5a-summary-{}", std::process::id())); let _ = std::fs::remove_dir_all(&d); let p = Pool::new(d.join("ava")); assert_eq!(p.identity_prefix().len(), 8); @@ -1337,7 +1337,7 @@ mod peek_tests { #[tokio::test] async fn a_peek_reads_the_key_and_name_and_never_gets_admitted() { - let d = std::env::temp_dir().join(format!("p5a-peek-{}", std::process::id())); + let d = crate::test_tmp::temp_path(format!("p5a-peek-{}", std::process::id())); let _ = std::fs::remove_dir_all(&d); let pool = Pool::new(d.join("ava")); let console = Arc::new(Identity::generate().unwrap()); @@ -1415,7 +1415,7 @@ mod gc_tests { use super::*; fn tmp(tag: &str) -> PathBuf { - let d = std::env::temp_dir().join(format!("ps5u-poolgc-{tag}-{}", std::process::id())); + let d = crate::test_tmp::temp_path(format!("ps5u-poolgc-{tag}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&d); std::fs::create_dir_all(&d).unwrap(); d @@ -1484,7 +1484,7 @@ mod not_paired_ttl_tests { /// is remembered for the longer not-paired time, not the plain refusal time. #[test] fn a_not_paired_refusal_is_remembered_for_its_own_time() { - let d = std::env::temp_dir().join(format!("p5a-np-{}", std::process::id())); + let d = crate::test_tmp::temp_path(format!("p5a-np-{}", std::process::id())); let pool = Pool::new(d.join("ava")) .with_refusal_ttl(Duration::from_millis(1)) .with_not_paired_ttl(Duration::from_secs(60)); diff --git a/engine/crates/ps5upload-ava1/src/relay.rs b/engine/crates/ps5upload-ava1/src/relay.rs index 23c68ac06..497c24258 100644 --- a/engine/crates/ps5upload-ava1/src/relay.rs +++ b/engine/crates/ps5upload-ava1/src/relay.rs @@ -1082,7 +1082,7 @@ mod tests { file("fresh_large", size), ], }; - let dir = std::env::temp_dir().join(format!("relay-skip-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("relay-skip-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); // The destination: file 0 fully durable, file 1 groups 0 and 1 durable diff --git a/engine/crates/ps5upload-ava1/src/source.rs b/engine/crates/ps5upload-ava1/src/source.rs index fe0661bac..915ba9322 100644 --- a/engine/crates/ps5upload-ava1/src/source.rs +++ b/engine/crates/ps5upload-ava1/src/source.rs @@ -245,7 +245,7 @@ mod tests { #[test] fn a_renamed_module_is_listed_under_its_new_name_and_read_from_the_old_file() { - let d = std::env::temp_dir().join(format!("p5a-renamed-{}", std::process::id())); + let d = crate::test_tmp::temp_path(format!("p5a-renamed-{}", std::process::id())); let _ = std::fs::remove_dir_all(&d); std::fs::create_dir_all(d.join("Media/Modules")).unwrap(); std::fs::write(d.join("eboot.bin"), b"eboot").unwrap(); diff --git a/engine/crates/ps5upload-ava1/src/upload.rs b/engine/crates/ps5upload-ava1/src/upload.rs index 8d656c5ca..658d1d82f 100644 --- a/engine/crates/ps5upload-ava1/src/upload.rs +++ b/engine/crates/ps5upload-ava1/src/upload.rs @@ -1857,7 +1857,7 @@ mod list_destination_tests { #[test] fn a_zip_that_cannot_be_read_is_retryable_but_a_bad_one_is_unsupported() { - let d = std::env::temp_dir().join(format!("p5a-zip-open-{}", std::process::id())); + let d = crate::test_tmp::temp_path(format!("p5a-zip-open-{}", std::process::id())); std::fs::create_dir_all(&d).unwrap(); let cfg = ps5upload_core::transfer::TransferConfig::new("c"); let pool = crate::pool::Pool::unavailable(); @@ -2159,7 +2159,7 @@ mod tests { #[test] fn no_identity_is_terminal_immediately() { - let d = std::env::temp_dir().join(format!("gate-noid-{}", std::process::id())); + let d = crate::test_tmp::temp_path(format!("gate-noid-{}", std::process::id())); let _ = std::fs::remove_dir_all(&d); std::fs::create_dir_all(d.join("identity")).unwrap(); let pool = Pool::new(d.clone()); diff --git a/engine/crates/ps5upload-ava1/src/zip_source.rs b/engine/crates/ps5upload-ava1/src/zip_source.rs index 051ef1883..2bcf94f3c 100644 --- a/engine/crates/ps5upload-ava1/src/zip_source.rs +++ b/engine/crates/ps5upload-ava1/src/zip_source.rs @@ -510,7 +510,7 @@ mod tests { /// A stored archive of `a` then `b`; returns its path and where `a`'s data starts. fn stored_zip(tag: &str, a: &[u8], b: &[u8]) -> (PathBuf, u64) { - let p = std::env::temp_dir().join(format!("p5a-zs-{tag}-{}.zip", std::process::id())); + let p = crate::test_tmp::temp_path(format!("p5a-zs-{tag}-{}.zip", std::process::id())); let mut z = zip::ZipWriter::new(std::fs::File::create(&p).unwrap()); let o = zip::write::SimpleFileOptions::default() .compression_method(zip::CompressionMethod::Stored); @@ -529,7 +529,7 @@ mod tests { /// preview normalises (`./sub/b.bin`) is sent the way the preview lists it. #[test] fn entry_names_follow_the_preview_rule() { - let p = std::env::temp_dir().join(format!("p5a-zs-names-{}.zip", std::process::id())); + let p = crate::test_tmp::temp_path(format!("p5a-zs-names-{}.zip", std::process::id())); let o = zip::write::SimpleFileOptions::default() .compression_method(zip::CompressionMethod::Stored); let mut z = zip::ZipWriter::new(std::fs::File::create(&p).unwrap()); diff --git a/engine/crates/ps5upload-ava1/src/zip_stored.rs b/engine/crates/ps5upload-ava1/src/zip_stored.rs index 11eaf5e63..f1441c016 100644 --- a/engine/crates/ps5upload-ava1/src/zip_stored.rs +++ b/engine/crates/ps5upload-ava1/src/zip_stored.rs @@ -793,7 +793,7 @@ mod tests { } fn dir(tag: &str) -> PathBuf { - let d = std::env::temp_dir().join(format!("p5a-zs-{tag}-{}", std::process::id())); + let d = crate::test_tmp::temp_path(format!("p5a-zs-{tag}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&d); std::fs::create_dir_all(&d).unwrap(); d diff --git a/engine/crates/ps5upload-ava1/tests/adapters.rs b/engine/crates/ps5upload-ava1/tests/adapters.rs index 6bdba8d30..ba5f457f2 100644 --- a/engine/crates/ps5upload-ava1/tests/adapters.rs +++ b/engine/crates/ps5upload-ava1/tests/adapters.rs @@ -23,7 +23,7 @@ use ps5upload_ava1::{block_on, Pool, PostCommitError, PostCommitKind}; use ps5upload_core::transfer::{FileListEntry, TransferConfig}; fn temp_dir(tag: &str) -> PathBuf { - let d = std::env::temp_dir().join(format!("p5a-{tag}-{}", std::process::id())); + let d = crate::test_tmp::temp_path(format!("p5a-{tag}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&d); d } @@ -1058,3 +1058,7 @@ async fn periodic_kills_never_strand_an_upload() { println!("periodic kills: attempts = {}", pool.attempts()); drop(proxy); } + +// Test scratch paths removed when the test process exits (engine/test-support/test_tmp.rs). +#[path = "../../../test-support/test_tmp.rs"] +mod test_tmp; diff --git a/engine/crates/ps5upload-ava1/tests/common/mod.rs b/engine/crates/ps5upload-ava1/tests/common/mod.rs index 6cd34fcf7..3922d6e52 100644 --- a/engine/crates/ps5upload-ava1/tests/common/mod.rs +++ b/engine/crates/ps5upload-ava1/tests/common/mod.rs @@ -11,7 +11,7 @@ use ava1::wire::Message; use ps5upload_ava1::gen; pub fn temp(tag: &str) -> PathBuf { - let d = std::env::temp_dir().join(format!("ava1-relay-{tag}-{}", std::process::id())); + let d = test_tmp::temp_path(format!("ava1-relay-{tag}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&d); std::fs::create_dir_all(&d).unwrap(); d @@ -150,3 +150,7 @@ pub fn assert_pattern(path: &Path, seed: u8, size: u64) { } assert_eq!(got.finalize(), want.finalize(), "{path:?} content differs"); } + +// Test scratch paths removed when the test process exits (engine/test-support/test_tmp.rs). +#[path = "../../../../test-support/test_tmp.rs"] +mod test_tmp; diff --git a/engine/crates/ps5upload-ava1/tests/download_copy.rs b/engine/crates/ps5upload-ava1/tests/download_copy.rs index b855fe434..02b52be95 100644 --- a/engine/crates/ps5upload-ava1/tests/download_copy.rs +++ b/engine/crates/ps5upload-ava1/tests/download_copy.rs @@ -28,7 +28,7 @@ use ps5upload_ava1::Pool; use ps5upload_core::download::DownloadKind; fn temp(tag: &str) -> PathBuf { - let d = std::env::temp_dir().join(format!("p5a-dl-{tag}-{}", std::process::id())); + let d = crate::test_tmp::temp_path(format!("p5a-dl-{tag}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&d); std::fs::create_dir_all(&d).unwrap(); d @@ -1538,3 +1538,7 @@ async fn a_confirmed_cancel_cleans_up_only_after_the_console_accepted_this_copy( ); assert_eq!(*rec.0.lock().unwrap(), [("/data/b".to_string(), true)]); } + +// Test scratch paths removed when the test process exits (engine/test-support/test_tmp.rs). +#[path = "../../../test-support/test_tmp.rs"] +mod test_tmp; diff --git a/engine/crates/ps5upload-ava1/tests/download_fds.rs b/engine/crates/ps5upload-ava1/tests/download_fds.rs index b153a932c..442546918 100644 --- a/engine/crates/ps5upload-ava1/tests/download_fds.rs +++ b/engine/crates/ps5upload-ava1/tests/download_fds.rs @@ -19,7 +19,7 @@ use ps5upload_ava1::Pool; use ps5upload_core::download::DownloadKind; fn temp(tag: &str) -> PathBuf { - let d = std::env::temp_dir().join(format!("p5a-fds-{tag}-{}", std::process::id())); + let d = crate::test_tmp::temp_path(format!("p5a-fds-{tag}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&d); std::fs::create_dir_all(&d).unwrap(); d @@ -179,3 +179,7 @@ async fn scenario(tag: &str, log_small: &str, hog: bool) { } assert_eq!(seen, n); } + +// Test scratch paths removed when the test process exits (engine/test-support/test_tmp.rs). +#[path = "../../../test-support/test_tmp.rs"] +mod test_tmp; diff --git a/engine/crates/ps5upload-ava1/tests/fast_status.rs b/engine/crates/ps5upload-ava1/tests/fast_status.rs index b836c3277..382a411a5 100644 --- a/engine/crates/ps5upload-ava1/tests/fast_status.rs +++ b/engine/crates/ps5upload-ava1/tests/fast_status.rs @@ -24,7 +24,7 @@ use tokio::io::{AsyncReadExt, AsyncWriteExt}; const ROUTE_TIMEOUT: Duration = ps5upload_ava1::mgmt::STATUS_TIMEOUT; fn temp(tag: &str) -> PathBuf { - let d = std::env::temp_dir().join(format!("p5a-fast-{tag}-{}", std::process::id())); + let d = crate::test_tmp::temp_path(format!("p5a-fast-{tag}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&d); std::fs::create_dir_all(&d).unwrap(); d @@ -314,3 +314,7 @@ async fn a_busy_helper_is_slow_not_gone_and_keeps_its_session() { "the busy console's session was kept" ); } + +// Test scratch paths removed when the test process exits (engine/test-support/test_tmp.rs). +#[path = "../../../test-support/test_tmp.rs"] +mod test_tmp; diff --git a/engine/crates/ps5upload-ava1/tests/kept_names.rs b/engine/crates/ps5upload-ava1/tests/kept_names.rs index 9ab16ae5e..99cde51d5 100644 --- a/engine/crates/ps5upload-ava1/tests/kept_names.rs +++ b/engine/crates/ps5upload-ava1/tests/kept_names.rs @@ -22,7 +22,7 @@ use ps5upload_core::download::DownloadKind; use ps5upload_core::transfer::{host_unsafe_component, TransferConfig}; fn temp(tag: &str) -> PathBuf { - let d = std::env::temp_dir().join(format!("p5a-kept-{tag}-{}", std::process::id())); + let d = crate::test_tmp::temp_path(format!("p5a-kept-{tag}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&d); std::fs::create_dir_all(&d).unwrap(); d @@ -280,3 +280,7 @@ async fn a_kept_name_the_app_did_not_make_is_refused() { assert!(names_of(&d.join("share")).is_empty(), "{bad:?}"); } } + +// Test scratch paths removed when the test process exits (engine/test-support/test_tmp.rs). +#[path = "../../../test-support/test_tmp.rs"] +mod test_tmp; diff --git a/engine/crates/ps5upload-ava1/tests/mgmt.rs b/engine/crates/ps5upload-ava1/tests/mgmt.rs index 2a03dfd37..a364e7bb7 100644 --- a/engine/crates/ps5upload-ava1/tests/mgmt.rs +++ b/engine/crates/ps5upload-ava1/tests/mgmt.rs @@ -27,7 +27,7 @@ const JOB_CANCEL: ps5upload_core::mgmt::Method = ps5upload_core::mgmt::Method { }; fn temp(tag: &str) -> PathBuf { - let d = std::env::temp_dir().join(format!("p5a-mgmt-{tag}-{}", std::process::id())); + let d = crate::test_tmp::temp_path(format!("p5a-mgmt-{tag}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&d); std::fs::create_dir_all(&d).unwrap(); d @@ -1155,3 +1155,7 @@ async fn a_call_longer_than_the_session_default_gets_its_callers_bound() { .unwrap(); assert_eq!(r.unwrap(), b"done"); } + +// Test scratch paths removed when the test process exits (engine/test-support/test_tmp.rs). +#[path = "../../../test-support/test_tmp.rs"] +mod test_tmp; diff --git a/engine/crates/ps5upload-ava1/tests/mgmt_job.rs b/engine/crates/ps5upload-ava1/tests/mgmt_job.rs index a5a0bc887..715f4babf 100644 --- a/engine/crates/ps5upload-ava1/tests/mgmt_job.rs +++ b/engine/crates/ps5upload-ava1/tests/mgmt_job.rs @@ -22,7 +22,7 @@ use ps5upload_core::mgmt::{self, ops, JobCall, MgmtError, MgmtTransport}; const T: Duration = Duration::from_secs(10); fn temp(tag: &str) -> PathBuf { - let d = std::env::temp_dir().join(format!("p5a-mgmtjob-{tag}-{}", std::process::id())); + let d = crate::test_tmp::temp_path(format!("p5a-mgmtjob-{tag}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&d); std::fs::create_dir_all(&d).unwrap(); d @@ -850,3 +850,7 @@ async fn a_crc32_the_console_could_not_run_is_an_err_field_not_an_error() { (None, Some("crc32_open_failed")) ); } + +// Test scratch paths removed when the test process exits (engine/test-support/test_tmp.rs). +#[path = "../../../test-support/test_tmp.rs"] +mod test_tmp; diff --git a/engine/crates/ps5upload-ava1/tests/mgmt_t6.rs b/engine/crates/ps5upload-ava1/tests/mgmt_t6.rs index 8718068ed..fd4450d00 100644 --- a/engine/crates/ps5upload-ava1/tests/mgmt_t6.rs +++ b/engine/crates/ps5upload-ava1/tests/mgmt_t6.rs @@ -21,7 +21,7 @@ use ps5upload_core::mgmt::{self, m, MgmtError, MgmtTransport}; const T: Duration = Duration::from_secs(20); fn temp(tag: &str) -> PathBuf { - let d = std::env::temp_dir().join(format!("p5a-t6-{tag}-{}", std::process::id())); + let d = crate::test_tmp::temp_path(format!("p5a-t6-{tag}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&d); std::fs::create_dir_all(&d).unwrap(); d @@ -457,3 +457,7 @@ async fn a_refused_kill_over_ava1_reads_like_the_legacy_one() { "PROCESS_KILL failed for pid 99999: No such process" ); } + +// Test scratch paths removed when the test process exits (engine/test-support/test_tmp.rs). +#[path = "../../../test-support/test_tmp.rs"] +mod test_tmp; diff --git a/engine/crates/ps5upload-ava1/tests/mgmt_t7.rs b/engine/crates/ps5upload-ava1/tests/mgmt_t7.rs index 1fc6f3a6b..d80ae9c3b 100644 --- a/engine/crates/ps5upload-ava1/tests/mgmt_t7.rs +++ b/engine/crates/ps5upload-ava1/tests/mgmt_t7.rs @@ -26,7 +26,7 @@ use ps5upload_core::{ }; fn temp(tag: &str) -> PathBuf { - let d = std::env::temp_dir().join(format!("p5a-t7-{tag}-{}", std::process::id())); + let d = crate::test_tmp::temp_path(format!("p5a-t7-{tag}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&d); std::fs::create_dir_all(&d).unwrap(); d @@ -653,3 +653,7 @@ fn no_core_module_of_this_group_dials_a_console_directly() { assert!(!d[i..i + end].contains("TcpStream::connect"), "{f}"); } } + +// Test scratch paths removed when the test process exits (engine/test-support/test_tmp.rs). +#[path = "../../../test-support/test_tmp.rs"] +mod test_tmp; diff --git a/engine/crates/ps5upload-ava1/tests/sevenz.rs b/engine/crates/ps5upload-ava1/tests/sevenz.rs index 50c906061..9cfa3eae1 100644 --- a/engine/crates/ps5upload-ava1/tests/sevenz.rs +++ b/engine/crates/ps5upload-ava1/tests/sevenz.rs @@ -28,7 +28,7 @@ use sevenz_rust2::{ }; fn temp_dir(tag: &str) -> PathBuf { - let d = std::env::temp_dir().join(format!("p5z-{tag}-{}", std::process::id())); + let d = crate::test_tmp::temp_path(format!("p5z-{tag}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&d); std::fs::create_dir_all(&d).unwrap(); d @@ -1025,3 +1025,7 @@ fn an_entrys_own_mtime_is_carried_into_the_manifest() { assert_eq!(t("dated"), 1_709_209_840); assert_eq!(t("undated"), 0); } + +// Test scratch paths removed when the test process exits (engine/test-support/test_tmp.rs). +#[path = "../../../test-support/test_tmp.rs"] +mod test_tmp; diff --git a/engine/crates/ps5upload-ava1/tests/shared_identity.rs b/engine/crates/ps5upload-ava1/tests/shared_identity.rs index 23dffc5c5..51af6b297 100644 --- a/engine/crates/ps5upload-ava1/tests/shared_identity.rs +++ b/engine/crates/ps5upload-ava1/tests/shared_identity.rs @@ -10,7 +10,7 @@ use ava1::server::{self, ServerCtx}; use ps5upload_ava1::Pool; fn temp(tag: &str) -> PathBuf { - let d = std::env::temp_dir().join(format!("p5a-shared-{tag}-{}", std::process::id())); + let d = crate::test_tmp::temp_path(format!("p5a-shared-{tag}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&d); std::fs::create_dir_all(&d).unwrap(); d @@ -138,3 +138,7 @@ async fn the_session_that_failed_is_forgotten_and_a_stale_cached_one_is_too() { assert!(!Arc::ptr_eq(&s2, &s3)); assert!(!s3.is_closed()); } + +// Test scratch paths removed when the test process exits (engine/test-support/test_tmp.rs). +#[path = "../../../test-support/test_tmp.rs"] +mod test_tmp; diff --git a/engine/crates/ps5upload-ava1/tests/tar.rs b/engine/crates/ps5upload-ava1/tests/tar.rs index 7d02c2e1d..0441c6545 100644 --- a/engine/crates/ps5upload-ava1/tests/tar.rs +++ b/engine/crates/ps5upload-ava1/tests/tar.rs @@ -26,7 +26,7 @@ use ps5upload_core::tar_archive::TarWatch; use ps5upload_core::transfer::TransferConfig; fn temp_dir(tag: &str) -> PathBuf { - let d = std::env::temp_dir().join(format!("p5t-{tag}-{}", std::process::id())); + let d = crate::test_tmp::temp_path(format!("p5t-{tag}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&d); std::fs::create_dir_all(&d).unwrap(); d @@ -550,3 +550,7 @@ async fn zip_entries_compressed_with_zstd_upload_and_are_checked() { .unwrap_err(); assert_eq!(failure(&e).reason, "ava1_zip_corrupt", "{e:#}"); } + +// Test scratch paths removed when the test process exits (engine/test-support/test_tmp.rs). +#[path = "../../../test-support/test_tmp.rs"] +mod test_tmp; diff --git a/engine/crates/ps5upload-convert-core/src/archive_tree.rs b/engine/crates/ps5upload-convert-core/src/archive_tree.rs index 35505979a..ed635ce08 100644 --- a/engine/crates/ps5upload-convert-core/src/archive_tree.rs +++ b/engine/crates/ps5upload-convert-core/src/archive_tree.rs @@ -341,7 +341,7 @@ mod tests { fn listing_of(paths: &[&str]) -> Listing { // A stored zip of empty-ish files, listed the real way. use std::io::Write; - let dir = std::env::temp_dir().join(format!( + let dir = crate::test_tmp::temp_path(format!( "ps5u-archive-tree-{}-{}", std::process::id(), paths.len() diff --git a/engine/crates/ps5upload-convert-core/src/folder_build.rs b/engine/crates/ps5upload-convert-core/src/folder_build.rs index 0a16a3fda..e86dcdd56 100644 --- a/engine/crates/ps5upload-convert-core/src/folder_build.rs +++ b/engine/crates/ps5upload-convert-core/src/folder_build.rs @@ -946,7 +946,7 @@ mod tests { fn scratch(tag: &str) -> PathBuf { let root = - std::env::temp_dir().join(format!("ps5upload-fold-{tag}-{}", std::process::id())); + crate::test_tmp::temp_path(format!("ps5upload-fold-{tag}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&root); std::fs::create_dir_all(&root).unwrap(); root diff --git a/engine/crates/ps5upload-convert-core/src/image_build.rs b/engine/crates/ps5upload-convert-core/src/image_build.rs index 9b1d80903..09f46c588 100644 --- a/engine/crates/ps5upload-convert-core/src/image_build.rs +++ b/engine/crates/ps5upload-convert-core/src/image_build.rs @@ -1796,7 +1796,7 @@ mod tests { /// Every format, plain and compressed, writes a folder that reads back hash for hash. #[test] fn every_format_round_trips_plain_and_compressed() { - let root = std::env::temp_dir().join(format!("ps5upload-imgb-{}", std::process::id())); + let root = crate::test_tmp::temp_path(format!("ps5upload-imgb-{}", std::process::id())); let _ = std::fs::remove_dir_all(&root); let src = game(&root); for format in [ImageFormat::Exfat, ImageFormat::Ffpkg, ImageFormat::Ffpfs] { @@ -1839,7 +1839,8 @@ mod tests { /// the build fails and leaves it, and its own partial file, alone and gone. #[test] fn an_output_that_appears_while_written_is_not_replaced() { - let root = std::env::temp_dir().join(format!("ps5upload-imgb-race-{}", std::process::id())); + let root = + crate::test_tmp::temp_path(format!("ps5upload-imgb-race-{}", std::process::id())); let _ = std::fs::remove_dir_all(&root); let src = game(&root); let out = root.join("g.exfat"); @@ -1872,7 +1873,7 @@ mod tests { #[test] fn an_lz4_packed_image_reads_as_the_game_it_was() { use ps5upload_fpkg::ampr_pack::image::{Lz4Unpacked, Unpacking}; - let root = std::env::temp_dir().join(format!("ps5upload-imglz4-{}", std::process::id())); + let root = crate::test_tmp::temp_path(format!("ps5upload-imglz4-{}", std::process::id())); let _ = std::fs::remove_dir_all(&root); let src = ampr_game(&root); let out = root.join("PPSA99999-app.exfat"); @@ -1939,7 +1940,7 @@ mod tests { /// already on disk, and the image comes out the same bytes. Any other game starts over. #[test] fn a_plain_exfat_goes_on_from_a_checkpoint() { - let root = std::env::temp_dir().join(format!("ps5upload-imgres-{}", std::process::id())); + let root = crate::test_tmp::temp_path(format!("ps5upload-imgres-{}", std::process::id())); let _ = std::fs::remove_dir_all(&root); let src = root.join("game"); std::fs::create_dir_all(src.join("sce_sys")).unwrap(); @@ -2115,7 +2116,7 @@ mod tests { /// is byte for byte the one an uninterrupted build makes. #[test] fn every_format_goes_on_from_a_crash_byte_for_byte() { - let root = std::env::temp_dir().join(format!("ps5upload-imgcrash-{}", std::process::id())); + let root = crate::test_tmp::temp_path(format!("ps5upload-imgcrash-{}", std::process::id())); let _ = std::fs::remove_dir_all(&root); let src = noisy_game(&root); for (format, compress) in EVERY_KIND { @@ -2168,7 +2169,7 @@ mod tests { /// the new source's, byte for byte. #[test] fn a_changed_source_refuses_the_resume_and_rebuilds() { - let root = std::env::temp_dir().join(format!("ps5upload-imgchg-{}", std::process::id())); + let root = crate::test_tmp::temp_path(format!("ps5upload-imgchg-{}", std::process::id())); let _ = std::fs::remove_dir_all(&root); for (format, compress) in EVERY_KIND { let what = format!("{format:?} compress={compress}"); @@ -2215,7 +2216,7 @@ mod tests { /// nothing, one past it leaves a hole, and going back is refused. #[test] fn the_checkpoint_writer_seeks_forward_over_what_is_on_disk() { - let root = std::env::temp_dir().join(format!("ps5upload-imgcks-{}", std::process::id())); + let root = crate::test_tmp::temp_path(format!("ps5upload-imgcks-{}", std::process::id())); let _ = std::fs::remove_dir_all(&root); std::fs::create_dir_all(&root).unwrap(); let path = root.join("x.partial"); @@ -2250,7 +2251,7 @@ mod tests { /// no checkpoint behind it gets a new one. #[test] fn an_index_stamp_lasts_only_as_long_as_its_checkpoint() { - let root = std::env::temp_dir().join(format!("ps5upload-imgstamp-{}", std::process::id())); + let root = crate::test_tmp::temp_path(format!("ps5upload-imgstamp-{}", std::process::id())); let _ = std::fs::remove_dir_all(&root); std::fs::create_dir_all(&root).unwrap(); let partial = root.join("x.exfat.partial"); @@ -2267,7 +2268,7 @@ mod tests { /// The writer drops what is on disk already, whichever way the writes are cut. #[test] fn the_checkpoint_writer_skips_then_writes_and_records() { - let root = std::env::temp_dir().join(format!("ps5upload-imgckw-{}", std::process::id())); + let root = crate::test_tmp::temp_path(format!("ps5upload-imgckw-{}", std::process::id())); let _ = std::fs::remove_dir_all(&root); std::fs::create_dir_all(&root).unwrap(); let path = root.join("x.partial"); @@ -2306,7 +2307,7 @@ mod tests { /// (Alembic's console test: without it the game mounts and then won't start). #[test] fn a_ps4_game_gets_its_param_json_in_every_format() { - let root = std::env::temp_dir().join(format!("ps5upload-imgb-ps4-{}", std::process::id())); + let root = crate::test_tmp::temp_path(format!("ps5upload-imgb-ps4-{}", std::process::id())); let _ = std::fs::remove_dir_all(&root); let src = root.join("CUSA00000-app"); std::fs::create_dir_all(src.join("sce_sys")).unwrap(); @@ -2359,7 +2360,7 @@ mod tests { /// and a cancel that lands after the image was finished does not turn it into a failure. #[test] fn another_builds_partial_is_left_alone_and_a_late_cancel_changes_nothing() { - let root = std::env::temp_dir().join(format!("ps5upload-imgp-{}", std::process::id())); + let root = crate::test_tmp::temp_path(format!("ps5upload-imgp-{}", std::process::id())); let _ = std::fs::remove_dir_all(&root); let src = game(&root); let out = root.join("x.exfat"); @@ -2401,7 +2402,7 @@ mod tests { /// A file that is not read front to back while the image is written is still checked. #[test] fn a_file_read_out_of_order_is_hashed_afterwards() { - let root = std::env::temp_dir().join(format!("ps5upload-imgh-{}", std::process::id())); + let root = crate::test_tmp::temp_path(format!("ps5upload-imgh-{}", std::process::id())); let _ = std::fs::remove_dir_all(&root); let src = game(&root); let mut tree = FolderSource::open(&src).unwrap(); @@ -2437,7 +2438,7 @@ mod tests { #[test] fn a_fast_verify_catches_what_it_samples_and_a_full_one_everything() { const MIB: usize = 1 << 20; - let root = std::env::temp_dir().join(format!("ps5upload-imgf-{}", std::process::id())); + let root = crate::test_tmp::temp_path(format!("ps5upload-imgf-{}", std::process::id())); let _ = std::fs::remove_dir_all(&root); let src = game(&root); // 48 MiB in six slices, each stamped with a marker the image can be searched for. @@ -2588,7 +2589,7 @@ mod tests { /// A PFS image holds ASCII names only; the build refuses before writing anything. #[test] fn a_name_pfs_cannot_hold_is_refused_before_writing() { - let root = std::env::temp_dir().join(format!("ps5upload-imgn-{}", std::process::id())); + let root = crate::test_tmp::temp_path(format!("ps5upload-imgn-{}", std::process::id())); let _ = std::fs::remove_dir_all(&root); let src = game(&root); std::fs::write(src.join("données.bin"), b"x").unwrap(); @@ -2640,7 +2641,7 @@ mod tests { /// descriptor file ../../../griffin/griffin.uproject"). #[test] fn an_unreal_title_packs_only_its_iostore_containers() { - let root = std::env::temp_dir().join(format!("ps5upload-imgu-{}", std::process::id())); + let root = crate::test_tmp::temp_path(format!("ps5upload-imgu-{}", std::process::id())); let _ = std::fs::remove_dir_all(&root); let src = ampr_game(&root); let paks = src.join("griffin/Content/Paks"); @@ -2717,7 +2718,7 @@ mod tests { #[test] fn an_lz4_packed_exfat_reads_back_to_the_source() { use ps5upload_fpkg::ampr_pack::Reader; - let root = std::env::temp_dir().join(format!("ps5upload-imgl-{}", std::process::id())); + let root = crate::test_tmp::temp_path(format!("ps5upload-imgl-{}", std::process::id())); let _ = std::fs::remove_dir_all(&root); let src = ampr_game(&root); let out = root.join("PPSA99999-app.exfat"); @@ -2811,7 +2812,7 @@ mod tests { /// (#449), never the dump's stale one. #[test] fn a_plain_image_regenerates_a_stale_ampr_index() { - let root = std::env::temp_dir().join(format!("ps5upload-imgi-{}", std::process::id())); + let root = crate::test_tmp::temp_path(format!("ps5upload-imgi-{}", std::process::id())); let _ = std::fs::remove_dir_all(&root); let src = ampr_game(&root); std::fs::write(src.join("ampr_emu.index"), b"AMPRIDX3 stale").unwrap(); @@ -2852,7 +2853,7 @@ mod tests { /// Packing is refused for a game whose ampr_emu can't serve packs, and leaves nothing behind. #[test] fn lz4_packs_are_refused_for_a_game_that_cannot_read_them() { - let root = std::env::temp_dir().join(format!("ps5upload-imgr-{}", std::process::id())); + let root = crate::test_tmp::temp_path(format!("ps5upload-imgr-{}", std::process::id())); let _ = std::fs::remove_dir_all(&root); let src = ampr_game(&root); let exfat = root.join("x.exfat"); diff --git a/engine/crates/ps5upload-convert-core/src/lib.rs b/engine/crates/ps5upload-convert-core/src/lib.rs index ed3494c67..df1215d84 100644 --- a/engine/crates/ps5upload-convert-core/src/lib.rs +++ b/engine/crates/ps5upload-convert-core/src/lib.rs @@ -31,3 +31,8 @@ pub mod safe_write; pub mod unpack_packs; pub mod writing; pub mod zstd_packs; + +// Test scratch paths removed when the test process exits (engine/test-support/test_tmp.rs). +#[cfg(test)] +#[path = "../../../test-support/test_tmp.rs"] +mod test_tmp; diff --git a/engine/crates/ps5upload-convert-core/src/lz4_packs.rs b/engine/crates/ps5upload-convert-core/src/lz4_packs.rs index 5fe18a881..cf4b5208c 100644 --- a/engine/crates/ps5upload-convert-core/src/lz4_packs.rs +++ b/engine/crates/ps5upload-convert-core/src/lz4_packs.rs @@ -403,7 +403,7 @@ mod tests { /// filesystem (and container) and then through the packs as the game it was. #[test] fn lz4_packs_go_into_every_image_plain_and_compressed() { - let root = std::env::temp_dir().join(format!("ps5upload-lz4all-{}", std::process::id())); + let root = crate::test_tmp::temp_path(format!("ps5upload-lz4all-{}", std::process::id())); let _ = std::fs::remove_dir_all(&root); let src = ampr_game(&root); for format in [ImageFormat::Exfat, ImageFormat::Ffpkg, ImageFormat::Ffpfs] { @@ -450,7 +450,7 @@ mod tests { /// server that starts over in another engine process go on from what is already there. #[test] fn packing_again_gives_the_same_bytes() { - let root = std::env::temp_dir().join(format!("ps5upload-lz4same-{}", std::process::id())); + let root = crate::test_tmp::temp_path(format!("ps5upload-lz4same-{}", std::process::id())); let _ = std::fs::remove_dir_all(&root); let src = ampr_game(&root); let cancel = AtomicBool::new(false); @@ -490,7 +490,7 @@ mod tests { /// the packs; the spool is gone and a damaged volume fails the read-back. #[test] fn an_lz4_packed_folder_reads_back_to_the_source() { - let root = std::env::temp_dir().join(format!("ps5upload-lz4dir-{}", std::process::id())); + let root = crate::test_tmp::temp_path(format!("ps5upload-lz4dir-{}", std::process::id())); let _ = std::fs::remove_dir_all(&root); let src = ampr_game(&root); let target = root.join("out/PPSA99998-app"); diff --git a/engine/crates/ps5upload-convert-core/src/safe_write.rs b/engine/crates/ps5upload-convert-core/src/safe_write.rs index dcdf8c513..e4bedb5fe 100644 --- a/engine/crates/ps5upload-convert-core/src/safe_write.rs +++ b/engine/crates/ps5upload-convert-core/src/safe_write.rs @@ -603,7 +603,7 @@ mod tests { /// creates the file nor cuts what the builder wrote. #[test] fn the_sync_handle_writes_and_never_creates_or_truncates() { - let dir = std::env::temp_dir().join(format!("ps5u-sync-handle-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("ps5u-sync-handle-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); let path = dir.join("g.pkg.partial"); @@ -626,7 +626,7 @@ mod tests { fn a_growing_file_is_synced_as_it_grows() { use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; - let dir = std::env::temp_dir().join(format!("ps5u-growth-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("ps5u-growth-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); let path = dir.join("g.pkg.partial"); @@ -867,7 +867,7 @@ mod tests { #[test] fn a_new_name_never_replaces_what_is_there() { - let dir = std::env::temp_dir().join(format!("ps5upload-safe-new-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("ps5upload-safe-new-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); let (from, to) = (dir.join("a.partial"), dir.join("a")); @@ -892,7 +892,7 @@ mod tests { #[test] fn a_removal_leaves_nothing() { - let f = std::env::temp_dir().join(format!("ps5upload-safe-{}", std::process::id())); + let f = crate::test_tmp::temp_path(format!("ps5upload-safe-{}", std::process::id())); std::fs::write(&f, b"x").unwrap(); remove_file(&f).unwrap(); assert!(!f.exists()); diff --git a/engine/crates/ps5upload-convert-core/src/unpack_packs.rs b/engine/crates/ps5upload-convert-core/src/unpack_packs.rs index 1cf4f72fd..f1d986a8b 100644 --- a/engine/crates/ps5upload-convert-core/src/unpack_packs.rs +++ b/engine/crates/ps5upload-convert-core/src/unpack_packs.rs @@ -419,11 +419,13 @@ fn unpack( (Some(path), Some(c)) => format!("it has {} at {path}", named(c)), _ => "it has none".to_string(), }; + // The facts last: a long detail is shortened in the middle, and these are what a + // report needs. return Err(format!( - "{NEEDS_OTHER_EMULATOR}: the game reads its files through AMPR and {has}, where \ - ampr_emu {RUNTIME_VERSION} or newer is needed, and none is on this PS5. Put the AMPR \ - emulator on this PS5 from the app, leave it out, or make the package with PS5Upload \ - on a computer" + "{NEEDS_OTHER_EMULATOR}. Put the AMPR emulator on this PS5 from the app, leave it \ + out, or make the package with PS5Upload on a computer. The game reads its files \ + through AMPR and {has}; ampr_emu {RUNTIME_VERSION} or newer is needed, and none is \ + on this PS5" )); } let mut generated: HashMap> = HashMap::new(); @@ -566,7 +568,7 @@ mod tests { impl Scratch { fn new(name: &str) -> Self { - let root = std::env::temp_dir().join(format!( + let root = crate::test_tmp::temp_path(format!( "ps5upload-core-unpack-{name}-{}", std::process::id() )); diff --git a/engine/crates/ps5upload-convert-core/src/writing.rs b/engine/crates/ps5upload-convert-core/src/writing.rs index f005a8ae7..0f10db49f 100644 --- a/engine/crates/ps5upload-convert-core/src/writing.rs +++ b/engine/crates/ps5upload-convert-core/src/writing.rs @@ -331,7 +331,7 @@ mod tests { /// else's is kept and named as in the way. A pack spool is ours either way. #[test] fn a_partial_folder_without_our_marker_is_never_cleared() { - let root = std::env::temp_dir().join(format!("ps5upload-claim-{}", std::process::id())); + let root = crate::test_tmp::temp_path(format!("ps5upload-claim-{}", std::process::id())); let _ = std::fs::remove_dir_all(&root); let theirs = root.join("Game.partial"); std::fs::create_dir_all(&theirs).unwrap(); @@ -366,7 +366,8 @@ mod tests { /// delete it. #[test] fn a_kept_finished_output_is_not_cleared_by_the_next_claim() { - let root = std::env::temp_dir().join(format!("ps5upload-keptclaim-{}", std::process::id())); + let root = + crate::test_tmp::temp_path(format!("ps5upload-keptclaim-{}", std::process::id())); let _ = std::fs::remove_dir_all(&root); std::fs::create_dir_all(&root).unwrap(); let partial = root.join("Game.pkg.partial"); @@ -389,7 +390,8 @@ mod tests { /// treats the same), refuses a second claim, and leaves nothing behind once dropped. #[test] fn a_claim_is_seen_by_other_processes_and_cleared_when_dropped() { - let root = std::env::temp_dir().join(format!("ps5upload-claimlock-{}", std::process::id())); + let root = + crate::test_tmp::temp_path(format!("ps5upload-claimlock-{}", std::process::id())); let _ = std::fs::remove_dir_all(&root); let partial = root.join("Game.exfat.partial"); let file = claim_file_of(&partial).unwrap(); @@ -427,7 +429,7 @@ mod tests { assert!(!retry_open(ErrorKind::PermissionDenied, false)); assert!(!retry_open(ErrorKind::NotFound, true)); // A parent that is a file: no claim file can exist there on any OS. - let root = std::env::temp_dir().join(format!("ps5upload-noclaim-{}", std::process::id())); + let root = crate::test_tmp::temp_path(format!("ps5upload-noclaim-{}", std::process::id())); let _ = std::fs::remove_dir_all(&root); std::fs::create_dir_all(&root).unwrap(); let blocker = root.join("not-a-folder"); diff --git a/engine/crates/ps5upload-convert-core/src/zstd_packs.rs b/engine/crates/ps5upload-convert-core/src/zstd_packs.rs index 7326b94d7..b04b9602a 100644 --- a/engine/crates/ps5upload-convert-core/src/zstd_packs.rs +++ b/engine/crates/ps5upload-convert-core/src/zstd_packs.rs @@ -613,7 +613,7 @@ mod tests { /// the game reads back as it was. #[test] fn a_game_reads_back_through_its_packs_in_every_format() { - let root = std::env::temp_dir().join(format!("ps5upload-zstd-{}", std::process::id())); + let root = crate::test_tmp::temp_path(format!("ps5upload-zstd-{}", std::process::id())); let _ = std::fs::remove_dir_all(&root); std::fs::create_dir_all(&root).unwrap(); let src = game(&root); @@ -685,7 +685,8 @@ mod tests { /// `prepare` makes always matches. #[test] fn packs_that_disagree_with_ampr_emu_index_are_refused() { - let root = std::env::temp_dir().join(format!("ps5upload-zstd-join-{}", std::process::id())); + let root = + crate::test_tmp::temp_path(format!("ps5upload-zstd-join-{}", std::process::id())); let _ = std::fs::remove_dir_all(&root); let src = game(&root); let mut tree = FolderSource::open(&src).unwrap(); @@ -737,7 +738,7 @@ mod tests { /// source; the result opens as the game it was. #[test] fn zstd_packs_go_into_every_image_plain_and_compressed() { - let root = std::env::temp_dir().join(format!("ps5upload-zstdall-{}", std::process::id())); + let root = crate::test_tmp::temp_path(format!("ps5upload-zstdall-{}", std::process::id())); let _ = std::fs::remove_dir_all(&root); std::fs::create_dir_all(&root).unwrap(); let src = game(&root); @@ -801,7 +802,7 @@ mod tests { #[test] fn a_game_folder_packs_into_a_folder_that_reads_back() { let root = - std::env::temp_dir().join(format!("ps5upload-zstd-folder-{}", std::process::id())); + crate::test_tmp::temp_path(format!("ps5upload-zstd-folder-{}", std::process::id())); let _ = std::fs::remove_dir_all(&root); std::fs::create_dir_all(&root).unwrap(); let src = game(&root); @@ -902,7 +903,7 @@ mod tests { #[test] fn a_profile_rule_keeps_its_files_loose() { let root = - std::env::temp_dir().join(format!("ps5upload-zstd-rules-{}", std::process::id())); + crate::test_tmp::temp_path(format!("ps5upload-zstd-rules-{}", std::process::id())); let _ = std::fs::remove_dir_all(&root); std::fs::create_dir_all(&root).unwrap(); let src = game(&root); @@ -985,7 +986,7 @@ mod tests { #[test] fn a_game_that_does_not_import_ampr_is_packed_too() { let root = - std::env::temp_dir().join(format!("ps5upload-zstd-noampr-{}", std::process::id())); + crate::test_tmp::temp_path(format!("ps5upload-zstd-noampr-{}", std::process::id())); let _ = std::fs::remove_dir_all(&root); std::fs::create_dir_all(&root).unwrap(); let src = game(&root); @@ -1067,7 +1068,7 @@ mod tests { #[test] fn a_folder_that_does_not_read_back_as_the_source_is_not_kept() { let root = - std::env::temp_dir().join(format!("ps5upload-zstd-folder-bad-{}", std::process::id())); + crate::test_tmp::temp_path(format!("ps5upload-zstd-folder-bad-{}", std::process::id())); let _ = std::fs::remove_dir_all(&root); std::fs::create_dir_all(&root).unwrap(); let src = game(&root); diff --git a/engine/crates/ps5upload-convert/src/job.rs b/engine/crates/ps5upload-convert/src/job.rs index 994223fcc..15a512cb3 100644 --- a/engine/crates/ps5upload-convert/src/job.rs +++ b/engine/crates/ps5upload-convert/src/job.rs @@ -59,7 +59,7 @@ const STATUS_EVERY: Duration = Duration::from_millis(250); const CANCEL_EVERY: Duration = Duration::from_millis(150); /// The most of a failure's words kept in the status: the helper reads `detail` into 400 bytes /// and drops a longer one. -const MAX_DETAIL_BYTES: usize = 300; +const MAX_DETAIL_BYTES: usize = 512; /// The largest emulator file read for zstd packs (ampr-emu-ng is well under 1 MiB). const MAX_RUNTIME_BYTES: u64 = 16 << 20; /// zstd's level when the request names none: the engine's default. @@ -204,13 +204,24 @@ fn read_request(dir: &Path) -> Result { Ok(request) } -/// `detail` cut to [`MAX_DETAIL_BYTES`] at a character boundary. -fn short(detail: &str) -> &str { - let mut end = detail.len().min(MAX_DETAIL_BYTES); - while !detail.is_char_boundary(end) { - end -= 1; +/// `detail` kept within [`MAX_DETAIL_BYTES`], cut at character boundaries. A long one loses its +/// middle, not its end: details start with a path and end with the reason, and a deep folder's +/// path must not push the reason (a version, a file name) off the end. +fn short(detail: &str) -> std::borrow::Cow<'_, str> { + if detail.len() <= MAX_DETAIL_BYTES { + return std::borrow::Cow::Borrowed(detail); } - &detail[..end] + const GAP: &str = "…"; + let head_max = MAX_DETAIL_BYTES / 3; + let mut head = head_max; + while !detail.is_char_boundary(head) { + head -= 1; + } + let mut tail = detail.len() - (MAX_DETAIL_BYTES - head - GAP.len()); + while !detail.is_char_boundary(tail) { + tail += 1; + } + std::borrow::Cow::Owned(format!("{}{GAP}{}", &detail[..head], &detail[tail..])) } /// A running job's reports: rewrites the status at most every [`STATUS_EVERY`], and at once @@ -1669,7 +1680,7 @@ mod tests { fn a_file_too_big_for_the_drive_has_its_cause() { let plan = Plan { source: std::env::temp_dir(), - dest: std::env::temp_dir().join("g.exfat"), + dest: crate::test_tmp::temp_path("g.exfat"), image: Some(ImageFormat::Exfat), ffpfsc: None, mode: VerifyMode::Full, @@ -1700,10 +1711,27 @@ mod tests { fn a_long_detail_is_cut_at_a_character() { let long = "é".repeat(400); let cut = short(&long); - assert!(cut.len() <= MAX_DETAIL_BYTES && cut.len() >= MAX_DETAIL_BYTES - 1); + assert!(cut.len() <= MAX_DETAIL_BYTES && cut.len() >= MAX_DETAIL_BYTES - 4); + assert!(cut.contains('…')); assert_eq!(short("short"), "short"); } + /// A deep folder's path loses its middle, so the reason at the end survives whole. + #[test] + fn a_long_path_never_cuts_the_reason_off() { + let detail = format!( + "/{}/packed: it has ampr_emu 0.3.9, which reads LZ4 packs only", + "a-very-deep-folder".repeat(30) + ); + let cut = short(&detail); + assert!(cut.len() <= MAX_DETAIL_BYTES, "{}", cut.len()); + assert!( + cut.ends_with("it has ampr_emu 0.3.9, which reads LZ4 packs only"), + "{cut}" + ); + assert!(cut.starts_with("/a-very-deep-folder")); + } + // ---- a .pkg of a game in asset packs, as plain files ("Unpack the asset packs") ---- /// A game large enough to pack, whose eboot imports libSceAmpr (`ampr`) or not, with the diff --git a/engine/crates/ps5upload-convert/src/lib.rs b/engine/crates/ps5upload-convert/src/lib.rs index 74f0d97dd..f89d0b4b3 100644 --- a/engine/crates/ps5upload-convert/src/lib.rs +++ b/engine/crates/ps5upload-convert/src/lib.rs @@ -586,3 +586,8 @@ mod tests { ); } } + +// Test scratch paths removed when the test process exits (engine/test-support/test_tmp.rs). +#[cfg(test)] +#[path = "../../../test-support/test_tmp.rs"] +mod test_tmp; diff --git a/engine/crates/ps5upload-core/src/archive_extract.rs b/engine/crates/ps5upload-core/src/archive_extract.rs index 81760e116..1e1d5799d 100644 --- a/engine/crates/ps5upload-core/src/archive_extract.rs +++ b/engine/crates/ps5upload-core/src/archive_extract.rs @@ -715,7 +715,7 @@ mod tests { #[test] fn remove_path_retrying_removes_trees_files_and_absent_paths() { - let base = std::env::temp_dir().join(format!("ps5u-rmretry-{}", std::process::id())); + let base = crate::test_tmp::temp_path(format!("ps5u-rmretry-{}", std::process::id())); let tree = base.join("tree"); std::fs::create_dir_all(tree.join("a/b")).unwrap(); std::fs::write(tree.join("a/b/f.bin"), b"x").unwrap(); diff --git a/engine/crates/ps5upload-core/src/archive_extract/free/tests.rs b/engine/crates/ps5upload-core/src/archive_extract/free/tests.rs index ce385792a..73dba8ede 100644 --- a/engine/crates/ps5upload-core/src/archive_extract/free/tests.rs +++ b/engine/crates/ps5upload-core/src/archive_extract/free/tests.rs @@ -8,7 +8,7 @@ struct Scratch(PathBuf); impl Scratch { fn new(name: &str) -> Scratch { static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); - let dir = std::env::temp_dir().join(format!( + let dir = crate::test_tmp::temp_path(format!( "ps5u-free-{name}-{}-{}", std::process::id(), N.fetch_add(1, Ordering::Relaxed) diff --git a/engine/crates/ps5upload-core/src/archive_stream.rs b/engine/crates/ps5upload-core/src/archive_stream.rs index 766f1eaac..b1d4b11bf 100644 --- a/engine/crates/ps5upload-core/src/archive_stream.rs +++ b/engine/crates/ps5upload-core/src/archive_stream.rs @@ -115,7 +115,7 @@ mod tests { /// alone refuses it. #[test] fn zstd_zip_entries_read_through_the_engine() { - let d = std::env::temp_dir().join(format!("ps5u-archive-shim-{}", std::process::id())); + let d = crate::test_tmp::temp_path(format!("ps5u-archive-shim-{}", std::process::id())); let _ = std::fs::remove_dir_all(&d); std::fs::create_dir_all(&d).unwrap(); let data: Vec = (0..200_000u32).map(|i| (i % 251) as u8).collect(); diff --git a/engine/crates/ps5upload-core/src/backport_pack.rs b/engine/crates/ps5upload-core/src/backport_pack.rs index cfc259a67..40b0823c1 100644 --- a/engine/crates/ps5upload-core/src/backport_pack.rs +++ b/engine/crates/ps5upload-core/src/backport_pack.rs @@ -312,7 +312,7 @@ mod tests { #[test] fn inspect_sorts_a_real_pack_layout() { // The richer pack shape: every role present at once. - let dir = std::env::temp_dir().join(format!("packtest-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("packtest-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); for sub in ["fakelib", "sce_module", "prx", "sce_sys/about"] { std::fs::create_dir_all(dir.join(sub)).unwrap(); diff --git a/engine/crates/ps5upload-core/src/cheats.rs b/engine/crates/ps5upload-core/src/cheats.rs index 0b19ea655..ee55f327f 100644 --- a/engine/crates/ps5upload-core/src/cheats.rs +++ b/engine/crates/ps5upload-core/src/cheats.rs @@ -1155,7 +1155,7 @@ mod tests { } } let dir = - std::env::temp_dir().join(format!("ps5upload-local-cheat-{}", std::process::id())); + crate::test_tmp::temp_path(format!("ps5upload-local-cheat-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let source = dir.join("PPSA13197.json"); std::fs::write( diff --git a/engine/crates/ps5upload-core/src/fakelibs.rs b/engine/crates/ps5upload-core/src/fakelibs.rs index ef44bac71..f1985fb5d 100644 --- a/engine/crates/ps5upload-core/src/fakelibs.rs +++ b/engine/crates/ps5upload-core/src/fakelibs.rs @@ -551,7 +551,7 @@ mod observation_tests { use super::*; fn scratch(tag: &str) -> PathBuf { - let dir = std::env::temp_dir().join(format!("fakelibs-obs-{tag}-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("fakelibs-obs-{tag}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); dir } @@ -1762,7 +1762,7 @@ mod tests { fn tempdir() -> TempDir { use std::sync::atomic::{AtomicU64, Ordering}; static NEXT: AtomicU64 = AtomicU64::new(0); - let p = std::env::temp_dir().join(format!( + let p = crate::test_tmp::temp_path(format!( "ps5upload-fakelibs-test-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed) diff --git a/engine/crates/ps5upload-core/src/fs_ops.rs b/engine/crates/ps5upload-core/src/fs_ops.rs index 75fcbd0a9..f1a191dd4 100644 --- a/engine/crates/ps5upload-core/src/fs_ops.rs +++ b/engine/crates/ps5upload-core/src/fs_ops.rs @@ -2203,7 +2203,7 @@ mod tests { #[test] fn walk_local_inventory_respects_excludes() { let root = - std::env::temp_dir().join(format!("ps5upload-fs-ops-excludes-{}", std::process::id())); + crate::test_tmp::temp_path(format!("ps5upload-fs-ops-excludes-{}", std::process::id())); let _ = std::fs::remove_dir_all(&root); std::fs::create_dir_all(root.join(".git")).unwrap(); std::fs::write(root.join("eboot.bin"), b"real").unwrap(); diff --git a/engine/crates/ps5upload-core/src/game_meta.rs b/engine/crates/ps5upload-core/src/game_meta.rs index 32a60e815..69b83bbf6 100644 --- a/engine/crates/ps5upload-core/src/game_meta.rs +++ b/engine/crates/ps5upload-core/src/game_meta.rs @@ -380,7 +380,7 @@ mod tests { )); let _ = fs::remove_dir_all(&p); fs::create_dir_all(&p).unwrap(); - p + crate::test_tmp::remove_at_exit(p) } #[test] diff --git a/engine/crates/ps5upload-core/src/lib.rs b/engine/crates/ps5upload-core/src/lib.rs index 5c03da242..daadb0725 100644 --- a/engine/crates/ps5upload-core/src/lib.rs +++ b/engine/crates/ps5upload-core/src/lib.rs @@ -76,3 +76,8 @@ pub mod vinput; pub mod volumes; pub mod vpad; pub mod zip_cd; + +// Test scratch paths removed when the test process exits (engine/test-support/test_tmp.rs). +#[cfg(test)] +#[path = "../../../test-support/test_tmp.rs"] +mod test_tmp; diff --git a/engine/crates/ps5upload-core/src/payload_library/cache.rs b/engine/crates/ps5upload-core/src/payload_library/cache.rs index b03593d96..842e29261 100644 --- a/engine/crates/ps5upload-core/src/payload_library/cache.rs +++ b/engine/crates/ps5upload-core/src/payload_library/cache.rs @@ -162,6 +162,13 @@ impl Library { (Some(t), _) => format!("{name} {t} isn't on this computer"), (None, _) => format!("{name} isn't on this computer"), }; + if super::repos::is_valid_custom_id(id) { + // A source the user added: the app downloads it when asked. + return Err(LibraryError::new( + NOT_ON_THIS_COMPUTER, + format!("{what}. Download it on its card in Payloads first."), + )); + } Err(LibraryError::new( NOT_ON_THIS_COMPUTER, format!( diff --git a/engine/crates/ps5upload-core/src/payload_library/http.rs b/engine/crates/ps5upload-core/src/payload_library/http.rs index ff4879eb6..91a8b7eb1 100644 --- a/engine/crates/ps5upload-core/src/payload_library/http.rs +++ b/engine/crates/ps5upload-core/src/payload_library/http.rs @@ -6,23 +6,37 @@ use std::io::Read; use std::net::IpAddr; -use std::time::Duration; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; use super::{LibraryError, ResolvedEntry}; /// Release metadata: small JSON, so a whole-request deadline fits. const METADATA_TIMEOUT: Duration = Duration::from_secs(15); +/// A payload file from a source the user added: no whole-request deadline (a slow line still +/// finishes), but a stalled one ends. +const DOWNLOAD_IDLE_TIMEOUT: Duration = Duration::from_secs(60); +const DOWNLOAD_CONNECT_TIMEOUT: Duration = Duration::from_secs(15); + +/// Where GitHub serves release files from: `github.com/.../releases/download/...` answers 302 to +/// one of these. +const GITHUB_ASSET_HOSTS: &[&str] = &[ + "objects.githubusercontent.com", + "release-assets.githubusercontent.com", + "github-releases.githubusercontent.com", +]; + const MAX_REDIRECTS: usize = 5; /// GitHub requires a user agent, and uses it to spot abuse: the version pinpoints a release. const HTTP_USER_AGENT: &str = concat!("ps5upload/", env!("CARGO_PKG_VERSION"), " (payloads)"); -/// Which timeouts a request runs under. Only release metadata is fetched now: payload files are -/// never downloaded. +/// Which timeouts a request runs under: release metadata, or a payload file from a source the +/// user added (the only payload files the app downloads). #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum FetchKind { Metadata, + Download, } /// One answer, redirects not followed. @@ -30,9 +44,36 @@ pub struct HttpResponse { pub status: u16, pub location: Option, pub content_length: Option, + /// When the host said it is limiting requests (`Retry-After`, or GitHub's + /// `x-ratelimit-remaining: 0` with `x-ratelimit-reset`): when to ask again, seconds since the + /// Unix epoch. + pub retry_at: Option, pub body: Box, } +fn now_secs() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0) +} + +/// When to ask again, from a response's headers: `Retry-After` (seconds), else GitHub's reset time +/// once its count is spent. `None` when the answer says nothing about a limit. +pub(crate) fn retry_at_from_headers( + retry_after: Option<&str>, + remaining: Option<&str>, + reset: Option<&str>, +) -> Option { + if let Some(secs) = retry_after.and_then(|v| v.trim().parse::().ok()) { + return Some(now_secs().saturating_add(secs.min(24 * 3600))); + } + if remaining.map(str::trim) == Some("0") { + return reset.and_then(|v| v.trim().parse::().ok()); + } + None +} + /// One GET, redirects not followed. A test scripts this; production is [`UreqClient`]. pub trait HttpClient: Send + Sync { fn get(&self, url: &str, accept: Option<&str>, kind: FetchKind) @@ -42,6 +83,7 @@ pub trait HttpClient: Send + Sync { /// The real client. ureq reads `HTTPS_PROXY` and friends from the environment, as before. pub struct UreqClient { metadata: ureq::Agent, + download: ureq::Agent, } impl UreqClient { @@ -52,8 +94,17 @@ impl UreqClient { .max_redirects(0) .timeout_global(Some(METADATA_TIMEOUT)) .build(); + let download = ureq::Agent::config_builder() + .user_agent(HTTP_USER_AGENT) + .http_status_as_error(false) + .max_redirects(0) + .timeout_connect(Some(DOWNLOAD_CONNECT_TIMEOUT)) + .timeout_recv_response(Some(DOWNLOAD_IDLE_TIMEOUT)) + .timeout_per_read(Some(DOWNLOAD_IDLE_TIMEOUT)) + .build(); Self { metadata: ureq::Agent::new_with_config(metadata), + download: ureq::Agent::new_with_config(download), } } } @@ -73,6 +124,7 @@ impl HttpClient for UreqClient { ) -> Result { let agent = match kind { FetchKind::Metadata => &self.metadata, + FetchKind::Download => &self.download, }; let mut req = agent.get(url); if let Some(a) = accept { @@ -87,18 +139,27 @@ impl HttpClient for UreqClient { }; let location = header("location"); let content_length = header("content-length").and_then(|v| v.parse().ok()); + let retry_at = retry_at_from_headers( + header("retry-after").as_deref(), + header("x-ratelimit-remaining").as_deref(), + header("x-ratelimit-reset").as_deref(), + ); Ok(HttpResponse { status: resp.status().as_u16(), location, content_length, + retry_at, body: Box::new(resp.into_body().into_reader()), }) } } -/// The scheme and host of an absolute URL. +/// The scheme, host and port of an absolute URL. `None` for a URL with credentials in it. fn scheme_and_host(url: &str) -> Option<(String, String, Option)> { let uri: ureq::http::Uri = url.parse().ok()?; + if uri.authority()?.as_str().contains('@') { + return None; + } Some(( uri.scheme_str()?.to_ascii_lowercase(), uri.host()?.to_ascii_lowercase(), @@ -123,24 +184,112 @@ pub(crate) fn is_local_name(host: &str) -> bool { .any(|s| bare.ends_with(s)) } +/// Where an address points, for the rule of which hosts a source may use. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum HostClass { + /// A public name or address. + Public, + /// A home network: a private address (10/8, 172.16/12, 192.168/16, 100.64/10, fc00::/7) or a + /// LAN name (`nas.local`, `gitea.lan`, a name without a dot). + Private, + /// Never: this computer itself (loopback, `localhost`), link-local (169.254/16, fe80::/10, + /// where cloud metadata answers), unspecified, multicast, broadcast, documentation ranges. + Forbidden, +} + +fn ipv4_class(v4: std::net::Ipv4Addr) -> HostClass { + let o = v4.octets(); + if v4.is_loopback() + || v4.is_unspecified() + || v4.is_link_local() + || v4.is_multicast() + || v4.is_broadcast() + || v4.is_documentation() + || o[0] == 0 + { + HostClass::Forbidden + } else if v4.is_private() || (o[0] == 100 && (o[1] & 0xc0) == 64) { + HostClass::Private + } else { + HostClass::Public + } +} + +/// The class of a host as a URL names it (an IPv6 address in brackets or not). +pub(crate) fn host_class(host: &str) -> HostClass { + let bare = host + .trim_start_matches('[') + .trim_end_matches(']') + .trim_end_matches('.') + .to_ascii_lowercase(); + if bare.is_empty() { + return HostClass::Forbidden; + } + match bare.parse::() { + Ok(IpAddr::V4(v4)) => return ipv4_class(v4), + Ok(IpAddr::V6(v6)) => { + if let Some(v4) = v6.to_ipv4_mapped() { + return ipv4_class(v4); + } + let first = v6.segments()[0]; + return if v6.is_loopback() + || v6.is_unspecified() + || v6.is_multicast() + || (first & 0xffc0) == 0xfe80 + { + HostClass::Forbidden + } else if (first & 0xfe00) == 0xfc00 { + HostClass::Private + } else { + HostClass::Public + }; + } + Err(_) => {} + } + if bare == "localhost" || bare.ends_with(".localhost") { + HostClass::Forbidden + } else if is_local_name(&bare) { + HostClass::Private + } else { + HostClass::Public + } +} + /// May a request for this entry land on `url`? /// -/// Always https on the default port, and never an address or a LAN name. Beyond that: the -/// entry's host and its subdomains, and for a user's own Gitea or Forgejo server any public name, -/// because such a server may answer from another host. The user chose to trust that server, and -/// the certificate still has to match the name. A GitHub repo stays on GitHub. +/// Always https, and never this computer or a link-local address. A user's own Gitea or Forgejo +/// server may be on the home network and on any port: its own address and port are allowed as +/// added. Beyond that, the default port and public names only: the entry's host and its +/// subdomains; for a source the user added on GitHub, GitHub's release-file hosts too; and for a +/// user's own Gitea or Forgejo server any public name, because such a server may answer from +/// object storage. The user chose to trust that server, and the certificate still has to match +/// the name. A GitHub repo stays on GitHub. pub(crate) fn hop_allowed(entry: &ResolvedEntry, url: &str) -> bool { let Some((scheme, host, port)) = scheme_and_host(url) else { return false; }; - if scheme != "https" || !matches!(port, None | Some(443)) || is_local_name(&host) { + if scheme != "https" || host_class(&host) == HostClass::Forbidden { return false; } let entry_host = entry.repo_host.as_str(); + let is_github = entry_host == "github.com"; + if entry.is_custom + && !is_github + && host == entry_host + && port.unwrap_or(443) == entry.repo_port.unwrap_or(443) + { + return true; + } + if !matches!(port, None | Some(443)) || is_local_name(&host) { + return false; + } if host == entry_host || host.ends_with(&format!(".{entry_host}")) { return true; } - entry.is_custom && entry_host != "github.com" + if is_github { + return entry.is_custom && GITHUB_ASSET_HOSTS.contains(&host.as_str()); + } + entry.is_custom } /// Where a redirect points, as an absolute URL. `None` for a form we do not follow. @@ -219,6 +368,7 @@ mod tests { asset_name_hint: String::new(), is_custom, list_payload: None, + repo_port: None, } } diff --git a/engine/crates/ps5upload-core/src/payload_library/mod.rs b/engine/crates/ps5upload-core/src/payload_library/mod.rs index 4409dec75..868ea7934 100644 --- a/engine/crates/ps5upload-core/src/payload_library/mod.rs +++ b/engine/crates/ps5upload-core/src/payload_library/mod.rs @@ -1,7 +1,7 @@ -//! Payload Library: the curated catalogue of third-party PS5 payloads, user-added repos, -//! release information (GitHub, Gitea, Forgejo: read-only, for "a new version is out"), and the -//! local copies of payloads users got earlier. The app never downloads a payload: users get the -//! file from the project themselves and send it. +//! Payload Library: the curated catalogue of third-party PS5 payloads, the payload sources users +//! add, release information (GitHub, Gitea, Forgejo), and the local copies of payloads. The +//! catalogue is a list of links: the app never downloads a payload from it. Only a source the user +//! added is downloaded, and only when the user asks (`user_sources.rs`). //! //! One implementation for every front end: the desktop app's commands and the engine's //! `/api/payloads` routes both call [`Library`], over the same folder when the engine is the @@ -27,6 +27,7 @@ mod releases; mod repos; mod sources; mod updates; +mod user_sources; use std::fmt; use std::path::{Path, PathBuf}; @@ -44,6 +45,10 @@ use repos::CustomRepo; use sources::ListPayload; pub use sources::SourceInfo; pub use updates::{is_newer, AppliedUpdate, UpdateOutcome, UpdateRow, UpdateState, PREVIOUS_DIR}; +pub use user_sources::{ + is_payload_file_name, name_pattern, names_match, parse_project_url, HaveCopy, LatestFile, + PreviewFile, PreviewRelease, ProjectRef, SourceError, SourcePreview, UserSource, +}; /// Overrides where the library lives. The desktop app sets it for its sidecar, so the engine's /// routes and the app's screens share one cache. @@ -172,6 +177,8 @@ pub(crate) struct ResolvedEntry { pub(crate) is_custom: bool, /// A payload from a source list (#829): its one listed file and SHA-256. pub(crate) list_payload: Option>, + /// The port of a user's own Gitea or Forgejo server, when it is not 443. + pub(crate) repo_port: Option, } impl From<&CatalogueEntry> for ResolvedEntry { @@ -184,6 +191,7 @@ impl From<&CatalogueEntry> for ResolvedEntry { asset_name_hint: e.asset_name_hint.to_string(), is_custom: false, list_payload: None, + repo_port: None, } } } @@ -198,6 +206,7 @@ impl From<&CustomRepo> for ResolvedEntry { asset_name_hint: r.asset_name_hint.clone(), is_custom: true, list_payload: None, + repo_port: r.repo_port, } } } @@ -350,12 +359,26 @@ fn is_safe_payload_id(id: &str) -> bool { || sources::is_valid_list_payload_id(id) } -/// The `.elf` in a payload's cache folder (there is one per payload; see `remove_other_elfs`). +/// The payload in a payload's cache folder (there is one per payload; see `remove_other_elfs`): +/// its `.elf`, else a `.bin` (a source the user added may publish one). fn elf_in_dir(dir: &Path) -> Option { - std::fs::read_dir(dir).ok()?.flatten().find_map(|f| { - let p = f.path(); - (p.extension().and_then(|e| e.to_str()) == Some("elf")).then_some(p) - }) + let files: Vec = std::fs::read_dir(dir) + .ok()? + .flatten() + .map(|f| f.path()) + .filter(|p| p.is_file()) + .collect(); + let with_ext = |ext: &str| { + files + .iter() + .find(|p| { + p.extension() + .and_then(|e| e.to_str()) + .is_some_and(|e| e.eq_ignore_ascii_case(ext)) + }) + .cloned() + }; + with_ext("elf").or_else(|| with_ext("bin")) } fn mtime_secs(meta: &std::fs::Metadata) -> i64 { @@ -443,6 +466,10 @@ pub(crate) mod test_support { pub struct Scripted { pub routes: Mutex>, pub asked: Mutex>, + /// url → when the host says to ask again (a rate-limit answer). + pub retry_at: Mutex>, + /// url → the length the answer claims, when it differs from the body (cut short). + pub claimed_len: Mutex>, } impl Scripted { @@ -465,6 +492,22 @@ pub(crate) mod test_support { .unwrap() .insert(url.to_string(), (0, None, Vec::new())); } + /// The host's rate limit: `status` (403 or 429), ask again at `retry_at`. + pub fn limited(&self, url: &str, status: u16, retry_at: u64) { + self.status(url, status); + self.retry_at + .lock() + .unwrap() + .insert(url.to_string(), retry_at); + } + /// An answer that claims `claimed` bytes and ends after `body`. + pub fn cut_short(&self, url: &str, body: &[u8], claimed: u64) { + self.ok(url, body); + self.claimed_len + .lock() + .unwrap() + .insert(url.to_string(), claimed); + } pub fn redirect(&self, url: &str, to: &str) { self.routes .lock() @@ -491,10 +534,18 @@ pub(crate) mod test_support { if status == 0 { return Err("io: Connection refused".into()); } + let content_length = self + .claimed_len + .lock() + .unwrap() + .get(url) + .copied() + .unwrap_or(body.len() as u64); Ok(HttpResponse { status, location, - content_length: Some(body.len() as u64), + content_length: Some(content_length), + retry_at: self.retry_at.lock().unwrap().get(url).copied(), body: Box::new(Cursor::new(body)), }) } @@ -505,7 +556,7 @@ pub(crate) mod test_support { impl TempDir { pub fn new(tag: &str) -> Self { let dir = - std::env::temp_dir().join(format!("ps5upload-library-{tag}-{}", unique_suffix())); + crate::test_tmp::temp_path(format!("ps5upload-library-{tag}-{}", unique_suffix())); std::fs::create_dir_all(&dir).unwrap(); Self(dir) } diff --git a/engine/crates/ps5upload-core/src/payload_library/releases.rs b/engine/crates/ps5upload-core/src/payload_library/releases.rs index 7a277249d..d561d2908 100644 --- a/engine/crates/ps5upload-core/src/payload_library/releases.rs +++ b/engine/crates/ps5upload-core/src/payload_library/releases.rs @@ -16,10 +16,10 @@ use super::{atomic_write, Library, LibraryError, ResolvedEntry}; const RELEASE_CACHE_TTL: Duration = Duration::from_secs(3600); /// The most release JSON accepted: 30 releases with long notes fit well under this. -const RELEASE_JSON_MAX_BYTES: u64 = 16 * 1024 * 1024; +pub(super) const RELEASE_JSON_MAX_BYTES: u64 = 16 * 1024 * 1024; /// GitHub and Gitea both accept this; only GitHub looks at it. -const JSON_ACCEPT: &str = "application/vnd.github+json"; +pub(super) const JSON_ACCEPT: &str = "application/vnd.github+json"; /// A text field GitHub sometimes sends as `null` instead of leaving it out (a release with no /// notes has `"body": null`). `#[serde(default)]` alone only covers a missing field, so a null @@ -51,6 +51,9 @@ pub(super) struct GithubRelease { /// So the UI can warn that a version may be unstable (payload development moves fast). #[serde(default)] pub(super) prerelease: bool, + /// A draft is not published yet (only its owner sees one); a source skips it. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub(super) draft: bool, } /// What a client consumes: flat, with the asset already picked. @@ -207,6 +210,7 @@ fn list_release(entry: &ResolvedEntry, refresh_error: Option) -> Release }], html_url: p.homepage.clone(), prerelease: false, + draft: false, }; release_to_info(entry, &release, 0, refresh_error) } @@ -494,6 +498,7 @@ mod tests { html_url: "".into(), prerelease: false, assets, + draft: false, } } diff --git a/engine/crates/ps5upload-core/src/payload_library/repos.rs b/engine/crates/ps5upload-core/src/payload_library/repos.rs index 1e5624d96..ad9a57900 100644 --- a/engine/crates/ps5upload-core/src/payload_library/repos.rs +++ b/engine/crates/ps5upload-core/src/payload_library/repos.rs @@ -1,10 +1,9 @@ -//! User-added payload repos (#93). +//! User-added payload repos (#93): the payload sources a user adds (see `user_sources.rs`). //! -//! The curated catalogue is a `const`. Users also track their own repos (a fork, a niche payload), -//! which live in `custom-repos.json` and flow through the same release-information path, so -//! every fetch guard applies to them. New repos can no longer be added from the app (it never -//! downloads a payload); repos added earlier stay listed and can be removed. Custom ids are always -//! `custom-`, so they can never collide with a catalogue id nor leave the library's folder. +//! The curated catalogue is a `const`. Users also add their own projects (a fork, a niche +//! payload), which live in `custom-repos.json` and flow through the same release-information +//! path, so every fetch guard applies to them. Custom ids are always `custom-`, so they can +//! never collide with a catalogue id nor leave the library's folder. use serde::{Deserialize, Serialize}; use serde_json::Value; @@ -15,8 +14,8 @@ use super::{atomic_write, Library, LibraryError, PayloadInfo}; pub(super) const CUSTOM_AUTOLOAD_PRIORITY: u8 = u8::MAX; pub(super) const CUSTOM_AUTOLOAD_DELAY_MS: u32 = 200; -/// A user-added repo, as stored by an earlier version. `id` was minted when it was added; the rest -/// is what the user supplied. Fields this build no longer reads (`checksum_file`) are ignored. +/// A user-added repo. `id` was minted when it was added; the rest is what the user supplied. +/// Fields this build no longer reads (`checksum_file`) are ignored. #[derive(Debug, Clone, Deserialize, Serialize)] pub(crate) struct CustomRepo { pub(crate) id: String, @@ -26,24 +25,49 @@ pub(crate) struct CustomRepo { pub(crate) repo_name: String, #[serde(default)] pub(crate) asset_name_hint: String, + /// A Gitea or Forgejo server's port, when it is not 443. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub(crate) repo_port: Option, + /// The payload file the user picked (12.6.34). Empty for a repo added before 12.6.0, which + /// asks for the file to be picked. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub(crate) file_name: String, +} + +impl CustomRepo { + /// The host as a URL names it: `host` or `host:port`. + pub(crate) fn host_and_port(&self) -> String { + match self.repo_port { + Some(p) => format!("{}:{p}", self.repo_host), + None => self.repo_host.clone(), + } + } + + /// The project's page. + pub(crate) fn project_url(&self) -> String { + format!( + "https://{}/{}/{}", + self.host_and_port(), + self.repo_owner, + self.repo_name + ) + } } impl From<&CustomRepo> for PayloadInfo { fn from(r: &CustomRepo) -> Self { - let homepage = if r.repo_host == "github.com" { - format!("https://github.com/{}/{}", r.repo_owner, r.repo_name) - } else { - format!("https://{}/{}/{}", r.repo_host, r.repo_owner, r.repo_name) - }; + let homepage = r.project_url(); Self { id: r.id.clone(), display_name: r.display_name.clone(), role: "Custom repo".to_string(), description: format!( - "User-added repo. Releases are fetched from {}/{}/{} and sent like any \ - other payload — the same ELF/zip checks apply. ps5upload doesn't vet \ - what this repo ships; only add repos you trust.", - r.repo_host, r.repo_owner, r.repo_name + "A payload source you added. Its releases are read from {}/{}/{}, and the file \ + you picked is downloaded and sent when you ask. ps5upload doesn't check what \ + this project publishes; only add projects you trust.", + r.host_and_port(), + r.repo_owner, + r.repo_name ), repo_owner: r.repo_owner.clone(), repo_name: r.repo_name.clone(), @@ -167,7 +191,7 @@ impl Library { } } - fn save_repo_file(&self, file: &RepoFile) -> Result<(), LibraryError> { + pub(super) fn save_repo_file(&self, file: &RepoFile) -> Result<(), LibraryError> { let mut out: Vec = Vec::with_capacity(file.repos.len() + file.kept.len()); for r in &file.repos { out.push( @@ -228,6 +252,8 @@ pub(crate) mod test_repos { repo_owner: owner.into(), repo_name: name.into(), asset_name_hint: String::new(), + repo_port: None, + file_name: String::new(), }; assert!(is_valid_custom_id(&repo.id)); let mut file = lib.read_repo_file().unwrap(); diff --git a/engine/crates/ps5upload-core/src/payload_library/sources.rs b/engine/crates/ps5upload-core/src/payload_library/sources.rs index fc4bead4c..3bdec1803 100644 --- a/engine/crates/ps5upload-core/src/payload_library/sources.rs +++ b/engine/crates/ps5upload-core/src/payload_library/sources.rs @@ -301,6 +301,7 @@ impl ListPayload { asset_name_hint: self.file_hint(), is_custom: false, list_payload: Some(Box::new(self.clone())), + repo_port: None, } } } diff --git a/engine/crates/ps5upload-core/src/payload_library/updates.rs b/engine/crates/ps5upload-core/src/payload_library/updates.rs index 0baea2acb..ede852822 100644 --- a/engine/crates/ps5upload-core/src/payload_library/updates.rs +++ b/engine/crates/ps5upload-core/src/payload_library/updates.rs @@ -351,10 +351,13 @@ impl Library { extra_ids: &[String], ) -> Result { let catalog = self.catalog(); + // A payload source the user added has its own card, which checks only when asked: it is + // left out here, so it is neither checked twice nor shown twice. let mut ids: Vec = self .local_inventory() .into_iter() .map(|e| e.payload_id) + .filter(|id| !super::repos::is_valid_custom_id(id)) .collect(); for id in extra_ids { if !ids.contains(id) && catalog.iter().any(|p| &p.id == id) { diff --git a/engine/crates/ps5upload-core/src/payload_library/user_sources.rs b/engine/crates/ps5upload-core/src/payload_library/user_sources.rs new file mode 100644 index 000000000..b2f5ce4be --- /dev/null +++ b/engine/crates/ps5upload-core/src/payload_library/user_sources.rs @@ -0,0 +1,2104 @@ +//! Payload sources the user adds: a GitHub project, or a Gitea or Forgejo one (on the internet or +//! on the home network), that publishes payload files in its releases. +//! +//! The user picks the file once. The app reads the project's releases only when asked (opening +//! Payloads, or Check), keeps what it read for ten minutes, downloads only on Download or Update, +//! and sends only on Send (through the usual send path). Nothing runs in the background. The +//! built-in catalogue stays a list of links: only a project the user added is ever downloaded. +//! +//! Stored with the repos earlier versions added (`custom-repos.json`, ids `custom-`): an entry +//! with a `file_name` is complete; one without (added before 12.6.0) asks for the file to be +//! picked. +//! +//! **Which file a newer release uses.** Two names match when they are the same apart from their +//! version parts. A version part is a number that does not follow a letter (a `v` before it +//! excepted), with the dots and letters joined to it: `1.6.0`, `2.4b`, `20240101`. So +//! `kstuff-v1.6.0.elf` matches `kstuff-v1.7.elf`, while `ftpsrv-ps5.elf` (the 5 follows a letter) +//! matches only itself and never `ftpsrv-ps4.elf`. Case does not matter. In a release, a file with +//! the exact name comes first. +//! +//! **Addresses.** https only, no user name or password in the address. github.com projects use +//! GitHub's API and its release-file hosts. Any other host is a Gitea or Forgejo server, which may +//! be on the home network (a private address or a LAN name) and on its own port; never this +//! computer (loopback, `localhost`) or a link-local address. Every redirect is checked again +//! (`http::hop_allowed`). +//! +//! **Files per source**, in `//`: the payload, `download.json` (which release it is), +//! `VERSION` (the tag, as older versions kept it) and `source-releases.json` (the last release +//! list read, used for ten minutes). + +use std::collections::HashMap; +use std::io::{Read, Write}; +use std::path::{Path, PathBuf}; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; + +use super::cache::sha256_of_file; +use super::http::{fetch, host_class, FetchKind, HostClass}; +use super::releases::{GithubAsset, GithubRelease, JSON_ACCEPT, RELEASE_JSON_MAX_BYTES}; +use super::repos::{is_valid_custom_id, CustomRepo}; +use super::{ + atomic_write, elf_in_dir, is_newer, replace_file, unique_suffix, Library, LibraryError, + ResolvedEntry, TmpFile, +}; + +/// How long a release list read from a project is used before it is read again (unless the user +/// presses Check). GitHub allows 60 anonymous requests an hour. +const SOURCE_CHECK_TTL: Duration = Duration::from_secs(600); +/// The newest releases read from a project. +const SOURCE_RELEASE_COUNT: usize = 10; +/// The largest payload file downloaded. +pub(crate) const SOURCE_DOWNLOAD_MAX_BYTES: u64 = 128 * 1024 * 1024; +/// The largest checksum file read. +const CHECKSUM_FILE_MAX_BYTES: u64 = 64 * 1024; +/// A partial download older than this was left by a crash. +const STALE_PART_AGE: Duration = Duration::from_secs(3600); +const RELEASES_FILE: &str = "source-releases.json"; +const DOWNLOAD_FILE: &str = "download.json"; +const URL_MAX_CHARS: usize = 500; +const FILE_NAME_MAX_CHARS: usize = 200; +const SEGMENT_MAX_CHARS: usize = 100; + +/// Why a source call failed: a stable `code` the app words itself, an English `message`, and for +/// a host's rate limit, when to try again. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct SourceError { + pub code: String, + pub message: String, + /// Seconds since the Unix epoch: when the host said to ask again. + #[serde(skip_serializing_if = "Option::is_none")] + pub retry_at: Option, +} + +impl SourceError { + fn new(code: &str, message: impl Into) -> Self { + Self { + code: code.to_string(), + message: message.into(), + retry_at: None, + } + } +} + +impl From for SourceError { + fn from(e: LibraryError) -> Self { + Self::new(e.code, e.message) + } +} + +impl std::fmt::Display for SourceError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.message) + } +} + +impl std::error::Error for SourceError {} + +// ── Addresses ──────────────────────────────────────────────────────────────────────────────────── + +/// A project as the user's address names it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ProjectRef { + /// `github.com`, or a Gitea or Forgejo server's host as a URL names it (lowercase). + pub host: String, + /// A Gitea or Forgejo server's port, when it is not 443. + pub port: Option, + pub owner: String, + pub name: String, +} + +impl ProjectRef { + pub fn is_github(&self) -> bool { + self.host == "github.com" + } + + fn host_and_port(&self) -> String { + match self.port { + Some(p) => format!("{}:{p}", self.host), + None => self.host.clone(), + } + } + + pub fn project_url(&self) -> String { + format!( + "https://{}/{}/{}", + self.host_and_port(), + self.owner, + self.name + ) + } + + /// `custom-<12 hex>`: FNV-1a over the lowercased `host[:port]/owner/name`, as earlier versions + /// minted it, so adding a project again finds the same entry and folder. + pub fn id(&self) -> String { + let key = + format!("{}/{}/{}", self.host_and_port(), self.owner, self.name).to_ascii_lowercase(); + let mut h: u64 = 0xcbf29ce484222325; + for b in key.as_bytes() { + h ^= *b as u64; + h = h.wrapping_mul(0x100000001b3); + } + format!("custom-{:012x}", h & 0xffff_ffff_ffff) + } + + fn entry(&self) -> ResolvedEntry { + ResolvedEntry { + id: self.id(), + repo_host: self.host.clone(), + repo_owner: self.owner.clone(), + repo_name: self.name.clone(), + asset_name_hint: String::new(), + is_custom: true, + list_payload: None, + repo_port: self.port, + } + } + + fn of_repo(r: &CustomRepo) -> Self { + Self { + host: r.repo_host.clone(), + port: r.repo_port, + owner: r.repo_owner.clone(), + name: r.repo_name.clone(), + } + } +} + +/// One path part of a project: an owner or a project name. +fn is_valid_segment(s: &str) -> bool { + !s.is_empty() + && s.len() <= SEGMENT_MAX_CHARS + && s != "." + && s != ".." + && s.chars() + .all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '_' || c == '-') +} + +/// A host name or address, as a URL names it: letters, digits, dots and dashes, or an IPv6 +/// address in brackets. +fn is_plausible_host(host: &str) -> bool { + if host.is_empty() || host.len() > 253 { + return false; + } + if let Some(inner) = host.strip_prefix('[').and_then(|h| h.strip_suffix(']')) { + return inner.parse::().is_ok(); + } + host.split('.').all(|l| { + !l.is_empty() + && l.len() <= 63 + && !l.starts_with('-') + && !l.ends_with('-') + && l.chars() + .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-') + }) +} + +/// Read a project's address: `https://github.com/owner/project` (anything after the project, like +/// `/releases`, is ignored), or a Gitea or Forgejo server's `https://host[:port]/owner/project`. +/// An address without a scheme is read as https. +pub fn parse_project_url(raw: &str) -> Result { + let raw = raw.trim(); + let not_a_project = || { + SourceError::new( + "url_not_a_project", + "That isn't a project address. Paste the project's page, like \ + https://github.com/owner/project.", + ) + }; + if raw.is_empty() || raw.chars().count() > URL_MAX_CHARS || raw.chars().any(char::is_whitespace) + { + return Err(not_a_project()); + } + let lower = raw.to_ascii_lowercase(); + let with_scheme = if lower.starts_with("https://") { + raw.to_string() + } else if lower.contains("://") { + return Err(SourceError::new( + "url_not_https", + "Only https:// addresses can be added.", + )); + } else { + format!("https://{raw}") + }; + let uri: ureq::http::Uri = with_scheme.parse().map_err(|_| not_a_project())?; + let authority = uri.authority().ok_or_else(not_a_project)?; + if authority.as_str().contains('@') { + return Err(SourceError::new( + "url_has_credentials", + "Remove the user name or password from the address.", + )); + } + let host = uri + .host() + .ok_or_else(not_a_project)? + .trim_end_matches('.') + .to_ascii_lowercase(); + let port = uri.port_u16().filter(|p| *p != 443); + let mut parts = uri.path().split('/').filter(|s| !s.is_empty()); + let owner = parts.next().unwrap_or_default().to_string(); + let name = parts + .next() + .unwrap_or_default() + .trim_end_matches(".git") + .to_string(); + if !is_valid_segment(&owner) || !is_valid_segment(&name) || !is_plausible_host(&host) { + return Err(not_a_project()); + } + if host == "github.com" || host == "www.github.com" { + if port.is_some() { + return Err(not_a_project()); + } + return Ok(ProjectRef { + host: "github.com".into(), + port: None, + owner, + name, + }); + } + if host.ends_with(".github.com") + || host.ends_with("githubusercontent.com") + || host == "github.io" + || host.ends_with(".github.io") + { + return Err(not_a_project()); + } + if host == "gitlab.com" || host.starts_with("gitlab.") { + return Err(SourceError::new( + "url_gitlab", + "GitLab projects aren't supported. Use a GitHub, Gitea or Forgejo project.", + )); + } + if host_class(&host) == HostClass::Forbidden { + return Err(SourceError::new( + "url_host_not_allowed", + format!( + "{host} can't be used: it is this computer or a link-local address. Use the \ + server's address on your network." + ), + )); + } + Ok(ProjectRef { + host, + port, + owner, + name, + }) +} + +// ── File names ─────────────────────────────────────────────────────────────────────────────────── + +/// A file name a source can use: a plain `.elf` or `.bin` name. +pub fn is_payload_file_name(name: &str) -> bool { + let lower = name.to_ascii_lowercase(); + !name.is_empty() + && name.chars().count() <= FILE_NAME_MAX_CHARS + && (lower.ends_with(".elf") || lower.ends_with(".bin")) + && lower.len() > 4 + && !name.starts_with('.') + && !name.contains("..") + && !name + .chars() + .any(|c| c.is_control() || matches!(c, '/' | '\\' | ':' | '%' | '*' | '?' | '"')) +} + +#[derive(Debug, PartialEq, Eq)] +enum Part { + Text(String), + Version, +} + +/// A name cut into text and version parts (see the module's notes). Text is kept as written. +fn name_parts(name: &str) -> Vec { + let chars: Vec = name.chars().collect(); + let mut out = Vec::new(); + let mut text = String::new(); + let mut i = 0; + while i < chars.len() { + let c = chars[i]; + let starts_part = c.is_ascii_digit() + && match i { + 0 => true, + _ => { + let prev = chars[i - 1]; + !prev.is_alphanumeric() + || (matches!(prev, 'v' | 'V') && (i < 2 || !chars[i - 2].is_alphanumeric())) + } + }; + if !starts_part { + text.push(c); + i += 1; + continue; + } + let mut j = i; + while j < chars.len() { + let d = chars[j]; + if d.is_ascii_alphanumeric() + || (d == '.' && chars.get(j + 1).is_some_and(|n| n.is_ascii_digit())) + { + j += 1; + } else { + break; + } + } + if !text.is_empty() { + out.push(Part::Text(std::mem::take(&mut text))); + } + out.push(Part::Version); + i = j; + } + if !text.is_empty() { + out.push(Part::Text(text)); + } + out +} + +/// The picked name as it shows which names newer releases may use: `*` for each version part +/// (`kstuff-v1.6.0.elf` → `kstuff-v*.elf`). A name without one shows as itself. +pub fn name_pattern(name: &str) -> String { + name_parts(name) + .iter() + .map(|p| match p { + Part::Text(t) => t.as_str(), + Part::Version => "*", + }) + .collect() +} + +/// Whether `candidate` is the picked `name` or the same apart from its version parts. +pub fn names_match(name: &str, candidate: &str) -> bool { + let (a, b) = (name_parts(name), name_parts(candidate)); + a.len() == b.len() + && a.iter().zip(&b).all(|pair| match pair { + (Part::Version, Part::Version) => true, + (Part::Text(x), Part::Text(y)) => x.eq_ignore_ascii_case(y), + _ => false, + }) +} + +/// The file a release has for the picked name: the exact name first, else a match. +fn file_in_release<'a>(release: &'a GithubRelease, picked: &str) -> Option<&'a GithubAsset> { + let usable = |a: &&GithubAsset| is_payload_file_name(&a.name); + release + .assets + .iter() + .filter(usable) + .find(|a| a.name.eq_ignore_ascii_case(picked)) + .or_else(|| { + release + .assets + .iter() + .filter(usable) + .find(|a| names_match(picked, &a.name)) + }) +} + +/// The newest release with a file for the picked name, and that file. +fn newest_match<'a>( + list: &'a [GithubRelease], + picked: &str, +) -> Option<(&'a GithubRelease, &'a GithubAsset)> { + list.iter() + .find_map(|r| file_in_release(r, picked).map(|a| (r, a))) +} + +// ── Checksums ──────────────────────────────────────────────────────────────────────────────────── + +/// Checksum files a release may carry for its files: one per file, or a list. +const CHECKSUM_LISTS: &[&str] = &[ + "sha256sums", + "sha256sums.txt", + "sha256sum.txt", + "sha256.txt", + "checksums.txt", + "checksums.sha256", + "checksum.txt", +]; + +/// The release's checksum file for `file`, and whether it is for that one file alone. +fn checksum_asset<'a>(release: &'a GithubRelease, file: &str) -> Option<(&'a GithubAsset, bool)> { + let lower = file.to_ascii_lowercase(); + let own = [ + format!("{lower}.sha256"), + format!("{lower}.sha256sum"), + format!("{lower}.sha256.txt"), + ]; + if let Some(a) = release + .assets + .iter() + .find(|a| own.contains(&a.name.to_ascii_lowercase())) + { + return Some((a, true)); + } + release + .assets + .iter() + .find(|a| CHECKSUM_LISTS.contains(&a.name.to_ascii_lowercase().as_str())) + .map(|a| (a, false)) +} + +fn is_sha256_hex(s: &str) -> bool { + s.len() == 64 && s.chars().all(|c| c.is_ascii_hexdigit()) +} + +/// The SHA-256 a checksum file gives `file`: ` ` (or ` *`), BSD's +/// `SHA256 () = `, or for a file's own checksum file the first hash in it. `None` when +/// it has none for `file`. +fn expected_sha256(text: &str, file: &str, own_file: bool) -> Option { + for line in text.lines() { + let line = line.trim(); + if let Some(rest) = line.strip_prefix("SHA256 (") { + if let Some((name, hex)) = rest.split_once(") = ") { + let base = name.rsplit('/').next().unwrap_or(name); + if base.eq_ignore_ascii_case(file) && is_sha256_hex(hex.trim()) { + return Some(hex.trim().to_ascii_lowercase()); + } + } + continue; + } + let mut words = line.split_whitespace(); + let Some(hex) = words.next().filter(|h| is_sha256_hex(h)) else { + continue; + }; + match words.next() { + Some(name) => { + let name = name.trim_start_matches('*'); + let base = name.rsplit('/').next().unwrap_or(name); + if base.eq_ignore_ascii_case(file) { + return Some(hex.to_ascii_lowercase()); + } + } + None if own_file => return Some(hex.to_ascii_lowercase()), + None => {} + } + } + None +} + +// ── What the screens show ──────────────────────────────────────────────────────────────────────── + +/// The copy of a source's file on this computer. +#[derive(Debug, Clone, Serialize)] +pub struct HaveCopy { + /// The release it came from; empty for a copy an old version saved without one. + pub tag: String, + pub file_name: String, + pub size: u64, + /// SHA-256 of the file as it is on disk now: what a send gives the console. + pub sha256: String, + pub published_at: String, + /// Seconds since the Unix epoch; 0 when unknown. + pub downloaded_at: i64, + /// `matched` (the release's checksum file named this file and it matched), `none` (the + /// release had none for it), or empty for a copy from an older version. + pub checksum: String, + /// Where it is: what a send uses. + pub path: String, +} + +/// The newest release's file for the picked name. +#[derive(Debug, Clone, Serialize)] +pub struct LatestFile { + pub tag: String, + pub release_name: String, + pub file_name: String, + pub size: u64, + pub published_at: String, + pub prerelease: bool, + pub html_url: String, +} + +/// A source as the screens show it. +#[derive(Debug, Clone, Serialize)] +pub struct UserSource { + pub id: String, + pub name: String, + /// `github` or `gitea` (Gitea and Forgejo). + pub kind: &'static str, + pub project_url: String, + pub owner: String, + pub repo: String, + /// The picked file. Empty for an entry added before 12.6.0: it asks for the file. + pub file_name: String, + /// Which names newer releases may use: the picked name with `*` for each version part. + pub file_pattern: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub have: Option, + /// Known after a check: the newest release's file for the picked name. + #[serde(skip_serializing_if = "Option::is_none")] + pub latest: Option, + /// The newest release's file is newer than the copy here. + pub update_available: bool, + /// Age of the release list shown, seconds. Absent before any check. + #[serde(skip_serializing_if = "Option::is_none")] + pub checked_age_secs: Option, + /// The last check failed (the list shown, if any, is older), or no release has the file. + #[serde(skip_serializing_if = "Option::is_none")] + pub error: Option, +} + +/// One file of a release, as the add step lists it. +#[derive(Debug, Clone, Serialize)] +pub struct PreviewFile { + pub name: String, + pub size: u64, + /// What newer releases may name it (see [`name_pattern`]). + pub pattern: String, +} + +#[derive(Debug, Clone, Serialize)] +pub struct PreviewRelease { + pub tag: String, + pub name: String, + pub published_at: String, + pub prerelease: bool, + pub html_url: String, + /// Its `.elf` and `.bin` files. + pub files: Vec, +} + +/// A project's newest releases with payload files, before (or instead of) adding it. +#[derive(Debug, Clone, Serialize)] +pub struct SourcePreview { + /// The id it has once added. + pub id: String, + pub name: String, + pub kind: &'static str, + pub project_url: String, + /// It is added already: adding again changes its file. + pub already_added: bool, + /// Its picked file, when added already. + pub current_file: String, + /// Newest first; only releases with a `.elf` or `.bin` file. + pub releases: Vec, +} + +/// What `download.json` keeps about a downloaded file. +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +struct DownloadRecord { + tag: String, + file_name: String, + #[serde(default)] + published_at: String, + #[serde(default)] + checksum: String, + #[serde(default)] + downloaded_at: i64, +} + +fn now_secs() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0) +} + +fn kind_of(p: &ProjectRef) -> &'static str { + if p.is_github() { + "github" + } else { + "gitea" + } +} + +/// The release list's address: GitHub's API, or the Gitea/Forgejo API on the server itself. +fn releases_api_url(p: &ProjectRef) -> String { + if p.is_github() { + format!( + "https://api.github.com/repos/{}/{}/releases?per_page={SOURCE_RELEASE_COUNT}", + p.owner, p.name + ) + } else { + format!( + "https://{}/api/v1/repos/{}/{}/releases?limit={SOURCE_RELEASE_COUNT}", + p.host_and_port(), + p.owner, + p.name + ) + } +} + +fn host_label(p: &ProjectRef) -> String { + if p.is_github() { + "GitHub".to_string() + } else { + p.host_and_port() + } +} + +/// Removes every `.elf` and `.bin` in a source's folder except `keep`. +fn remove_other_payload_files(dir: &Path, keep: &str) { + let Ok(read) = std::fs::read_dir(dir) else { + return; + }; + for f in read.flatten() { + let p = f.path(); + let ext = p + .extension() + .and_then(|e| e.to_str()) + .map(str::to_ascii_lowercase); + if p.is_file() + && matches!(ext.as_deref(), Some("elf") | Some("bin")) + && f.file_name().to_str() != Some(keep) + { + let _ = std::fs::remove_file(&p); + } + } +} + +/// Removes partial downloads a crash left (older than an hour; a newer one may be a download in +/// progress). +fn sweep_stale_parts(dir: &Path) { + let Ok(read) = std::fs::read_dir(dir) else { + return; + }; + for f in read.flatten() { + let name = f.file_name().to_string_lossy().into_owned(); + if !name.ends_with(".part") { + continue; + } + let old = f + .metadata() + .and_then(|m| m.modified()) + .ok() + .and_then(|t| SystemTime::now().duration_since(t).ok()) + .is_some_and(|age| age >= STALE_PART_AGE); + if old { + let _ = std::fs::remove_file(f.path()); + } + } +} + +/// A release list as a host answered it: the published releases, newest first. +fn parse_release_list(body: &str) -> Result, SourceError> { + let list: Vec = serde_json::from_str(body).map_err(|e| { + SourceError::new( + "fetch_failed", + format!("The answer wasn't a list of releases ({e})."), + ) + })?; + Ok(list.into_iter().filter(|r| !r.draft).collect()) +} + +impl Library { + fn find_source(&self, id: &str) -> Result { + let unknown = || SourceError::new("unknown_source", format!("no payload source {id}")); + if !is_valid_custom_id(id) { + return Err(unknown()); + } + self.read_repo_file()? + .repos + .into_iter() + .find(|r| r.id == id) + .ok_or_else(unknown) + } + + /// Ask a project for its newest releases. + fn fetch_release_list(&self, p: &ProjectRef) -> Result, SourceError> { + let entry = p.entry(); + let url = releases_api_url(p); + let resp = fetch( + self.http.as_ref(), + &entry, + &url, + Some(JSON_ACCEPT), + FetchKind::Metadata, + ) + .map_err(|e| { + if e.code == "fetch_failed" { + SourceError::new( + "unreachable", + format!("Couldn't reach {}: {}", host_label(p), e.message), + ) + } else { + e.into() + } + })?; + let status = resp.status; + if status == 429 || (status == 403 && resp.retry_at.is_some()) { + return Err(SourceError { + code: "rate_limited".into(), + message: format!( + "{} is limiting how often it can be asked. Try again later.", + host_label(p) + ), + retry_at: resp.retry_at, + }); + } + if status == 404 { + return Err(SourceError::new( + "project_not_found", + format!( + "{} has no public project {}/{}.", + host_label(p), + p.owner, + p.name + ), + )); + } + if !(200..300).contains(&status) { + return Err(SourceError::new( + "fetch_failed", + format!("{} answered HTTP {status}.", host_label(p)), + )); + } + let mut body = String::new(); + resp.body + .take(RELEASE_JSON_MAX_BYTES) + .read_to_string(&mut body) + .map_err(|e| { + SourceError::new( + "unreachable", + format!("Couldn't read {}'s answer: {e}", host_label(p)), + ) + })?; + parse_release_list(&body) + } + + fn releases_cache(&self, id: &str) -> PathBuf { + self.dir.join(id).join(RELEASES_FILE) + } + + /// The release list saved for a source, and its age. `fresh_only`: only one from the last ten + /// minutes. + fn cached_release_list(&self, id: &str, fresh_only: bool) -> Option<(Vec, u64)> { + let path = self.releases_cache(id); + let age = std::fs::metadata(&path) + .ok() + .and_then(|m| m.modified().ok()) + .and_then(|t| SystemTime::now().duration_since(t).ok()) + .unwrap_or_default(); + if fresh_only && age >= SOURCE_CHECK_TTL { + return None; + } + let list = serde_json::from_slice(&std::fs::read(&path).ok()?).ok()?; + Some((list, age.as_secs())) + } + + fn save_release_list(&self, id: &str, list: &[GithubRelease]) { + let dir = self.dir.join(id); + if std::fs::create_dir_all(&dir).is_err() { + return; + } + if let Ok(body) = serde_json::to_vec(list) { + // A saving, not the answer: a full or read-only folder must not fail a check. + let _ = atomic_write(&dir.join(RELEASES_FILE), &body); + } + } + + /// A source's release list: the one from the last ten minutes (unless `force`), else the + /// project's. A failed read answers the older list, if any, with the error. `skip` is an error + /// this pass already had from the same host (its rate limit, or no network): the host is not + /// asked again. + fn source_release_list( + &self, + repo: &CustomRepo, + force: bool, + skip: Option<&SourceError>, + ) -> (Option<(Vec, u64)>, Option) { + if !force { + if let Some(fresh) = self.cached_release_list(&repo.id, true) { + return (Some(fresh), None); + } + } + let fetched = match skip { + Some(e) => Err(e.clone()), + None => self.fetch_release_list(&ProjectRef::of_repo(repo)), + }; + match fetched { + Ok(list) => { + self.save_release_list(&repo.id, &list); + (Some((list, 0)), None) + } + Err(e) => (self.cached_release_list(&repo.id, false), Some(e)), + } + } + + /// The copy of a source's file here, if any. + fn have_copy(&self, repo: &CustomRepo) -> Option { + let dir = self.dir.join(&repo.id); + if !dir.is_dir() { + return None; + } + let record: Option = std::fs::read(dir.join(DOWNLOAD_FILE)) + .ok() + .and_then(|b| serde_json::from_slice(&b).ok()) + .filter(|r: &DownloadRecord| is_payload_file_name(&r.file_name)); + let (path, record) = match record { + Some(r) if dir.join(&r.file_name).is_file() => (dir.join(&r.file_name), r), + _ => { + // A copy an older version saved: its `.elf` and `VERSION`. + let path = elf_in_dir(&dir)?; + let tag = std::fs::read_to_string(dir.join("VERSION")) + .unwrap_or_default() + .trim() + .to_string(); + let file_name = path.file_name()?.to_string_lossy().into_owned(); + ( + path, + DownloadRecord { + tag, + file_name, + ..DownloadRecord::default() + }, + ) + } + }; + let size = std::fs::metadata(&path).ok()?.len(); + let sha256 = sha256_of_file(&path).ok()?; + Some(HaveCopy { + tag: record.tag, + file_name: record.file_name, + size, + sha256, + published_at: record.published_at, + downloaded_at: record.downloaded_at, + checksum: record.checksum, + path: path.to_string_lossy().into_owned(), + }) + } + + fn source_view( + &self, + repo: &CustomRepo, + list: Option<(Vec, u64)>, + error: Option, + ) -> UserSource { + let p = ProjectRef::of_repo(repo); + let have = self.have_copy(repo); + let mut error = error; + let mut latest = None; + let mut checked_age_secs = None; + if let Some((list, age)) = &list { + checked_age_secs = Some(*age); + if !repo.file_name.is_empty() { + match newest_match(list, &repo.file_name) { + Some((r, a)) => { + latest = Some(LatestFile { + tag: r.tag_name.clone(), + release_name: if r.name.is_empty() { + r.tag_name.clone() + } else { + r.name.clone() + }, + file_name: a.name.clone(), + size: a.size, + published_at: r.published_at.clone(), + prerelease: r.prerelease, + html_url: r.html_url.clone(), + }) + } + None if error.is_none() => { + error = Some(SourceError::new( + "no_matching_file", + format!( + "None of the newest releases has a file named like {}.", + name_pattern(&repo.file_name) + ), + )) + } + None => {} + } + } + } + let update_available = match (&have, &latest) { + (Some(h), Some(l)) => { + is_newer(&l.tag, &h.tag) + || (l.tag == h.tag + && (!l.file_name.eq_ignore_ascii_case(&h.file_name) + || (l.size > 0 && l.size != h.size))) + } + _ => false, + }; + UserSource { + id: repo.id.clone(), + name: repo.display_name.clone(), + kind: kind_of(&p), + project_url: p.project_url(), + owner: repo.repo_owner.clone(), + repo: repo.repo_name.clone(), + file_pattern: if repo.file_name.is_empty() { + String::new() + } else { + name_pattern(&repo.file_name) + }, + file_name: repo.file_name.clone(), + have, + latest, + update_available, + checked_age_secs, + error, + } + } + + /// The sources the user added. `check`: read each one's releases (a list from the last ten + /// minutes is used as it is, unless `force`). Without `check` nothing asks the network: the + /// last list read is shown when it is from the last ten minutes. Once a host answers with its + /// rate limit or cannot be reached, the other sources on it are not asked in this pass. + pub fn user_sources(&self, check: bool, force: bool) -> Result, SourceError> { + let repos = self.read_repo_file()?.repos; + let mut host_errors: HashMap = HashMap::new(); + let mut out = Vec::with_capacity(repos.len()); + for repo in &repos { + if repo.file_name.is_empty() { + out.push(self.source_view(repo, None, None)); + continue; + } + if !check { + let list = self.cached_release_list(&repo.id, true); + out.push(self.source_view(repo, list, None)); + continue; + } + let host = repo.host_and_port(); + let (list, error) = self.source_release_list(repo, force, host_errors.get(&host)); + if let Some(e) = &error { + if matches!(e.code.as_str(), "rate_limited" | "unreachable") { + host_errors.entry(host).or_insert_with(|| e.clone()); + } + } + out.push(self.source_view(repo, list, error)); + } + Ok(out) + } + + /// One source, without asking the network. + pub fn user_source(&self, id: &str) -> Result { + let repo = self.find_source(id)?; + let list = self.cached_release_list(&repo.id, true); + Ok(self.source_view(&repo, list, None)) + } + + /// A project's newest releases with `.elf` and `.bin` files, for picking the file. A project + /// already added uses its list from the last ten minutes. + pub fn preview_user_source(&self, url: &str) -> Result { + let p = parse_project_url(url)?; + let id = p.id(); + let existing = self + .read_repo_file()? + .repos + .into_iter() + .find(|r| r.id == id); + let list = match &existing { + Some(repo) => match self.source_release_list(repo, false, None) { + (_, Some(e)) => return Err(e), + (Some((list, _)), None) => list, + (None, None) => Vec::new(), + }, + None => self.fetch_release_list(&p)?, + }; + let releases = list + .iter() + .filter_map(|r| { + let files: Vec = r + .assets + .iter() + .filter(|a| is_payload_file_name(&a.name)) + .map(|a| PreviewFile { + name: a.name.clone(), + size: a.size, + pattern: name_pattern(&a.name), + }) + .collect(); + (!files.is_empty()).then(|| PreviewRelease { + tag: r.tag_name.clone(), + name: if r.name.is_empty() { + r.tag_name.clone() + } else { + r.name.clone() + }, + published_at: r.published_at.clone(), + prerelease: r.prerelease, + html_url: r.html_url.clone(), + files, + }) + }) + .collect(); + Ok(SourcePreview { + id, + name: existing + .as_ref() + .map(|r| r.display_name.clone()) + .unwrap_or_else(|| p.name.clone()), + kind: kind_of(&p), + project_url: p.project_url(), + already_added: existing.is_some(), + current_file: existing.map(|r| r.file_name).unwrap_or_default(), + releases, + }) + } + + /// Add a project as a payload source with the file the user picked, or change the file of one + /// added already. Asks no network: the next check reads its releases. + pub fn add_user_source(&self, url: &str, file_name: &str) -> Result { + let p = parse_project_url(url)?; + let file_name = checked_file_name(file_name)?; + let id = p.id(); + let mut file = self.read_repo_file()?; + let same = |r: &CustomRepo| { + r.id == id + || (r.repo_host == p.host + && r.repo_port == p.port + && r.repo_owner.eq_ignore_ascii_case(&p.owner) + && r.repo_name.eq_ignore_ascii_case(&p.name)) + }; + let repo = match file.repos.iter_mut().find(|r| same(r)) { + Some(r) => { + r.file_name = file_name; + r.clone() + } + None => { + let r = CustomRepo { + id, + display_name: p.name.clone(), + repo_host: p.host.clone(), + repo_owner: p.owner.clone(), + repo_name: p.name.clone(), + asset_name_hint: String::new(), + repo_port: p.port, + file_name, + }; + file.repos.push(r.clone()); + r + } + }; + self.save_repo_file(&file)?; + let list = self.cached_release_list(&repo.id, true); + Ok(self.source_view(&repo, list, None)) + } + + /// Change the file a source downloads (or pick it, for an entry from before 12.6.0). The copy + /// here stays until the next download replaces it. + pub fn set_user_source_file( + &self, + id: &str, + file_name: &str, + ) -> Result { + let file_name = checked_file_name(file_name)?; + self.find_source(id)?; + let mut file = self.read_repo_file()?; + let Some(repo) = file.repos.iter_mut().find(|r| r.id == id) else { + return Err(SourceError::new( + "unknown_source", + format!("no payload source {id}"), + )); + }; + repo.file_name = file_name; + let repo = repo.clone(); + self.save_repo_file(&file)?; + let list = self.cached_release_list(&repo.id, true); + Ok(self.source_view(&repo, list, None)) + } + + /// Download the newest release's file for a source into its folder: through a temporary file, + /// checked against the size the release gives and against the release's checksum file when it + /// has one for it, then renamed into place. The copy it replaces stays if anything fails. + pub fn download_user_source(&self, id: &str) -> Result { + let repo = self.find_source(id)?; + if repo.file_name.is_empty() { + return Err(SourceError::new( + "needs_file", + "Pick the file this source downloads first.", + )); + } + let p = ProjectRef::of_repo(&repo); + let list = match self.source_release_list(&repo, false, None) { + (Some((list, _)), _) => list, + (None, Some(e)) => return Err(e), + (None, None) => Vec::new(), + }; + let Some((release, asset)) = newest_match(&list, &repo.file_name) else { + return Err(SourceError::new( + "no_matching_file", + format!( + "None of the newest releases has a file named like {}.", + name_pattern(&repo.file_name) + ), + )); + }; + // Only a plain .elf or .bin name is ever picked (`file_in_release`), so it is safe as a + // file name in the source's folder; checked again here, where it becomes one. + if !is_payload_file_name(&asset.name) { + return Err(SourceError::new( + "asset_not_payload", + format!("{} isn't a .elf or .bin file name.", asset.name), + )); + } + let entry = p.entry(); + let dir = self.dir.join(&repo.id); + std::fs::create_dir_all(&dir) + .map_err(|e| SourceError::new("io_failed", format!("mkdir {}: {e}", dir.display())))?; + sweep_stale_parts(&dir); + + // The checksum first: a file that lists it but can't be read fails before the download. + let expected = match checksum_asset(release, &asset.name) { + Some((sums, own)) => { + let text = self.read_checksum_file(&entry, &sums.browser_download_url)?; + expected_sha256(&text, &asset.name, own) + } + None => None, + }; + + let resp = fetch( + self.http.as_ref(), + &entry, + &asset.browser_download_url, + None, + FetchKind::Download, + )?; + if !(200..300).contains(&resp.status) { + return Err(SourceError::new( + "fetch_failed", + format!( + "{} answered HTTP {} for {}.", + host_label(&p), + resp.status, + asset.name + ), + )); + } + let too_large = |n: u64| { + SourceError::new( + "asset_too_large", + format!( + "{} is too large ({n} bytes; the most is {SOURCE_DOWNLOAD_MAX_BYTES}).", + asset.name + ), + ) + }; + if let Some(n) = resp + .content_length + .filter(|n| *n > SOURCE_DOWNLOAD_MAX_BYTES) + { + return Err(too_large(n)); + } + if asset.size > SOURCE_DOWNLOAD_MAX_BYTES { + return Err(too_large(asset.size)); + } + + let part = TmpFile(dir.join(format!(".{}.{}.part", asset.name, unique_suffix()))); + let mut hasher = Sha256::new(); + let mut written: u64 = 0; + let mut head = [0u8; 4]; + let mut head_len = 0usize; + { + let mut out = std::fs::File::create(&part.0).map_err(|e| { + SourceError::new("io_failed", format!("create {}: {e}", part.0.display())) + })?; + let mut body = resp.body; + let mut buf = vec![0u8; 64 * 1024]; + loop { + let n = body.read(&mut buf).map_err(|e| { + SourceError::new( + "download_cut_short", + format!( + "The download of {} stopped after {written} bytes ({e}). Try again.", + asset.name + ), + ) + })?; + if n == 0 { + break; + } + written = written.saturating_add(n as u64); + if written > SOURCE_DOWNLOAD_MAX_BYTES { + return Err(too_large(written)); + } + hasher.update(&buf[..n]); + let take = (head.len() - head_len).min(n); + head[head_len..head_len + take].copy_from_slice(&buf[..take]); + head_len += take; + out.write_all(&buf[..n]).map_err(|e| { + SourceError::new("io_failed", format!("write {}: {e}", part.0.display())) + })?; + } + out.sync_all().map_err(|e| { + SourceError::new("io_failed", format!("fsync {}: {e}", part.0.display())) + })?; + } + let want = resp + .content_length + .or((asset.size > 0).then_some(asset.size)); + if let Some(total) = want.filter(|t| *t != written) { + return Err(SourceError::new( + "download_cut_short", + format!( + "The download of {} stopped after {written} of {total} bytes. Try again.", + asset.name + ), + )); + } + if asset.size > 0 && asset.size != written { + return Err(SourceError::new( + "download_cut_short", + format!( + "{} is {written} bytes, but the release lists {} bytes. Try again.", + asset.name, asset.size + ), + )); + } + let got: String = hasher + .finalize() + .iter() + .map(|b| format!("{b:02x}")) + .collect(); + let checksum = match &expected { + Some(want) if *want != got => { + return Err(SourceError::new( + "checksum_mismatch", + format!( + "{} doesn't match the checksum its release lists (got {got}, expected \ + {want}). It was not kept.", + asset.name + ), + )) + } + Some(_) => "matched", + None => "none", + }; + // The same rule a send applies: an .elf must be one (not an error page saved under its + // name), a .bin must not be empty. + let is_elf_name = asset.name.to_ascii_lowercase().ends_with(".elf"); + if written == 0 || (is_elf_name && head[..head_len] != *b"\x7FELF") { + return Err(SourceError::new( + "asset_not_payload", + format!( + "{} isn't a payload ({}). It was not kept.", + asset.name, + if written == 0 { + "it is empty" + } else { + "not an ELF file" + } + ), + )); + } + let final_path = dir.join(&asset.name); + replace_file(&part.0, &final_path).map_err(|e| { + SourceError::new( + "io_failed", + format!("rename into {}: {e}", final_path.display()), + ) + })?; + remove_other_payload_files(&dir, &asset.name); + let record = DownloadRecord { + tag: release.tag_name.clone(), + file_name: asset.name.clone(), + published_at: release.published_at.clone(), + checksum: checksum.to_string(), + downloaded_at: now_secs() as i64, + }; + if let Ok(body) = serde_json::to_vec_pretty(&record) { + atomic_write(&dir.join(DOWNLOAD_FILE), &body) + .map_err(|e| SourceError::new("io_failed", format!("write download.json: {e}")))?; + } + let _ = atomic_write(&dir.join("VERSION"), release.tag_name.as_bytes()); + crate::log::log(&format!( + "[payloads] source {}: downloaded {} {} ({written} bytes, checksum {checksum})", + repo.id, asset.name, release.tag_name + )); + let list = self.cached_release_list(&repo.id, false); + Ok(self.source_view(&repo, list, None)) + } + + fn read_checksum_file(&self, entry: &ResolvedEntry, url: &str) -> Result { + let unreadable = |why: String| { + SourceError::new( + "checksum_unreadable", + format!("The release's checksum file couldn't be read ({why})."), + ) + }; + let resp = fetch(self.http.as_ref(), entry, url, None, FetchKind::Metadata) + .map_err(|e| unreadable(e.message))?; + if !(200..300).contains(&resp.status) { + return Err(unreadable(format!("HTTP {}", resp.status))); + } + if resp + .content_length + .is_some_and(|n| n > CHECKSUM_FILE_MAX_BYTES) + { + return Err(unreadable("too large".into())); + } + let mut bytes = Vec::new(); + resp.body + .take(CHECKSUM_FILE_MAX_BYTES + 1) + .read_to_end(&mut bytes) + .map_err(|e| unreadable(e.to_string()))?; + if bytes.len() as u64 > CHECKSUM_FILE_MAX_BYTES { + return Err(unreadable("too large".into())); + } + Ok(String::from_utf8_lossy(&bytes).into_owned()) + } +} + +fn checked_file_name(name: &str) -> Result { + let name = name.trim(); + if !is_payload_file_name(name) { + return Err(SourceError::new( + "invalid_file_name", + "Pick a .elf or .bin file from the project's releases.", + )); + } + Ok(name.to_string()) +} + +#[cfg(test)] +mod tests { + use super::super::http::hop_allowed; + use super::super::test_support::{library, Scripted}; + use super::*; + + const GH_API: &str = "https://api.github.com/repos/me/kstuff/releases?per_page=10"; + const GH_URL: &str = "https://github.com/me/kstuff"; + + fn elf(fill: u8, len: usize) -> Vec { + let mut v = b"\x7FELF".to_vec(); + v.resize(len, fill); + v + } + + fn sha_hex(b: &[u8]) -> String { + Sha256::digest(b) + .iter() + .map(|x| format!("{x:02x}")) + .collect() + } + + fn asset_json(name: &str, url: &str, size: usize) -> serde_json::Value { + serde_json::json!({ "name": name, "browser_download_url": url, "size": size }) + } + + fn release_json(tag: &str, assets: Vec) -> serde_json::Value { + serde_json::json!({ + "tag_name": tag, "name": format!("kstuff {tag}"), "body": null, + "published_at": "2026-11-01T00:00:00Z", "prerelease": false, "draft": false, + "html_url": format!("{GH_URL}/releases/tag/{tag}"), "assets": assets, + }) + } + + fn dl(tag: &str, name: &str) -> String { + format!("{GH_URL}/releases/download/{tag}/{name}") + } + + /// A release list with one release carrying `name` (and the body served at its URL). + fn serve_one(http: &Scripted, tag: &str, name: &str, body: &[u8]) { + let list = serde_json::json!([release_json( + tag, + vec![asset_json(name, &dl(tag, name), body.len())] + )]); + http.ok(GH_API, list.to_string().as_bytes()); + http.ok(&dl(tag, name), body); + } + + fn files_in(dir: &Path) -> Vec { + let mut v: Vec = std::fs::read_dir(dir) + .map(|r| { + r.flatten() + .map(|f| f.file_name().to_string_lossy().into_owned()) + .collect() + }) + .unwrap_or_default(); + v.sort(); + v + } + + #[test] + fn github_addresses_are_read_in_their_usual_forms() { + for url in [ + "https://github.com/me/kstuff", + "https://github.com/me/kstuff/", + "https://www.github.com/me/kstuff", + "https://github.com/me/kstuff.git", + "https://github.com/me/kstuff/releases/tag/v1.0", + "github.com/me/kstuff", + " https://GitHub.com/me/kstuff?tab=readme#top ", + ] { + let p = parse_project_url(url).unwrap_or_else(|e| panic!("{url}: {e}")); + assert_eq!( + (p.host.as_str(), p.port, p.owner.as_str(), p.name.as_str()), + ("github.com", None, "me", "kstuff"), + "{url}" + ); + assert_eq!(p.project_url(), "https://github.com/me/kstuff"); + } + } + + #[test] + fn the_id_is_the_one_earlier_versions_minted() { + let (_d, _h, lib) = library("same-id"); + let old = super::super::repos::test_repos::save_custom_repo(&lib, "me", "kstuff", "old"); + let p = parse_project_url("https://github.com/Me/KStuff").unwrap(); + assert_eq!(p.id(), old.id); + // Adding it again completes the old entry instead of making a second one. + let s = lib.add_user_source(GH_URL, "kstuff.elf").unwrap(); + assert_eq!(s.id, old.id); + assert_eq!(s.name, "old"); + assert_eq!(lib.user_sources(false, false).unwrap().len(), 1); + } + + #[test] + fn address_rules() { + let code = |url: &str| parse_project_url(url).err().map(|e| e.code); + assert_eq!( + code("http://github.com/me/kstuff").as_deref(), + Some("url_not_https") + ); + assert_eq!( + code("ftp://example.org/me/k").as_deref(), + Some("url_not_https") + ); + assert_eq!( + code("https://user:pw@github.com/me/kstuff").as_deref(), + Some("url_has_credentials") + ); + assert_eq!( + code("https://token@git.example.org/me/k").as_deref(), + Some("url_has_credentials") + ); + for bad in [ + "https://github.com/me", + "https://github.com/", + "https://github.com:8443/me/kstuff", + "https://api.github.com/repos/me/kstuff", + "https://raw.githubusercontent.com/me/kstuff/main/x.elf", + "https://me.github.io/kstuff", + "https://github.com/me/../x", + "https://github.com/me/kst uff", + "", + ] { + assert_eq!(code(bad).as_deref(), Some("url_not_a_project"), "{bad}"); + } + assert_eq!( + code("https://gitlab.com/me/k").as_deref(), + Some("url_gitlab") + ); + // Never this computer or a link-local address, whatever the kind. + for bad in [ + "https://127.0.0.1/me/k", + "https://127.0.0.1:19113/me/k", + "https://localhost:3000/me/k", + "https://gitea.localhost/me/k", + "https://[::1]:3000/me/k", + "https://169.254.169.254/me/k", + "https://[fe80::1]/me/k", + "https://0.0.0.0/me/k", + "https://[::ffff:127.0.0.1]/me/k", + ] { + assert_eq!(code(bad).as_deref(), Some("url_host_not_allowed"), "{bad}"); + } + } + + #[test] + fn a_gitea_server_may_be_on_the_home_network_and_its_own_port() { + let p = parse_project_url("https://192.168.1.5:3000/me/kstuff").unwrap(); + assert_eq!((p.host.as_str(), p.port), ("192.168.1.5", Some(3000))); + assert!(!p.is_github()); + assert_eq!(p.project_url(), "https://192.168.1.5:3000/me/kstuff"); + assert_eq!( + releases_api_url(&p), + "https://192.168.1.5:3000/api/v1/repos/me/kstuff/releases?limit=10" + ); + for ok in [ + "https://nas.local/me/k", + "https://gitea/me/k", + "https://10.0.0.2/me/k", + "https://[fd00::5]:3000/me/k", + "https://codeberg.org/me/k", + "https://git.example.org:443/me/k", + ] { + assert!(parse_project_url(ok).is_ok(), "{ok}"); + } + assert_eq!( + parse_project_url("https://git.example.org:443/me/k") + .unwrap() + .port, + None + ); + } + + #[test] + fn redirects_follow_the_same_rules() { + let gh = parse_project_url(GH_URL).unwrap().entry(); + assert!(hop_allowed( + &gh, + "https://github.com/me/kstuff/releases/download/v1/k.elf" + )); + assert!(hop_allowed( + &gh, + "https://release-assets.githubusercontent.com/x?sig=1" + )); + assert!(hop_allowed(&gh, "https://objects.githubusercontent.com/x")); + assert!(!hop_allowed(&gh, "https://evil.example/x")); + assert!(!hop_allowed(&gh, "https://192.168.1.5/x")); + assert!(!hop_allowed(&gh, "https://user@github.com/x")); + + let lan = parse_project_url("https://192.168.1.5:3000/me/k") + .unwrap() + .entry(); + assert!(hop_allowed( + &lan, + "https://192.168.1.5:3000/attachments/abc" + )); + assert!(hop_allowed(&lan, "https://s3.example.net/bucket/a.elf")); + for bad in [ + "http://192.168.1.5:3000/attachments/abc", + "https://192.168.1.5:22/x", + "https://192.168.1.6:3000/x", + "https://127.0.0.1:3000/x", + "https://localhost:3000/x", + "https://169.254.169.254/latest/meta-data", + "https://nas.local/x", + ] { + assert!(!hop_allowed(&lan, bad), "{bad}"); + } + } + + #[test] + fn the_file_name_rule() { + assert_eq!(name_pattern("kstuff-v1.6.0.elf"), "kstuff-v*.elf"); + assert_eq!(name_pattern("kstuff.elf"), "kstuff.elf"); + assert_eq!(name_pattern("ftpsrv-ps5.elf"), "ftpsrv-ps5.elf"); + assert_eq!( + name_pattern("ps5-kstuff-1.13-fpkg.elf"), + "ps5-kstuff-*-fpkg.elf" + ); + assert_eq!(name_pattern("etaHEN-2.4b.bin"), "etaHEN-*.bin"); + assert_eq!(name_pattern("payload_20240101.elf"), "payload_*.elf"); + assert_eq!(name_pattern("1.0-thing.elf"), "*-thing.elf"); + + assert!(names_match("kstuff-v1.6.0.elf", "kstuff-v1.7.elf")); + assert!(names_match("kstuff-v1.6.0.elf", "KSTUFF-v2.0.0.ELF")); + assert!(names_match("etaHEN-2.4b.bin", "etaHEN-2.5.bin")); + assert!(names_match("kstuff.elf", "kstuff.elf")); + assert!(!names_match("kstuff.elf", "kstuff-1.0.elf")); + assert!(!names_match("kstuff-v1.6.0.elf", "kstuff-v1.6.0-debug.elf")); + assert!(!names_match("kstuff-v1.6.0.elf", "kstuff-v1.6.0.bin")); + assert!(!names_match("ftpsrv-ps5.elf", "ftpsrv-ps4.elf")); + assert!(!names_match("kstuff-1.0.elf", "kstuff-x.elf")); + + assert!(is_payload_file_name("kstuff.elf")); + assert!(is_payload_file_name("etaHEN.BIN")); + for bad in [ + "kstuff.zip", + ".elf", + "../x.elf", + "a/b.elf", + "a\\b.elf", + "C:x.elf", + "x%2f.elf", + "", + ] { + assert!(!is_payload_file_name(bad), "{bad}"); + } + } + + #[test] + fn checksum_files_in_their_common_forms() { + let h = "a".repeat(64); + let want = Some(h.clone()); + assert_eq!( + expected_sha256(&format!("{h} kstuff.elf\n"), "kstuff.elf", false), + want + ); + assert_eq!( + expected_sha256(&format!("{h} *dist/kstuff.elf"), "kstuff.elf", false), + want + ); + assert_eq!( + expected_sha256( + &format!("SHA256 (kstuff.elf) = {}", h.to_uppercase()), + "kstuff.elf", + false + ), + want + ); + assert_eq!(expected_sha256(&format!("{h}\n"), "kstuff.elf", true), want); + assert_eq!( + expected_sha256(&format!("{h} other.elf"), "kstuff.elf", false), + None + ); + assert_eq!( + expected_sha256(&format!("{h}\n"), "kstuff.elf", false), + None + ); + assert_eq!(expected_sha256("nothing here", "kstuff.elf", true), None); + } + + #[test] + fn add_check_and_download_from_a_github_project() { + let (_d, http, lib) = library("src-flow"); + let body = elf(1, 300); + serve_one(&http, "v1.6.0", "kstuff-v1.6.0.elf", &body); + + let preview = lib.preview_user_source(GH_URL).unwrap(); + assert!(!preview.already_added); + assert_eq!(preview.kind, "github"); + assert_eq!(preview.releases.len(), 1); + assert_eq!(preview.releases[0].files[0].pattern, "kstuff-v*.elf"); + assert!( + !lib.dir().join(&preview.id).exists(), + "a preview saves nothing" + ); + + let added = lib.add_user_source(GH_URL, "kstuff-v1.6.0.elf").unwrap(); + assert_eq!(added.file_pattern, "kstuff-v*.elf"); + assert!(added.have.is_none() && added.latest.is_none()); + + let listed = lib.user_sources(true, false).unwrap(); + let latest = listed[0].latest.as_ref().unwrap(); + assert_eq!((latest.tag.as_str(), latest.size), ("v1.6.0", 300)); + assert!(!listed[0].update_available); + + let got = lib.download_user_source(&added.id).unwrap(); + let have = got.have.unwrap(); + assert_eq!(have.tag, "v1.6.0"); + assert_eq!(have.file_name, "kstuff-v1.6.0.elf"); + assert_eq!(have.size, 300); + assert_eq!(have.sha256, sha_hex(&body)); + assert_eq!(have.checksum, "none"); + assert_eq!(std::fs::read(&have.path).unwrap(), body); + assert_eq!( + files_in(&lib.dir().join(&added.id)), + [ + "VERSION", + "download.json", + "kstuff-v1.6.0.elf", + "source-releases.json" + ] + ); + // The library's own lookups see it too: a send by id uses it. + assert_eq!( + lib.local_path(&added.id).unwrap().to_string_lossy(), + have.path + ); + } + + #[test] + fn checks_use_the_last_ten_minutes_unless_forced() { + let (_d, http, lib) = library("src-cache"); + serve_one(&http, "v1", "k.elf", &elf(1, 10)); + lib.add_user_source(GH_URL, "k.elf").unwrap(); + let asked = || { + http.asked + .lock() + .unwrap() + .iter() + .filter(|u| u.as_str() == GH_API) + .count() + }; + lib.user_sources(true, false).unwrap(); + lib.user_sources(true, false).unwrap(); + assert_eq!(asked(), 1); + // Listing without a check never asks, and still shows the fresh list. + let quiet = lib.user_sources(false, false).unwrap(); + assert!(quiet[0].latest.is_some()); + assert_eq!(asked(), 1); + lib.user_sources(true, true).unwrap(); + assert_eq!(asked(), 2); + } + + #[test] + fn a_rate_limit_says_when_and_the_host_is_not_asked_again() { + let (_d, http, lib) = library("src-limit"); + http.limited(GH_API, 403, 1_900_000_000); + let other = "https://api.github.com/repos/me/other/releases?per_page=10"; + http.ok(other, b"[]"); + lib.add_user_source(GH_URL, "k.elf").unwrap(); + lib.add_user_source("https://github.com/me/other", "o.elf") + .unwrap(); + let listed = lib.user_sources(true, true).unwrap(); + for s in &listed { + let e = s.error.as_ref().unwrap(); + assert_eq!(e.code, "rate_limited", "{}", s.id); + assert_eq!(e.retry_at, Some(1_900_000_000)); + } + assert!(!http.asked.lock().unwrap().iter().any(|u| u == other)); + + // The add step says the same. + let e = lib.preview_user_source(GH_URL).unwrap_err(); + assert_eq!( + (e.code.as_str(), e.retry_at), + ("rate_limited", Some(1_900_000_000)) + ); + + // A 429 without a time is a rate limit too; a plain 403 is not. + http.status(GH_API, 429); + http.retry_at.lock().unwrap().clear(); + let e = lib.preview_user_source(GH_URL).unwrap_err(); + assert_eq!((e.code.as_str(), e.retry_at), ("rate_limited", None)); + http.status(GH_API, 403); + assert_eq!( + lib.preview_user_source(GH_URL).unwrap_err().code, + "fetch_failed" + ); + http.status(GH_API, 404); + assert_eq!( + lib.preview_user_source(GH_URL).unwrap_err().code, + "project_not_found" + ); + http.unreachable(GH_API); + assert_eq!( + lib.preview_user_source(GH_URL).unwrap_err().code, + "unreachable" + ); + } + + #[test] + fn a_failed_check_keeps_showing_the_last_list() { + let (_d, http, lib) = library("src-stale"); + serve_one(&http, "v1", "k.elf", &elf(1, 10)); + lib.add_user_source(GH_URL, "k.elf").unwrap(); + lib.user_sources(true, false).unwrap(); + http.limited(GH_API, 429, 1_900_000_000); + let s = &lib.user_sources(true, true).unwrap()[0]; + assert_eq!(s.latest.as_ref().unwrap().tag, "v1"); + assert_eq!(s.error.as_ref().unwrap().code, "rate_limited"); + } + + #[test] + fn a_release_without_the_file_is_passed_over() { + let (_d, http, lib) = library("src-missing"); + let body = elf(2, 64); + let list = serde_json::json!([ + // Newest: only a debug build and the source. + release_json( + "v2", + vec![ + asset_json("kstuff-v2-debug.elf", &dl("v2", "kstuff-v2-debug.elf"), 64), + asset_json("source.zip", &dl("v2", "source.zip"), 64), + ] + ), + serde_json::json!({ "tag_name": "v3-draft", "draft": true, "assets": [ + asset_json("kstuff-v3.elf", &dl("v3", "kstuff-v3.elf"), 64)] }), + release_json( + "v1", + vec![asset_json("kstuff-v1.elf", &dl("v1", "kstuff-v1.elf"), 64)] + ), + ]); + http.ok(GH_API, list.to_string().as_bytes()); + http.ok(&dl("v1", "kstuff-v1.elf"), &body); + let s = lib.add_user_source(GH_URL, "kstuff-v1.elf").unwrap(); + let listed = lib.user_sources(true, false).unwrap(); + assert_eq!(listed[0].latest.as_ref().unwrap().tag, "v1"); + assert!(listed[0].error.is_none()); + assert_eq!( + lib.download_user_source(&s.id).unwrap().have.unwrap().tag, + "v1" + ); + + // Picked a name no release has: said plainly, nothing downloaded. + let s = lib.set_user_source_file(&s.id, "other.elf").unwrap(); + let listed = lib.user_sources(true, false).unwrap(); + let e = listed[0].error.as_ref().unwrap(); + assert_eq!(e.code, "no_matching_file"); + assert!(e.message.contains("other.elf"), "{}", e.message); + assert_eq!( + lib.download_user_source(&s.id).unwrap_err().code, + "no_matching_file" + ); + } + + #[test] + fn a_renamed_file_that_matches_is_the_update() { + let (_d, http, lib) = library("src-renamed"); + let v1 = elf(1, 40); + serve_one(&http, "v1.6.0", "kstuff-v1.6.0.elf", &v1); + let s = lib.add_user_source(GH_URL, "kstuff-v1.6.0.elf").unwrap(); + lib.download_user_source(&s.id).unwrap(); + + let v2 = elf(2, 50); + serve_one(&http, "v1.7.0", "kstuff-v1.7.0.elf", &v2); + let listed = lib.user_sources(true, true).unwrap(); + assert!(listed[0].update_available); + assert_eq!( + listed[0].latest.as_ref().unwrap().file_name, + "kstuff-v1.7.0.elf" + ); + + let got = lib.download_user_source(&s.id).unwrap(); + let have = got.have.unwrap(); + assert_eq!( + (have.tag.as_str(), have.file_name.as_str()), + ("v1.7.0", "kstuff-v1.7.0.elf") + ); + assert!(!got.update_available); + // The old file is gone: one payload per source. + let files = files_in(&lib.dir().join(&s.id)); + assert!(files.contains(&"kstuff-v1.7.0.elf".to_string())); + assert!(!files.contains(&"kstuff-v1.6.0.elf".to_string())); + } + + #[test] + fn a_checksum_file_is_checked() { + let (_d, http, lib) = library("src-sums"); + let body = elf(3, 77); + let list = serde_json::json!([release_json( + "v1", + vec![ + asset_json("k.elf", &dl("v1", "k.elf"), body.len()), + asset_json("SHA256SUMS", &dl("v1", "SHA256SUMS"), 100), + ] + )]); + http.ok(GH_API, list.to_string().as_bytes()); + http.ok(&dl("v1", "k.elf"), &body); + http.ok( + &dl("v1", "SHA256SUMS"), + format!("{} k.elf\n", sha_hex(&body)).as_bytes(), + ); + let s = lib.add_user_source(GH_URL, "k.elf").unwrap(); + assert_eq!( + lib.download_user_source(&s.id) + .unwrap() + .have + .unwrap() + .checksum, + "matched" + ); + + // A file that doesn't match its checksum is not kept, and the copy here stays. + let mut tampered = body.clone(); + tampered[10] ^= 0xff; + http.ok(&dl("v1", "k.elf"), &tampered); + let e = lib.download_user_source(&s.id).unwrap_err(); + assert_eq!(e.code, "checksum_mismatch"); + let have = lib.user_source(&s.id).unwrap().have.unwrap(); + assert_eq!(have.sha256, sha_hex(&body)); + assert!(!files_in(&lib.dir().join(&s.id)) + .iter() + .any(|f| f.ends_with(".part"))); + + // A checksum file that can't be read stops the download before it starts. + http.status(&dl("v1", "SHA256SUMS"), 500); + assert_eq!( + lib.download_user_source(&s.id).unwrap_err().code, + "checksum_unreadable" + ); + } + + #[test] + fn a_files_own_checksum_file_counts() { + let (_d, http, lib) = library("src-own-sum"); + let body = elf(4, 33); + let list = serde_json::json!([release_json( + "v1", + vec![ + asset_json("k.elf", &dl("v1", "k.elf"), body.len()), + asset_json("k.elf.sha256", &dl("v1", "k.elf.sha256"), 64), + ] + )]); + http.ok(GH_API, list.to_string().as_bytes()); + http.ok(&dl("v1", "k.elf"), &body); + http.ok(&dl("v1", "k.elf.sha256"), sha_hex(&body).as_bytes()); + let s = lib.add_user_source(GH_URL, "k.elf").unwrap(); + assert_eq!( + lib.download_user_source(&s.id) + .unwrap() + .have + .unwrap() + .checksum, + "matched" + ); + } + + #[test] + fn a_download_cut_short_leaves_nothing_and_keeps_the_old_copy() { + let (_d, http, lib) = library("src-short"); + let v1 = elf(1, 40); + serve_one(&http, "v1", "k.elf", &v1); + let s = lib.add_user_source(GH_URL, "k.elf").unwrap(); + lib.download_user_source(&s.id).unwrap(); + + // The answer claims 100 bytes and ends after 60. + let list = serde_json::json!([release_json( + "v2", + vec![asset_json("k.elf", &dl("v2", "k.elf"), 100)] + )]); + http.ok(GH_API, list.to_string().as_bytes()); + http.cut_short(&dl("v2", "k.elf"), &elf(2, 60), 100); + lib.user_sources(true, true).unwrap(); + let e = lib.download_user_source(&s.id).unwrap_err(); + assert_eq!(e.code, "download_cut_short"); + assert!(e.message.contains("60 of 100"), "{}", e.message); + // The release's own size counts when the answer agrees with the short body. + http.cut_short(&dl("v2", "k.elf"), &elf(2, 60), 60); + assert_eq!( + lib.download_user_source(&s.id).unwrap_err().code, + "download_cut_short" + ); + + let dir = lib.dir().join(&s.id); + assert!( + !files_in(&dir).iter().any(|f| f.ends_with(".part")), + "{:?}", + files_in(&dir) + ); + let have = lib.user_source(&s.id).unwrap().have.unwrap(); + assert_eq!((have.tag.as_str(), have.sha256), ("v1", sha_hex(&v1))); + } + + #[test] + fn an_error_page_is_not_kept_as_a_payload() { + let (_d, http, lib) = library("src-html"); + serve_one(&http, "v1", "k.elf", b"Not Found"); + let s = lib.add_user_source(GH_URL, "k.elf").unwrap(); + assert_eq!( + lib.download_user_source(&s.id).unwrap_err().code, + "asset_not_payload" + ); + assert!(lib.user_source(&s.id).unwrap().have.is_none()); + // A .bin only has to have something in it. + serve_one(&http, "v1", "k.bin", b"\x01\x02"); + lib.user_sources(true, true).unwrap(); + let s = lib.set_user_source_file(&s.id, "k.bin").unwrap(); + let have = lib.download_user_source(&s.id).unwrap().have.unwrap(); + assert_eq!(have.file_name, "k.bin"); + assert_eq!(lib.local_path(&s.id).unwrap().to_string_lossy(), have.path); + } + + #[test] + fn a_download_through_githubs_file_host() { + let (_d, http, lib) = library("src-cdn"); + let body = elf(5, 20); + let list = serde_json::json!([release_json( + "v1", + vec![asset_json("k.elf", &dl("v1", "k.elf"), body.len())] + )]); + http.ok(GH_API, list.to_string().as_bytes()); + let cdn = + "https://release-assets.githubusercontent.com/github-production-release-asset/1?sig=x"; + http.redirect(&dl("v1", "k.elf"), cdn); + http.ok(cdn, &body); + let s = lib.add_user_source(GH_URL, "k.elf").unwrap(); + assert_eq!( + lib.download_user_source(&s.id).unwrap().have.unwrap().size, + 20 + ); + + // A redirect anywhere else is refused before it is asked. + http.redirect(&dl("v1", "k.elf"), "https://192.168.1.1/x.elf"); + lib.user_sources(true, true).unwrap(); + assert_eq!( + lib.download_user_source(&s.id).unwrap_err().code, + "redirect_refused" + ); + assert!(!http + .asked + .lock() + .unwrap() + .iter() + .any(|u| u.contains("192.168.1.1"))); + } + + #[test] + fn a_gitea_server_on_the_lan() { + let (_d, http, lib) = library("src-gitea"); + let base = "https://192.168.1.5:3000"; + let api = format!("{base}/api/v1/repos/me/k/releases?limit=10"); + let file = format!("{base}/me/k/releases/download/v1/k.elf"); + let body = elf(6, 12); + let list = serde_json::json!([{ + "tag_name": "v1", "name": "", "published_at": "2026-11-01T00:00:00Z", + "prerelease": true, "draft": false, "html_url": format!("{base}/me/k/releases/tag/v1"), + "assets": [ { "name": "k.elf", "browser_download_url": file, "size": 12 } ], + }]); + http.ok(&api, list.to_string().as_bytes()); + http.ok(&file, &body); + let url = format!("{base}/me/k"); + let preview = lib.preview_user_source(&url).unwrap(); + assert_eq!(preview.kind, "gitea"); + assert!(preview.releases[0].prerelease); + let s = lib.add_user_source(&url, "k.elf").unwrap(); + assert_eq!(s.project_url, url); + assert_eq!( + lib.download_user_source(&s.id) + .unwrap() + .have + .unwrap() + .sha256, + sha_hex(&body) + ); + } + + #[test] + fn an_entry_from_before_asks_for_the_file_and_keeps_its_copy() { + let (_d, http, lib) = library("src-old"); + let info = + super::super::repos::test_repos::save_custom_repo(&lib, "me", "kstuff", "My kstuff"); + let dir = lib.dir().join(&info.id); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("kstuff.elf"), elf(7, 9)).unwrap(); + std::fs::write(dir.join("VERSION"), "v0.9\n").unwrap(); + + let s = &lib.user_sources(true, true).unwrap()[0]; + assert_eq!(s.file_name, ""); + assert!(s.latest.is_none() && s.error.is_none()); + let have = s.have.as_ref().unwrap(); + assert_eq!( + ( + have.tag.as_str(), + have.file_name.as_str(), + have.checksum.as_str() + ), + ("v0.9", "kstuff.elf", "") + ); + assert!( + http.asked.lock().unwrap().is_empty(), + "nothing to check yet" + ); + assert_eq!( + lib.download_user_source(&info.id).unwrap_err().code, + "needs_file" + ); + + serve_one(&http, "v1.0", "kstuff.elf", &elf(8, 11)); + let s = lib.set_user_source_file(&info.id, "kstuff.elf").unwrap(); + assert_eq!(s.file_name, "kstuff.elf"); + let s = &lib.user_sources(true, false).unwrap()[0]; + assert!(s.update_available); + assert!(lib.preview_user_source(GH_URL).unwrap().already_added); + } + + #[test] + fn bad_input_is_refused_before_anything_is_written() { + let (_d, http, lib) = library("src-bad"); + assert_eq!( + lib.add_user_source(GH_URL, "k.zip").unwrap_err().code, + "invalid_file_name" + ); + assert_eq!( + lib.add_user_source(GH_URL, "../k.elf").unwrap_err().code, + "invalid_file_name" + ); + assert_eq!( + lib.add_user_source("http://github.com/me/k", "k.elf") + .unwrap_err() + .code, + "url_not_https" + ); + assert_eq!( + lib.download_user_source("custom-../x").unwrap_err().code, + "unknown_source" + ); + assert_eq!( + lib.set_user_source_file("custom-0b", "k.elf") + .unwrap_err() + .code, + "unknown_source" + ); + assert!(!lib.dir().exists()); + assert!(http.asked.lock().unwrap().is_empty()); + } + + #[test] + fn a_source_is_not_part_of_the_update_check() { + let (_d, http, lib) = library("src-not-updates"); + serve_one(&http, "v1", "k.elf", &elf(1, 10)); + let s = lib.add_user_source(GH_URL, "k.elf").unwrap(); + lib.download_user_source(&s.id).unwrap(); + let state = lib.check_updates(true, &[]).unwrap(); + assert!(state.rows.iter().all(|r| r.payload_id != s.id)); + // Removing it takes its folder. + assert!(lib.remove_custom_repo(&s.id).unwrap()); + assert!(!lib.dir().join(&s.id).exists()); + } +} diff --git a/engine/crates/ps5upload-core/src/payload_lifecycle.rs b/engine/crates/ps5upload-core/src/payload_lifecycle.rs index 2ccf5cf43..db50ce0e5 100644 --- a/engine/crates/ps5upload-core/src/payload_lifecycle.rs +++ b/engine/crates/ps5upload-core/src/payload_lifecycle.rs @@ -1393,7 +1393,7 @@ mod tests { fn temp_file(name: &str, content: &[u8]) -> TempFile { use std::sync::atomic::{AtomicU64, Ordering}; static NEXT: AtomicU64 = AtomicU64::new(0); - let dir = std::env::temp_dir().join(format!( + let dir = crate::test_tmp::temp_path(format!( "ps5upload-send-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed) diff --git a/engine/crates/ps5upload-core/src/rar_helper.rs b/engine/crates/ps5upload-core/src/rar_helper.rs index 66de84f5d..3b60eaec1 100644 --- a/engine/crates/ps5upload-core/src/rar_helper.rs +++ b/engine/crates/ps5upload-core/src/rar_helper.rs @@ -555,7 +555,7 @@ mod tests { #[test] fn a_missing_helper_says_rar_support_is_not_installed() { - let bin = std::env::temp_dir().join("ps5upload-no-such-dir/ps5upload-unrar-missing"); + let bin = crate::test_tmp::temp_path("ps5upload-no-such-dir/ps5upload-unrar-missing"); let e = list_with(&bin, "/x/game.rar", None).err().unwrap(); assert_eq!(e.code, Code::Helper); assert_eq!(e.to_string(), MISSING); diff --git a/engine/crates/ps5upload-core/src/save_archive.rs b/engine/crates/ps5upload-core/src/save_archive.rs index a0dc6c244..3b5f56b28 100644 --- a/engine/crates/ps5upload-core/src/save_archive.rs +++ b/engine/crates/ps5upload-core/src/save_archive.rs @@ -954,7 +954,7 @@ mod tests { use std::sync::atomic::{AtomicU32, Ordering}; static N: AtomicU32 = AtomicU32::new(0); let id = N.fetch_add(1, Ordering::SeqCst); - let p = std::env::temp_dir().join(format!( + let p = crate::test_tmp::temp_path(format!( "ps5upload-test-{}-{}-{}", tag, std::process::id(), @@ -1781,7 +1781,7 @@ mod tests { #[test] fn zip_folder_sets_executable_dir_mode() { let tmp = - std::env::temp_dir().join(format!("ps5upload-test-zipperms-{}", std::process::id())); + crate::test_tmp::temp_path(format!("ps5upload-test-zipperms-{}", std::process::id())); let _ = std::fs::remove_dir_all(&tmp); let title = "CUSA03474"; let inner = tmp.join(title); diff --git a/engine/crates/ps5upload-core/src/tar_archive/tests.rs b/engine/crates/ps5upload-core/src/tar_archive/tests.rs index c95040dae..c6a63dae3 100644 --- a/engine/crates/ps5upload-core/src/tar_archive/tests.rs +++ b/engine/crates/ps5upload-core/src/tar_archive/tests.rs @@ -6,7 +6,7 @@ use super::*; use std::io::Write; fn temp_dir(tag: &str) -> PathBuf { - let d = std::env::temp_dir().join(format!("p5tar-{tag}-{}", std::process::id())); + let d = crate::test_tmp::temp_path(format!("p5tar-{tag}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&d); std::fs::create_dir_all(&d).unwrap(); d diff --git a/engine/crates/ps5upload-core/src/zip_cd.rs b/engine/crates/ps5upload-core/src/zip_cd.rs index 44d21aea2..4666369ee 100644 --- a/engine/crates/ps5upload-core/src/zip_cd.rs +++ b/engine/crates/ps5upload-core/src/zip_cd.rs @@ -388,7 +388,7 @@ mod tests { .duration_since(std::time::UNIX_EPOCH) .unwrap_or_default() .as_nanos(); - std::env::temp_dir().join(format!( + crate::test_tmp::temp_path(format!( "ps5upload-zipcd-test-{}-{}-{}.zip", std::process::id(), n, diff --git a/engine/crates/ps5upload-ctest/tests/lifecycle.rs b/engine/crates/ps5upload-ctest/tests/lifecycle.rs index 19bc02c4a..f5e235bc2 100644 --- a/engine/crates/ps5upload-ctest/tests/lifecycle.rs +++ b/engine/crates/ps5upload-ctest/tests/lifecycle.rs @@ -59,7 +59,7 @@ mod tempdir { impl Dir { pub fn new() -> Dir { static N: AtomicU32 = AtomicU32::new(0); - let p = std::env::temp_dir().join(format!( + let p = crate::test_tmp::temp_path(format!( "ava1-t8-{}-{}", std::process::id(), N.fetch_add(1, Ordering::Relaxed) @@ -356,3 +356,7 @@ fn waiting_for_a_free_port_does_not_wait() { ); assert!(t.elapsed() < Duration::from_millis(500)); } + +// Test scratch paths removed when the test process exits (engine/test-support/test_tmp.rs). +#[path = "../../../test-support/test_tmp.rs"] +mod test_tmp; diff --git a/engine/crates/ps5upload-ctest/tests/smp_meta.rs b/engine/crates/ps5upload-ctest/tests/smp_meta.rs index b9657b85b..6f2e296c6 100644 --- a/engine/crates/ps5upload-ctest/tests/smp_meta.rs +++ b/engine/crates/ps5upload-ctest/tests/smp_meta.rs @@ -18,7 +18,7 @@ struct Roots { impl Roots { fn new(tag: &str) -> Roots { - let base = std::env::temp_dir().join(format!( + let base = crate::test_tmp::temp_path(format!( "ps5u-smp-meta-{tag}-{}-{:?}", std::process::id(), std::time::SystemTime::now() @@ -261,3 +261,7 @@ fn poll_interval_is_clamped_and_run_now_returns_at_once() { assert_eq!(smp_meta::set_poll_seconds(30), 30); assert_eq!(smp_meta::stats().running, 0, "not started by the hooks"); } + +// Test scratch paths removed when the test process exits (engine/test-support/test_tmp.rs). +#[path = "../../../test-support/test_tmp.rs"] +mod test_tmp; diff --git a/engine/crates/ps5upload-engine/api/openapi.json b/engine/crates/ps5upload-engine/api/openapi.json index 4d98a00e0..2135da6d5 100644 --- a/engine/crates/ps5upload-engine/api/openapi.json +++ b/engine/crates/ps5upload-engine/api/openapi.json @@ -4260,6 +4260,17 @@ ], "type": "object" }, + "FileBody": { + "properties": { + "file_name": { + "type": "string" + } + }, + "required": [ + "file_name" + ], + "type": "object" + }, "FileListEntryReq": { "properties": { "dest": { @@ -11209,6 +11220,17 @@ ], "type": "object" }, + "PreviewBody": { + "properties": { + "url": { + "type": "string" + } + }, + "required": [ + "url" + ], + "type": "object" + }, "Problem": { "properties": { "error": { @@ -15712,6 +15734,10 @@ "description": "\"file\" or \"folder\". The caller already knows from context\n(Library/FileSystem row) so we trust the hint and skip a\nstat round-trip just to classify.", "type": "string" }, + "remove_source": { + "description": "A move to a saved server (`dest_dir` is `remote://…`): once the copy is complete and\nchecked on the server, the source is deleted on the console. A failed or cancelled copy\nleaves it (download_relay::finish_move). Refused with any other destination.", + "type": "boolean" + }, "src_path": { "description": "Path on the PS5 to download. For `kind: \"folder\"` this is the\nroot of the tree; for `kind: \"file\"` it's the file itself.", "type": "string" @@ -16639,6 +16665,7 @@ "engine.collection_check_api.CheckStatus": { "properties": { "bytes_done": { + "description": "Of every pass together: a package's full check reads it twice (its blocks, then the\nPlayGo chunk CRCs), and both count here, so `bytes_done` reaches `bytes_total` only at\nthe end (#951).", "minimum": 0, "type": "integer" }, @@ -16682,6 +16709,10 @@ "path": { "type": "string" }, + "phase": { + "description": "For `method` `package` while it runs: `blocks` (every block against its digest) or\n`playgo` (the PlayGo chunk CRCs, a second read of the package). Absent otherwise.", + "type": "string" + }, "problems": { "items": { "$ref": "#/components/schemas/Problem" @@ -17235,6 +17266,21 @@ ], "type": "string" }, + "engine.payloads_api.AddBody": { + "properties": { + "file_name": { + "type": "string" + }, + "url": { + "type": "string" + } + }, + "required": [ + "url", + "file_name" + ], + "type": "object" + }, "engine.pldmgr_api.DeleteReq": { "properties": { "filename": { @@ -28134,8 +28180,66 @@ } }, "/api/payloads/repos": { + "get": { + "description": "GET /api/payloads/repos?check=1&force=1 → {sources}: the payload sources the user added.\nWithout `check`, nothing asks the network (a release list read in the last ten minutes is\nshown). With it, each source's releases are read (a list from the last ten minutes is used\nunless `force`).", + "parameters": [ + { + "in": "query", + "name": "check", + "required": false, + "schema": { + "type": [ + "string", + "null" + ] + } + }, + { + "in": "query", + "name": "force", + "required": false, + "schema": { + "type": [ + "string", + "null" + ] + } + } + ], + "responses": { + "200": { + "description": "Success. The handler builds this answer in a way the generator cannot read." + }, + "403": { + "$ref": "#/components/responses/Error", + "description": "Refused by the engine's address, Origin or Host guards." + }, + "default": { + "$ref": "#/components/responses/Error", + "description": "Any other failure, in the same shape." + } + }, + "summary": "{sources}: the payload sources the user added", + "tags": [ + "payloads" + ], + "x-ps5upload": { + "access": "loopback", + "response_schema": "none" + } + }, "post": { - "description": "POST /api/payloads/repos: refused (410 `payload_downloads_removed`). Repos added earlier stay\nlisted and can be removed.", + "description": "POST /api/payloads/repos {url, file_name} → the source: adds a project as a payload source\nwith the file picked from its releases (adding one again changes its file). Asks no network.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/engine.payloads_api.AddBody" + } + } + }, + "required": true + }, "responses": { "200": { "description": "Success. The handler builds this answer in a way the generator cannot read." @@ -28144,35 +28248,48 @@ "$ref": "#/components/responses/Error", "description": "Refused by the engine's address, Origin or Host guards." }, - "410": { - "content": { - "application/json": { - "schema": { - "anyOf": [ - { - "$ref": "#/components/schemas/Error" - }, - { - "properties": { - "code": {}, - "error": { - "type": "string" - } - }, - "type": "object" - } - ] - } + "default": { + "$ref": "#/components/responses/Error", + "description": "Any other failure, in the same shape." + } + }, + "summary": "The source: adds a project as a payload source with the file picked from its releases (adding one again changes its file)", + "tags": [ + "payloads" + ], + "x-ps5upload": { + "access": "loopback", + "response_schema": "none" + } + } + }, + "/api/payloads/repos/preview": { + "post": { + "description": "POST /api/payloads/repos/preview {url} → the project's newest releases with `.elf` and `.bin`\nfiles, for picking the file. Saves nothing.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PreviewBody" } - }, - "description": "Gone" + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Success. The handler builds this answer in a way the generator cannot read." + }, + "403": { + "$ref": "#/components/responses/Error", + "description": "Refused by the engine's address, Origin or Host guards." }, "default": { "$ref": "#/components/responses/Error", "description": "Any other failure, in the same shape." } }, - "summary": "Refused (410 `payload_downloads_removed`)", + "summary": "The project's newest releases with `.elf` and `.bin` files, for picking the file", "tags": [ "payloads" ], @@ -28184,7 +28301,7 @@ }, "/api/payloads/repos/{id}": { "delete": { - "description": "DELETE /api/payloads/repos/{id} → {removed}", + "description": "DELETE /api/payloads/repos/{id} → {removed}: the source and its downloaded file.", "parameters": [ { "in": "path", @@ -28208,7 +28325,88 @@ "description": "Any other failure, in the same shape." } }, - "summary": "{removed}", + "summary": "{removed}: the source and its downloaded file", + "tags": [ + "payloads" + ], + "x-ps5upload": { + "access": "loopback", + "response_schema": "none" + } + } + }, + "/api/payloads/repos/{id}/download": { + "post": { + "description": "POST /api/payloads/repos/{id}/download → the source: downloads the newest release's file into\nthe payload folder (through a temporary file, checked against its size and the release's\nchecksum file when there is one). The copy it replaces stays if anything fails.", + "parameters": [ + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Success. The handler builds this answer in a way the generator cannot read." + }, + "403": { + "$ref": "#/components/responses/Error", + "description": "Refused by the engine's address, Origin or Host guards." + }, + "default": { + "$ref": "#/components/responses/Error", + "description": "Any other failure, in the same shape." + } + }, + "tags": [ + "payloads" + ], + "x-ps5upload": { + "access": "loopback", + "response_schema": "none" + } + } + }, + "/api/payloads/repos/{id}/file": { + "put": { + "description": "PUT /api/payloads/repos/{id}/file {file_name} → the source: change the file it downloads, or\npick it for a source added before 12.6.0.", + "parameters": [ + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/FileBody" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Success. The handler builds this answer in a way the generator cannot read." + }, + "403": { + "$ref": "#/components/responses/Error", + "description": "Refused by the engine's address, Origin or Host guards." + }, + "default": { + "$ref": "#/components/responses/Error", + "description": "Any other failure, in the same shape." + } + }, + "summary": "The source: change the file it downloads, or pick it for a source added before 12.6.0", "tags": [ "payloads" ], diff --git a/engine/crates/ps5upload-engine/src/ampr_index_api.rs b/engine/crates/ps5upload-engine/src/ampr_index_api.rs index 098e2a44e..aacf9471a 100644 --- a/engine/crates/ps5upload-engine/src/ampr_index_api.rs +++ b/engine/crates/ps5upload-engine/src/ampr_index_api.rs @@ -408,7 +408,7 @@ mod tests { use ps5upload_fpkg::source::FolderSource; fn scratch(tag: &str) -> PathBuf { - let root = std::env::temp_dir().join(format!( + let root = crate::test_tmp::temp_path(format!( "ps5upload-ampridx-{tag}-{}-{}", std::process::id(), Uuid::new_v4() diff --git a/engine/crates/ps5upload-engine/src/api_surface_tests.rs b/engine/crates/ps5upload-engine/src/api_surface_tests.rs index 8bb9bb1fd..14ad8e6a6 100644 --- a/engine/crates/ps5upload-engine/src/api_surface_tests.rs +++ b/engine/crates/ps5upload-engine/src/api_surface_tests.rs @@ -928,7 +928,7 @@ async fn every_name_for_the_console_works_on_the_routes_that_lacked_them() { #[tokio::test] async fn ps4_updates_and_addons_are_told_and_refused_in_words() { let app = app(); - let root = std::env::temp_dir().join(format!("ps5upload-ps4-kinds-{}", std::process::id())); + let root = crate::test_tmp::temp_path(format!("ps5upload-ps4-kinds-{}", std::process::id())); let _ = std::fs::remove_dir_all(&root); std::fs::create_dir_all(&root).unwrap(); let put = |name: &str, gz: &[u8]| { @@ -1032,7 +1032,7 @@ async fn ps4_updates_and_addons_are_told_and_refused_in_words() { #[tokio::test] async fn a_ps4_game_becomes_a_ps4_package() { let app = app(); - let root = std::env::temp_dir().join(format!("ps5upload-ps4-pkg-{}", std::process::id())); + let root = crate::test_tmp::temp_path(format!("ps5upload-ps4-pkg-{}", std::process::id())); let _ = std::fs::remove_dir_all(&root); std::fs::create_dir_all(&root).unwrap(); let put = |name: &str, gz: &[u8]| { @@ -1203,7 +1203,7 @@ async fn a_packed_game_packages_as_plain_files_without_its_emulator() { #[tokio::test] async fn a_folder_build_with_zstd_packs_takes_a_game_folder_and_refuses_what_cannot_work() { let app = app(); - let root = std::env::temp_dir().join(format!("ps5upload-zstd-req-{}", std::process::id())); + let root = crate::test_tmp::temp_path(format!("ps5upload-zstd-req-{}", std::process::id())); let _ = std::fs::remove_dir_all(&root); let game = root.join("PPSA99996-app"); std::fs::create_dir_all(game.join("sce_sys")).unwrap(); @@ -1321,7 +1321,7 @@ async fn job_end(st: &AppState, resp: HttpResponse) -> JobState { async fn lz4_packs_go_into_a_folder_and_any_image() { let st = state(); let app = app_with(st.clone(), Default::default(), ""); - let root = std::env::temp_dir().join(format!("ps5upload-api-lz4-{}", std::process::id())); + let root = crate::test_tmp::temp_path(format!("ps5upload-api-lz4-{}", std::process::id())); let _ = std::fs::remove_dir_all(&root); let game = lz4_game(&root); let out = root.join("out"); @@ -1428,7 +1428,7 @@ async fn lz4_packs_go_straight_to_a_server() { .id; let st = state(); let app = app_with(st.clone(), Default::default(), ""); - let root = std::env::temp_dir().join(format!("ps5upload-api-lz4srv-{}", std::process::id())); + let root = crate::test_tmp::temp_path(format!("ps5upload-api-lz4srv-{}", std::process::id())); let _ = std::fs::remove_dir_all(&root); let game = lz4_game(&root); let out = root.join("never"); @@ -1525,7 +1525,7 @@ async fn an_image_and_a_folder_go_straight_to_a_server() { .id; let st = state(); let app = app_with(st.clone(), Default::default(), ""); - let root = std::env::temp_dir().join(format!("ps5upload-api-toserver-{}", std::process::id())); + let root = crate::test_tmp::temp_path(format!("ps5upload-api-toserver-{}", std::process::id())); let _ = std::fs::remove_dir_all(&root); let game = root.join("PPSA99995-app"); std::fs::create_dir_all(game.join("sce_sys")).unwrap(); diff --git a/engine/crates/ps5upload-engine/src/archive_build_tests.rs b/engine/crates/ps5upload-engine/src/archive_build_tests.rs index b177492db..5584b6768 100644 --- a/engine/crates/ps5upload-engine/src/archive_build_tests.rs +++ b/engine/crates/ps5upload-engine/src/archive_build_tests.rs @@ -32,7 +32,7 @@ fn state() -> (AppState, Jobs) { } fn root(tag: &str) -> PathBuf { - let r = std::env::temp_dir().join(format!("ps5u-archive-build-{tag}-{}", std::process::id())); + let r = crate::test_tmp::temp_path(format!("ps5u-archive-build-{tag}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&r); std::fs::create_dir_all(&r).unwrap(); r diff --git a/engine/crates/ps5upload-engine/src/archive_free.rs b/engine/crates/ps5upload-engine/src/archive_free.rs index c642a7360..f035b08c2 100644 --- a/engine/crates/ps5upload-engine/src/archive_free.rs +++ b/engine/crates/ps5upload-engine/src/archive_free.rs @@ -349,7 +349,7 @@ mod tests { fn plan_of(mode: free::FreeMode, archive: u64, unpacked: u64, peak: u64) -> free::FreePlan { // A real plan of a small zip, with the figures under test put in. - let dir = std::env::temp_dir().join(format!( + let dir = crate::test_tmp::temp_path(format!( "ps5u-free-room-{}-{}", std::process::id(), uuid::Uuid::new_v4() @@ -433,7 +433,7 @@ mod tests { #[test] fn a_kept_folder_is_known_by_any_path_in_it_and_gets_a_name_of_its_own() { - let base = std::env::temp_dir().join(format!("ps5u-kept-{}", uuid::Uuid::new_v4())); + let base = crate::test_tmp::temp_path(format!("ps5u-kept-{}", uuid::Uuid::new_v4())); std::fs::create_dir_all(&base).unwrap(); let first = kept_dest(&base, Path::new("/dl/Game.part1.rar")); assert_eq!(first, base.join("Game.unpacked")); diff --git a/engine/crates/ps5upload-engine/src/ava1_only_tests.rs b/engine/crates/ps5upload-engine/src/ava1_only_tests.rs index ed8b40745..24e4ab186 100644 --- a/engine/crates/ps5upload-engine/src/ava1_only_tests.rs +++ b/engine/crates/ps5upload-engine/src/ava1_only_tests.rs @@ -40,7 +40,7 @@ fn state_for(jobs: &Arc>>) -> AppState { /// retries and not by trying another protocol. #[tokio::test(flavor = "multi_thread")] async fn no_ava1_listener_surfaces_helper_not_running() { - let dir = std::env::temp_dir().join(format!("p5-ava1only-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("p5-ava1only-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let src = dir.join("one.bin"); std::fs::write(&src, b"hello").unwrap(); @@ -89,7 +89,7 @@ async fn assert_helper_not_ava1(jobs: &Arc>>) { #[tokio::test(flavor = "multi_thread")] async fn transfer_dir_with_no_ava1_listener_is_helper_not_ava1() { - let dir = std::env::temp_dir().join(format!("p5-ava1only-dir-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("p5-ava1only-dir-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); std::fs::write(dir.join("a.bin"), b"hello").unwrap(); let jobs: Arc>> = Arc::new(Mutex::new(HashMap::new())); @@ -122,7 +122,7 @@ fn tiny_zip(path: &std::path::Path) { #[tokio::test(flavor = "multi_thread")] async fn transfer_zip_with_no_ava1_listener_is_helper_not_ava1() { - let dir = std::env::temp_dir().join(format!("p5-ava1only-zip-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("p5-ava1only-zip-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let zp = dir.join("g.zip"); tiny_zip(&zp); @@ -145,7 +145,7 @@ async fn transfer_zip_with_no_ava1_listener_is_helper_not_ava1() { #[tokio::test(flavor = "multi_thread")] async fn transfer_7z_with_no_ava1_listener_is_helper_not_ava1() { - let dir = std::env::temp_dir().join(format!("p5-ava1only-7z-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("p5-ava1only-7z-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let ap = dir.join("g.7z"); { @@ -177,7 +177,7 @@ async fn transfer_7z_with_no_ava1_listener_is_helper_not_ava1() { #[tokio::test(flavor = "multi_thread")] async fn transfer_tar_with_no_ava1_listener_is_helper_not_ava1() { - let dir = std::env::temp_dir().join(format!("p5-ava1only-tar-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("p5-ava1only-tar-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); // A lone .zst by hand: one single-segment frame, content size 5, one raw block "hello". let ap = dir.join("a.txt.zst"); @@ -235,7 +235,7 @@ async fn transfer_rar_with_no_ava1_listener_is_helper_not_ava1() { #[tokio::test(flavor = "multi_thread")] async fn transfer_file_list_with_no_ava1_listener_is_helper_not_ava1() { - let dir = std::env::temp_dir().join(format!("p5-ava1only-fl-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("p5-ava1only-fl-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); std::fs::write(dir.join("a.bin"), b"hello").unwrap(); let jobs: Arc>> = Arc::new(Mutex::new(HashMap::new())); @@ -261,7 +261,7 @@ async fn transfer_file_list_with_no_ava1_listener_is_helper_not_ava1() { /// success with the file simply absent (R2-1 F25). #[tokio::test(flavor = "multi_thread")] async fn transfer_file_list_names_the_files_it_could_not_read() { - let dir = std::env::temp_dir().join(format!("p5-ava1only-fl-skip-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("p5-ava1only-fl-skip-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); std::fs::write(dir.join("a.bin"), b"hello").unwrap(); let missing = dir.join("gone.bin").to_string_lossy().into_owned(); @@ -300,7 +300,7 @@ async fn transfer_file_list_names_the_files_it_could_not_read() { #[tokio::test(flavor = "multi_thread")] async fn transfer_dir_reconcile_with_no_ava1_listener_is_helper_not_ava1() { - let dir = std::env::temp_dir().join(format!("p5-ava1only-rc-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("p5-ava1only-rc-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); std::fs::write(dir.join("a.bin"), b"hello").unwrap(); let jobs: Arc>> = Arc::new(Mutex::new(HashMap::new())); @@ -323,7 +323,7 @@ async fn transfer_dir_reconcile_with_no_ava1_listener_is_helper_not_ava1() { #[tokio::test(flavor = "multi_thread")] async fn transfer_download_with_no_ava1_listener_is_helper_not_ava1() { - let dir = std::env::temp_dir().join(format!("p5-ava1only-dl-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("p5-ava1only-dl-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let jobs: Arc>> = Arc::new(Mutex::new(HashMap::new())); let req = TransferDownloadReq { @@ -333,6 +333,7 @@ async fn transfer_download_with_no_ava1_listener_is_helper_not_ava1() { kind: "file".to_string(), unsafe_read: false, escape_names: false, + remove_source: false, }; let resp = transfer_download_handler(State(state_for(&jobs)), Json(req)) .await @@ -346,7 +347,7 @@ async fn transfer_download_with_no_ava1_listener_is_helper_not_ava1() { /// download keeps names (`escape_names`, the saves code): then it starts. #[tokio::test(flavor = "multi_thread")] async fn transfer_download_takes_a_name_windows_refuses_only_when_keeping_names() { - let dir = std::env::temp_dir().join(format!("p5-ava1only-kept-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("p5-ava1only-kept-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); for src in ["/data/x/options\\gabindings.xml", "/data/x/CON"] { for escape_names in [false, true] { @@ -358,6 +359,7 @@ async fn transfer_download_takes_a_name_windows_refuses_only_when_keeping_names( kind: "file".to_string(), unsafe_read: false, escape_names, + remove_source: false, }; let resp = transfer_download_handler(State(state_for(&jobs)), Json(req)) .await @@ -373,9 +375,39 @@ async fn transfer_download_takes_a_name_windows_refuses_only_when_keeping_names( let _ = std::fs::remove_dir_all(&dir); } +/// #953: a move off the console (`remove_source`) goes only to a saved server, never takes a +/// drive or a top folder as a whole, and never rides on `unsafe_read`; each is refused up front. +#[tokio::test(flavor = "multi_thread")] +async fn transfer_download_refuses_a_move_it_should_not_make() { + let cases = [ + ("/data/x", "/tmp/somewhere", false), + ("/data", "remote://abc/games", false), + ("/mnt/usb0", "remote://abc/games", false), + ("/mnt/usb0/", "remote://abc/games", false), + ("/data/x", "remote://abc/games", true), + ]; + for (src, dest, unsafe_read) in cases { + let jobs: Arc>> = Arc::new(Mutex::new(HashMap::new())); + let req = TransferDownloadReq { + addr: Some("127.0.0.1:9113".to_string()), + src_path: src.to_string(), + dest_dir: dest.to_string(), + kind: "folder".to_string(), + unsafe_read, + escape_names: false, + remove_source: true, + }; + let resp = transfer_download_handler(State(state_for(&jobs)), Json(req)) + .await + .into_response(); + assert_eq!(resp.status(), StatusCode::BAD_REQUEST, "{src} -> {dest}"); + assert!(jobs.lock().unwrap().is_empty(), "{src}: no job starts"); + } +} + #[tokio::test(flavor = "multi_thread")] async fn transfer_download_zip_with_no_ava1_listener_is_helper_not_ava1() { - let dir = std::env::temp_dir().join(format!("p5-ava1only-dz-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("p5-ava1only-dz-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let jobs: Arc>> = Arc::new(Mutex::new(HashMap::new())); let req = TransferDownloadZipReq { @@ -399,7 +431,7 @@ async fn transfer_download_zip_with_no_ava1_listener_is_helper_not_ava1() { /// gone without a word. The person has to have chosen that (the save dialog asks; a script says so). #[tokio::test(flavor = "multi_thread")] async fn transfer_download_zip_refuses_an_existing_archive_unless_told_to_replace_it() { - let dir = std::env::temp_dir().join(format!("p5-dz-existing-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("p5-dz-existing-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let zip = dir.join("x.zip"); std::fs::write(&zip, b"an earlier backup").unwrap(); @@ -771,7 +803,7 @@ fn engine_does_not_read_console_files_through_ftpsrv() { /// and the record holds neither the source path nor the console's address. #[test] fn a_failed_transfer_leaves_a_record_with_no_local_path_and_no_address() { - let dir = std::env::temp_dir().join(format!("p5-ava1only-telem-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("p5-ava1only-telem-{}", std::process::id())); let src_dir = dir.join("Secret Games Folder"); std::fs::create_dir_all(&src_dir).unwrap(); let src = src_dir.join("one.bin"); diff --git a/engine/crates/ps5upload-engine/src/browser_payload.rs b/engine/crates/ps5upload-engine/src/browser_payload.rs index 177150d50..5c36d4ea7 100644 --- a/engine/crates/ps5upload-engine/src/browser_payload.rs +++ b/engine/crates/ps5upload-engine/src/browser_payload.rs @@ -627,7 +627,7 @@ mod tests { #[tokio::test] async fn the_json_form_sends_a_file_from_a_path() { - let dir = std::env::temp_dir().join(format!("ps5upload-send-api-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("ps5upload-send-api-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let file = dir.join("thing.elf"); std::fs::write(&file, b"\x7fELFfrom a path").unwrap(); @@ -648,7 +648,7 @@ mod tests { #[tokio::test] async fn the_json_form_accepts_the_other_names_for_the_console() { let (port, received) = listen_once(); - let dir = std::env::temp_dir().join(format!("ps5upload-send-api2-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("ps5upload-send-api2-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let file = dir.join("a.bin"); std::fs::write(&file, b"x").unwrap(); @@ -818,7 +818,7 @@ mod tests { /// own one in place of a damaged copy, and never a file that is not named .elf. #[test] fn the_bundled_form_takes_a_good_copy_and_replaces_a_damaged_one() { - let dir = std::env::temp_dir().join(format!("ps5upload-bundled-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("ps5upload-bundled-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let good = dir.join("ps5upload.elf"); std::fs::write(&good, b"\x7fELF the app's helper").unwrap(); diff --git a/engine/crates/ps5upload-engine/src/collection/junk.rs b/engine/crates/ps5upload-engine/src/collection/junk.rs index 895ac4c1d..f4ceb1cb8 100644 --- a/engine/crates/ps5upload-engine/src/collection/junk.rs +++ b/engine/crates/ps5upload-engine/src/collection/junk.rs @@ -175,7 +175,7 @@ mod tests { use super::*; fn tmp(name: &str) -> PathBuf { - let d = std::env::temp_dir().join(format!("ps5u-junk-{name}-{}", std::process::id())); + let d = crate::test_tmp::temp_path(format!("ps5u-junk-{name}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&d); std::fs::create_dir_all(&d).unwrap(); d diff --git a/engine/crates/ps5upload-engine/src/collection/organize.rs b/engine/crates/ps5upload-engine/src/collection/organize.rs index f5cda1f53..d279292b2 100644 --- a/engine/crates/ps5upload-engine/src/collection/organize.rs +++ b/engine/crates/ps5upload-engine/src/collection/organize.rs @@ -1714,7 +1714,7 @@ mod tests { } fn lib(name: &str) -> Lib { - let d = std::env::temp_dir().join(format!("ps5u-org-{name}-{}", std::process::id())); + let d = crate::test_tmp::temp_path(format!("ps5u-org-{name}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&d); std::fs::create_dir_all(d.join("fpkg")).unwrap(); Lib(d) diff --git a/engine/crates/ps5upload-engine/src/collection/organize_fs.rs b/engine/crates/ps5upload-engine/src/collection/organize_fs.rs index fdd16503e..d9888815b 100644 --- a/engine/crates/ps5upload-engine/src/collection/organize_fs.rs +++ b/engine/crates/ps5upload-engine/src/collection/organize_fs.rs @@ -681,7 +681,7 @@ mod tests { .unwrap() .conn .id; - let logs = std::env::temp_dir().join(format!("ps5u-rorg-{name}-{}", std::process::id())); + let logs = crate::test_tmp::temp_path(format!("ps5u-rorg-{name}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&logs); Server { mem, diff --git a/engine/crates/ps5upload-engine/src/collection/scan.rs b/engine/crates/ps5upload-engine/src/collection/scan.rs index 33491722c..3f84651cb 100644 --- a/engine/crates/ps5upload-engine/src/collection/scan.rs +++ b/engine/crates/ps5upload-engine/src/collection/scan.rs @@ -915,7 +915,7 @@ mod tests { } fn tmp(tag: &str) -> PathBuf { - let d = std::env::temp_dir().join(format!("ps5upload-coll-{tag}-{}", std::process::id())); + let d = crate::test_tmp::temp_path(format!("ps5upload-coll-{tag}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&d); std::fs::create_dir_all(&d).unwrap(); d @@ -1361,7 +1361,9 @@ mod tests { "Game", "01.000.000", ); - let gone = s(&std::env::temp_dir().join("ps5upload-coll-never-there-461")); + let gone = s(&crate::test_tmp::temp_path( + "ps5upload-coll-never-there-461", + )); let mut prev = Library::default(); let kept = PkgCacheEntry::default(); prev.pkg_cache.insert(format!("{gone}|a.pkg"), kept.clone()); diff --git a/engine/crates/ps5upload-engine/src/collection/store.rs b/engine/crates/ps5upload-engine/src/collection/store.rs index 1e2a7fe80..91855060d 100644 --- a/engine/crates/ps5upload-engine/src/collection/store.rs +++ b/engine/crates/ps5upload-engine/src/collection/store.rs @@ -295,7 +295,7 @@ mod tests { /// A settings file that does not read is kept, not left where the next save writes over it. #[test] fn a_settings_file_that_does_not_read_is_kept_aside() { - let dir = std::env::temp_dir().join(format!("ps5u-coll-settings-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("ps5u-coll-settings-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); std::fs::write(dir.join("settings.json"), br#"{"roots": 5}"#).unwrap(); @@ -346,7 +346,7 @@ mod tests { /// those fields is new since: it must read as empty, and a save must not grow it for nothing. #[test] fn an_older_index_still_loads() { - let dir = std::env::temp_dir().join(format!("ps5u-old-index-{}", uuid::Uuid::new_v4())); + let dir = crate::test_tmp::temp_path(format!("ps5u-old-index-{}", uuid::Uuid::new_v4())); std::fs::create_dir_all(&dir).unwrap(); std::fs::write( dir.join("index.json"), diff --git a/engine/crates/ps5upload-engine/src/collection_api.rs b/engine/crates/ps5upload-engine/src/collection_api.rs index ae61ef4fc..4e124077a 100644 --- a/engine/crates/ps5upload-engine/src/collection_api.rs +++ b/engine/crates/ps5upload-engine/src/collection_api.rs @@ -1127,7 +1127,7 @@ mod cover_tests { #[test] fn a_thumbnail_is_made_once_and_again_when_the_cover_changes() { let dir = - std::env::temp_dir().join(format!("ps5upload-cover-thumb-{}", std::process::id())); + crate::test_tmp::temp_path(format!("ps5upload-cover-thumb-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let cover = dir.join("PPSA01234.png"); std::fs::write(&cover, png(512, 10)).unwrap(); @@ -1154,7 +1154,7 @@ mod cover_tests { #[test] fn a_small_cover_has_no_thumbnail() { let dir = - std::env::temp_dir().join(format!("ps5upload-cover-small-{}", std::process::id())); + crate::test_tmp::temp_path(format!("ps5upload-cover-small-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let cover = dir.join("PPSA00001.png"); std::fs::write(&cover, png(64, 1)).unwrap(); diff --git a/engine/crates/ps5upload-engine/src/collection_check_api.rs b/engine/crates/ps5upload-engine/src/collection_check_api.rs index 7e9e440d3..5a12257d4 100644 --- a/engine/crates/ps5upload-engine/src/collection_check_api.rs +++ b/engine/crates/ps5upload-engine/src/collection_check_api.rs @@ -108,8 +108,15 @@ pub struct CheckStatus { pub state: String, /// `package`, `archive`, `files` or `bytes`: see the module docs. pub method: String, + /// Of every pass together: a package's full check reads it twice (its blocks, then the + /// PlayGo chunk CRCs), and both count here, so `bytes_done` reaches `bytes_total` only at + /// the end (#951). pub bytes_done: u64, pub bytes_total: u64, + /// For `method` `package` while it runs: `blocks` (every block against its digest) or + /// `playgo` (the PlayGo chunk CRCs, a second read of the package). Absent otherwise. + #[serde(skip_serializing_if = "String::is_empty")] + pub phase: String, pub files_done: u64, pub files_total: u64, pub problems: Vec, @@ -365,12 +372,17 @@ fn package(job: &Job, path: &Path) -> Result { s.bytes_total = total; }); }; - match ps5upload_fpkg::verify::verify_streaming_cancellable( + let mut phase = |p: ps5upload_fpkg::verify::Phase| job.update(|s| s.phase = p.as_str().into()); + let verified = ps5upload_fpkg::verify::verify_streaming_phased( path, ps5upload_fpkg::crypto::DEFAULT_PASSCODE, &job.cancel, &mut progress, - ) { + &mut phase, + ); + // A pass names a running check only. + job.update(|s| s.phase.clear()); + match verified { // A retail package got as far as a report: its blocks can't be read with a debug // key, so "every block fails" would be about the key, not the file. Ok(report) if !report.is_debug() => { @@ -698,7 +710,7 @@ mod tests { struct Scratch(std::path::PathBuf); impl Scratch { fn new(tag: &str) -> Self { - let d = std::env::temp_dir().join(format!("ps5u-check-{tag}-{}", std::process::id())); + let d = crate::test_tmp::temp_path(format!("ps5u-check-{tag}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&d); std::fs::create_dir_all(&d).unwrap(); Scratch(d) @@ -827,6 +839,32 @@ mod tests { s } + /// #951: the PlayGo CRC pass counts in the check's total (a 200 GB package showed 100% + /// through a whole second read), and a finished check names no pass. + #[test] + fn a_package_check_counts_both_passes_and_ends_with_no_phase() { + let t = Scratch::new("phases"); + let pkg = debug_package(t.path()); + let mut f = ps5upload_fpkg::PkgFile::open(&pkg).unwrap(); + let zip_start = ps5upload_fpkg::si::read(&mut f) + .unwrap() + .expect("an SI ZIP") + .zip_start; + drop(f); + let s = checked(&pkg); + assert_eq!(s.method, "package"); + assert_eq!(s.problems_total, 0, "{:?}", s.problems); + assert_eq!(s.bytes_done, s.bytes_total); + // Both reads: the image's blocks and everything before the SI ZIP again. + assert!( + s.bytes_total > zip_start, + "{} vs {zip_start}", + s.bytes_total + ); + assert!(s.phase.is_empty()); + assert!(!serde_json::to_string(&s).unwrap().contains("\"phase\"")); + } + /// The three things a package check can tell apart, each with what the screen needs to /// say it in plain words: damaged data (how many blocks of how many), a file cut short /// (how long it is and has to be), and only the package's own information not matching. diff --git a/engine/crates/ps5upload-engine/src/collection_tidy_api.rs b/engine/crates/ps5upload-engine/src/collection_tidy_api.rs index 75c6cf739..6023689c8 100644 --- a/engine/crates/ps5upload-engine/src/collection_tidy_api.rs +++ b/engine/crates/ps5upload-engine/src/collection_tidy_api.rs @@ -1814,7 +1814,7 @@ mod tests { } fn scratch(tag: &str) -> PathBuf { - let d = std::env::temp_dir().join(format!("ps5u-trash-{tag}-{}", uuid::Uuid::new_v4())); + let d = crate::test_tmp::temp_path(format!("ps5u-trash-{tag}-{}", uuid::Uuid::new_v4())); std::fs::create_dir_all(&d).unwrap(); d } @@ -1928,7 +1928,7 @@ mod tests { #[test] fn a_permanent_delete_takes_a_file_or_a_whole_folder_and_never_follows_a_link() { - let d = std::env::temp_dir().join(format!("ps5u-del-{}", std::process::id())); + let d = crate::test_tmp::temp_path(format!("ps5u-del-{}", std::process::id())); let _ = std::fs::remove_dir_all(&d); std::fs::create_dir_all(d.join("Game-app/sce_sys")).unwrap(); std::fs::write(d.join("Game-app/sce_sys/param.json"), b"{}").unwrap(); @@ -1966,7 +1966,7 @@ mod tests { #[test] fn same_named_folders_get_their_own_undo_logs() { - let d = std::env::temp_dir().join(format!("ps5u-logs-{}", std::process::id())); + let d = crate::test_tmp::temp_path(format!("ps5u-logs-{}", std::process::id())); let _ = std::fs::remove_dir_all(&d); std::fs::create_dir_all(&d).unwrap(); let a = unique_log_base(&d, "organize_1_fpkg"); @@ -1989,7 +1989,7 @@ mod tests { .id; let root = format!("remote://{id}/games/fpkg"); let now = origin_of(FsPath::new(&root)).unwrap(); - let d = std::env::temp_dir().join(format!("ps5u-place-{}", std::process::id())); + let d = crate::test_tmp::temp_path(format!("ps5u-place-{}", std::process::id())); std::fs::create_dir_all(&d).unwrap(); let log = |origin: Option, root: &str| { let p = d.join(format!("organize_{}.json", uuid::Uuid::new_v4())); diff --git a/engine/crates/ps5upload-engine/src/console_backup.rs b/engine/crates/ps5upload-engine/src/console_backup.rs index 313d60703..9a6296c8a 100644 --- a/engine/crates/ps5upload-engine/src/console_backup.rs +++ b/engine/crates/ps5upload-engine/src/console_backup.rs @@ -958,7 +958,7 @@ mod tests { #[test] fn logs_and_temporary_files_are_left_out_and_the_rest_kept() { - let dir = std::env::temp_dir().join(format!("cb-prune-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("cb-prune-{}", std::process::id())); std::fs::create_dir_all(dir.join("sub")).unwrap(); for f in ["config.ini", "debug.log", "sub/x.tmp", "sub/keep.bin"] { std::fs::write(dir.join(f), b"x").unwrap(); @@ -1014,7 +1014,7 @@ mod tests { #[test] fn a_manifest_comes_back_as_written_and_a_newer_one_is_refused() { - let dir = std::env::temp_dir().join(format!("cb-manifest-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("cb-manifest-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let m = Manifest { format: FORMAT, diff --git a/engine/crates/ps5upload-engine/src/console_snapshot.rs b/engine/crates/ps5upload-engine/src/console_snapshot.rs index 09176ddf0..a8eb504b7 100644 --- a/engine/crates/ps5upload-engine/src/console_snapshot.rs +++ b/engine/crates/ps5upload-engine/src/console_snapshot.rs @@ -422,7 +422,7 @@ mod tests { #[test] fn round_trip_and_corrupt_file() { - let dir = std::env::temp_dir().join(format!("ps5u-snap-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("ps5u-snap-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let file = dir.join("console-snapshots.json"); let mut s = Snapshots::new(); diff --git a/engine/crates/ps5upload-engine/src/convert_cli.rs b/engine/crates/ps5upload-engine/src/convert_cli.rs index becbabf79..f597f2b6f 100644 --- a/engine/crates/ps5upload-engine/src/convert_cli.rs +++ b/engine/crates/ps5upload-engine/src/convert_cli.rs @@ -830,7 +830,7 @@ mod tests { /// image route's own handler and job, and the image holds the folder's files. #[tokio::test] async fn a_game_folder_converts_to_a_verified_image() { - let root = std::env::temp_dir().join(format!("convert-cli-{}", Uuid::new_v4())); + let root = crate::test_tmp::temp_path(format!("convert-cli-{}", Uuid::new_v4())); let (game, out) = (root.join("PPSA01234"), root.join("out")); tiny_game(&game); diff --git a/engine/crates/ps5upload-engine/src/convert_source.rs b/engine/crates/ps5upload-engine/src/convert_source.rs index 87ae6f35b..55ffc9b15 100644 --- a/engine/crates/ps5upload-engine/src/convert_source.rs +++ b/engine/crates/ps5upload-engine/src/convert_source.rs @@ -161,7 +161,7 @@ mod tests { .id; register(); let url = format!("remote://{id}/fpkg-remote/mini.exfat"); - let out = std::env::temp_dir().join(format!("fpkg-remote-build-{}", std::process::id())); + let out = crate::test_tmp::temp_path(format!("fpkg-remote-build-{}", std::process::id())); let _ = std::fs::remove_dir_all(&out); let (u, o) = (url.clone(), out.clone()); let report = tokio::task::spawn_blocking(move || { @@ -325,7 +325,7 @@ mod tests { ]); register(); let url = "ps5://192.0.2.99/data/games/mini.exfat".to_string(); - let out = std::env::temp_dir().join(format!("fpkg-console-build-{}", std::process::id())); + let out = crate::test_tmp::temp_path(format!("fpkg-console-build-{}", std::process::id())); let _ = std::fs::remove_dir_all(&out); let (c, o) = (console.clone(), out.clone()); let report = tokio::task::spawn_blocking(move || { @@ -470,7 +470,7 @@ mod tests { ps5upload_ava1::mgmt::install(); register(); let url = format!("ps5://{host}{path}"); - let out = std::env::temp_dir().join(format!("fpkg-live-{}", std::process::id())); + let out = crate::test_tmp::temp_path(format!("fpkg-live-{}", std::process::id())); let _ = std::fs::remove_dir_all(&out); let o = out.clone(); let started = std::time::Instant::now(); diff --git a/engine/crates/ps5upload-engine/src/download_relay.rs b/engine/crates/ps5upload-engine/src/download_relay.rs index 665a4b53c..86d7f1672 100644 --- a/engine/crates/ps5upload-engine/src/download_relay.rs +++ b/engine/crates/ps5upload-engine/src/download_relay.rs @@ -28,18 +28,22 @@ pub fn is_server_dest(dest: &str) -> bool { /// A file on the console: its path, its path relative to the root's parent, its size. type ConsoleFile = (String, String, u64); +/// A source as the console lists it: its files, its folders, and what a relay leaves out +/// (links and other special entries, relative like the rest): a move keeps a source with any. +type Listing = (Vec, Vec, Vec); + /// Every file under `root` on the console, and every folder (relative to `root`'s parent, the /// root itself first among them): a folder with no file in it is made on the server too. -fn console_files( - addr: &str, - root: &str, - kind: DownloadKind, -) -> Result<(Vec, Vec)> { +fn console_files(addr: &str, root: &str, kind: DownloadKind) -> Result { let root = root.trim_end_matches('/'); if matches!(kind, DownloadKind::File) { let base = root.rsplit('/').next().unwrap_or(root).to_string(); let st = fs_ops::fs_stat(addr, root)?; - return Ok((vec![(root.to_string(), base, st.size)], Vec::new())); + return Ok(( + vec![(root.to_string(), base, st.size)], + Vec::new(), + Vec::new(), + )); } walk_console(root, |dir, offset| { let l = fs_ops::list_dir(addr, dir, ListDirOptions { offset, limit: 256 })?; @@ -57,10 +61,11 @@ fn console_files( fn walk_console( root: &str, mut list: impl FnMut(&str, u64) -> Result<(Vec<(String, String, u64)>, bool)>, -) -> Result<(Vec, Vec)> { +) -> Result { let base = root.rsplit('/').next().unwrap_or(root).to_string(); let mut out = Vec::new(); let mut dirs = Vec::new(); + let mut skipped = Vec::new(); let mut stack = vec![(root.to_string(), base)]; while let Some((dir, rel)) = stack.pop() { dirs.push(rel.clone()); @@ -80,7 +85,8 @@ fn walk_console( match kind.as_str() { "dir" => stack.push((path, r)), "file" => out.push((path, r, size)), - _ => {} + // A link, a device…: never copied, so a move must not delete it. + _ => skipped.push(r), } } if n == 0 || (n < 256 && !truncated) { @@ -91,7 +97,8 @@ fn walk_console( } out.sort_by(|a, b| a.1.cmp(&b.1)); dirs.sort(); - Ok((out, dirs)) + skipped.sort(); + Ok((out, dirs, skipped)) } fn remote_err(e: RemoteError) -> anyhow::Error { @@ -160,7 +167,103 @@ fn staged_name(console_path: &str) -> Result { ps5upload_core::host_names::escape_name(name).map_err(|why| anyhow!(why)) } +/// The console end of a relay: what is copied, how one file comes off it, and (for a move) how +/// the source goes. A trait so the tests can stand a folder on this computer in for the console. +pub(crate) trait ConsoleSide { + /// Every file and folder under the source, as [`console_files`] lists them. + fn files(&self) -> Result; + /// Pulls the console file `path` into `staging`, under [`staged_name`], counting into `dl`. + fn pull( + &self, + path: &str, + staging: &Path, + dl: &ps5upload_ava1::download::Counters, + cancel: &Arc, + ) -> Result<()>; + /// Deletes the source (the file, or the whole folder tree) on the console. + fn delete(&self) -> Result<()>; +} + +/// The console itself, over AVA1. +struct Ava1Console<'a> { + addr: &'a str, + src: &'a str, + kind: DownloadKind, + unsafe_read: bool, +} + +impl ConsoleSide for Ava1Console<'_> { + fn files(&self) -> Result { + console_files(self.addr, self.src, self.kind) + } + + fn pull( + &self, + path: &str, + staging: &Path, + dl: &ps5upload_ava1::download::Counters, + cancel: &Arc, + ) -> Result<()> { + let id: [u8; 16] = ava1::keys::random_bytes()?; + // Staged under a name this computer can hold whatever the console's is (`a:b`, `CON`, + // `x.` on Windows): the server gets the console's own name, and it is the server, not + // this computer's staging folder, that says whether it can hold it. + ps5upload_ava1::download::to_local_escaped( + self.addr, + path, + DownloadKind::File, + staging, + self.unsafe_read, + id, + dl, + Some(Arc::clone(cancel)), + ) + .map(|_| ()) + } + + fn delete(&self) -> Result<()> { + // As the Files delete does: never from under a game that is running from it. + if let Some(title) = crate::running_title_from(self.addr, self.src) { + bail!( + "{title} is running from {}. Close it first: {KEPT}.", + self.src + ); + } + // A whole game folder takes minutes to delete (see the fs_delete route's deadline). + fs_ops::fs_delete_with_op_id(self.addr, self.src, 0, Some(Duration::from_secs(60 * 60))) + } +} + +/// How a move that stopped short ends its message. +const KEPT: &str = "the original was kept on the PS5"; + +/// Whether `src` may be moved off the console: never a drive or a top folder (`/data`, +/// `/mnt/usb0`) as a whole, whose delete would take every other file on it along. +pub fn movable_source(src: &str) -> bool { + let parts: Vec<&str> = src.split('/').filter(|p| !p.is_empty()).collect(); + if !src.starts_with('/') || parts.iter().any(|p| *p == "." || *p == "..") { + return false; + } + match parts.first() { + Some(&"mnt") => parts.len() > 2, + Some(_) => parts.len() > 1, + None => false, + } +} + +/// What a relay put on the server: every file (console path, path under `dest_dir`, size) and +/// every folder, as the console listed them. +pub(crate) struct Relayed { + bytes: u64, + dest_dir: String, + files: Vec, + dirs: Vec, + skipped: Vec, +} + /// Pulls `src` (a file or a folder) from the console at `addr` into `dest` (`remote://id/dir`). +/// With `remove_source` it is a move: the copy is checked on the server and the source deleted +/// only then ([`finish_move`]); a failed or cancelled copy leaves the source as it was. /// Returns the bytes delivered. #[allow(clippy::too_many_arguments)] pub fn to_server( @@ -169,6 +272,7 @@ pub fn to_server( kind: DownloadKind, dest: &str, unsafe_read: bool, + remove_source: bool, counters: &ps5upload_ava1::download::Counters, cancel: Arc, staging_root: &Path, @@ -179,7 +283,54 @@ pub fn to_server( let fs = rt .block_on(r.pool.fs(&r.store, &rp.connection_id)) .map_err(remote_err)?; - let (files, dirs) = console_files(addr, src, kind)?; + let console = Ava1Console { + addr, + src, + kind, + unsafe_read, + }; + copy_or_move( + &rt, + fs.as_ref(), + &console, + &rp.path, + remove_source, + counters, + &cancel, + staging_root, + ) +} + +/// [`to_server`] past its setup: the relay, then for a move [`finish_move`]. The bytes delivered. +#[allow(clippy::too_many_arguments)] +pub(crate) fn copy_or_move( + rt: &tokio::runtime::Handle, + fs: &dyn RemoteFs, + console: &dyn ConsoleSide, + dest_dir: &str, + remove_source: bool, + counters: &ps5upload_ava1::download::Counters, + cancel: &Arc, + staging_root: &Path, +) -> Result { + let done = relay(rt, fs, console, dest_dir, counters, cancel, staging_root)?; + if remove_source { + finish_move(rt, fs, console, &done, cancel)?; + } + Ok(done.bytes) +} + +/// The copy of [`to_server`]: every folder made, every file staged here and placed on the server. +pub(crate) fn relay( + rt: &tokio::runtime::Handle, + fs: &dyn RemoteFs, + console: &dyn ConsoleSide, + dest_dir: &str, + counters: &ps5upload_ava1::download::Counters, + cancel: &Arc, + staging_root: &Path, +) -> Result { + let (files, dirs, skipped) = console.files()?; let total: u64 = files.iter().map(|f| f.2).sum(); if let Some(t) = &counters.total { t.store(total.max(1), Ordering::Relaxed); @@ -188,8 +339,8 @@ pub fn to_server( let staging: PathBuf = staging_root.join(job.iter().map(|b| format!("{b:02x}")).collect::()); std::fs::create_dir_all(&staging).with_context(|| format!("make {}", staging.display()))?; + let dest_dir = dest_dir.trim_end_matches('/').to_string(); let result = (|| -> Result { - let dest_dir = rp.path.trim_end_matches('/').to_string(); let mut made = std::collections::HashSet::new(); let mut done = 0u64; // Every folder, so one with nothing in it is on the server as it is on the console. @@ -198,7 +349,7 @@ pub fn to_server( bail!("transfer_cancelled"); } let dir = format!("{dest_dir}/{rel}"); - rt.block_on(make_dirs(fs.as_ref(), &dir))?; + rt.block_on(make_dirs(fs, &dir))?; made.insert(dir); } for (path, rel, size) in &files { @@ -208,7 +359,7 @@ pub fn to_server( let target = format!("{dest_dir}/{rel}"); if let Some((parent, _)) = target.rsplit_once('/') { if !parent.is_empty() && made.insert(parent.to_string()) { - rt.block_on(make_dirs(fs.as_ref(), parent))?; + rt.block_on(make_dirs(fs, parent))?; } } // 1. Off the console, into staging (half of this file's share of the bar). @@ -216,8 +367,6 @@ pub fn to_server( let dl_bytes = Arc::clone(&dl.bytes); let shown = Arc::clone(&counters.bytes); let base = done; - // Before the progress thread starts: an early return must not leave it running. - let id: [u8; 16] = ava1::keys::random_bytes()?; let stop = Arc::new(AtomicBool::new(false)); let mirror = { let stop = Arc::clone(&stop); @@ -231,19 +380,7 @@ pub fn to_server( } }) }; - // Staged under a name this computer can hold whatever the console's is (`a:b`, - // `CON`, `x.` on Windows): the server gets the console's own name, and it is the - // server, not this computer's staging folder, that says whether it can hold it. - let got = ps5upload_ava1::download::to_local_escaped( - addr, - path, - DownloadKind::File, - &staging, - unsafe_read, - id, - &dl, - Some(Arc::clone(&cancel)), - ); + let got = console.pull(path, &staging, &dl, cancel); stop.store(true, Ordering::Relaxed); let _ = mirror.join(); got?; @@ -268,9 +405,9 @@ pub fn to_server( shown.store(base + half + part, Ordering::Relaxed); }) }, - cancel: Arc::clone(&cancel), + cancel: Arc::clone(cancel), }; - let placed = rt.block_on(place(fs.as_ref(), &staged, &target, &progress)); + let placed = rt.block_on(place(fs, &staged, &target, &progress)); let _ = std::fs::remove_file(&staged); placed?; done += size; @@ -282,7 +419,59 @@ pub fn to_server( Ok(done) })(); let _ = std::fs::remove_dir_all(&staging); - result + Ok(Relayed { + bytes: result?, + dest_dir, + files, + dirs, + skipped, + }) +} + +/// A move's second half, once the copy finished: every file is on the server at its size and +/// every folder is there, the source on the console is still what was copied (nothing added, +/// grown or gone meanwhile), and only then is the source deleted. Any doubt keeps the source. +pub(crate) fn finish_move( + rt: &tokio::runtime::Handle, + fs: &dyn RemoteFs, + console: &dyn ConsoleSide, + r: &Relayed, + cancel: &AtomicBool, +) -> Result<()> { + if cancel.load(Ordering::Relaxed) { + bail!("transfer_cancelled"); + } + if let Some(first) = r.skipped.first() { + bail!("{first} is a link, which can't be copied to the server: {KEPT}."); + } + for (_, rel, size) in &r.files { + let target = format!("{}/{rel}", r.dest_dir); + match rt.block_on(fs.stat(&target)) { + Ok(e) if !e.is_dir && e.size == *size => {} + Ok(e) => bail!( + "The copy of {rel} on the server is {} bytes, not {size}: {KEPT}.", + e.size + ), + Err(e) => bail!( + "The copy of {rel} could not be checked on the server ({}): {KEPT}.", + remote::api::error_with_hint(&e) + ), + } + } + for rel in &r.dirs { + let dir = format!("{}/{rel}", r.dest_dir); + if !rt.block_on(fs.stat(&dir)).is_ok_and(|e| e.is_dir) { + bail!("The folder {rel} is not on the server: {KEPT}."); + } + } + let (files, dirs, skipped) = console.files()?; + if files != r.files || dirs != r.dirs || skipped != r.skipped { + bail!("Files on the PS5 changed during the copy: {KEPT}."); + } + if cancel.load(Ordering::Relaxed) { + bail!("transfer_cancelled"); + } + console.delete() } #[cfg(test)] @@ -300,7 +489,7 @@ mod tests { #[tokio::test] async fn a_file_lands_under_its_name_through_a_temporary_one() { let fs = MemFs::new(&[("/games/old.bin", b"stale")]); - let dir = std::env::temp_dir().join(format!("relay-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("relay-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let staged = dir.join("old.bin"); std::fs::write(&staged, b"fresh bytes").unwrap(); @@ -325,7 +514,7 @@ mod tests { /// A folder with nothing in it is listed, so it is made on the server (it was dropped). #[test] fn a_folder_with_no_file_in_it_is_still_listed() { - let (files, dirs) = walk_console("/data/game", |dir, offset| { + let (files, dirs, _) = walk_console("/data/game", |dir, offset| { let page: Vec<(String, String, u64)> = match (dir, offset) { ("/data/game", 0) => vec![ (".".into(), "dir".into(), 0), @@ -371,7 +560,7 @@ mod tests { }); assert!(r.is_err(), "{bad:?}: {r:?}"); } - let (files, _) = walk_console("/data/game", |dir, _| { + let (files, _, _) = walk_console("/data/game", |dir, _| { let page = match dir { "/data/game" => { vec![("options\\gabindings.xml".to_string(), "file".to_string(), 1)] @@ -396,10 +585,416 @@ mod tests { ); } + /// A folder on this computer standing in for the console: a pull copies a file into staging + /// (failing, cancelling or coming up short on cue), and a delete removes the source. + struct DirConsole { + root: PathBuf, + /// The pull with this number (1-based) fails as a dropped console. + fail_at: Option, + /// The pull with this number is cancelled, as Stop does mid-file. + cancel_at: Option, + /// Every pull stages one byte less than the file holds. + short: bool, + /// After the first pull, a file is added to the source (a game writing into it). + grow: bool, + pulls: std::sync::atomic::AtomicUsize, + deletes: std::sync::atomic::AtomicUsize, + } + + impl DirConsole { + fn new(root: &Path) -> Self { + Self { + root: root.to_path_buf(), + fail_at: None, + cancel_at: None, + short: false, + grow: false, + pulls: Default::default(), + deletes: Default::default(), + } + } + } + + impl ConsoleSide for DirConsole { + fn files(&self) -> Result { + walk_console(self.root.to_str().unwrap(), |dir, offset| { + if offset > 0 { + return Ok((Vec::new(), false)); + } + let mut page = Vec::new(); + for e in std::fs::read_dir(dir)? { + let e = e?; + let md = std::fs::symlink_metadata(e.path())?; + let kind = if md.is_symlink() { + "link" + } else if md.is_dir() { + "dir" + } else { + "file" + }; + page.push(( + e.file_name().to_string_lossy().into_owned(), + kind.to_string(), + md.len(), + )); + } + Ok((page, false)) + }) + } + + fn pull( + &self, + path: &str, + staging: &Path, + dl: &ps5upload_ava1::download::Counters, + cancel: &Arc, + ) -> Result<()> { + let n = self.pulls.fetch_add(1, Ordering::SeqCst) + 1; + if self.fail_at == Some(n) { + bail!("the console dropped the connection"); + } + if self.cancel_at == Some(n) { + cancel.store(true, Ordering::SeqCst); + bail!("transfer_cancelled"); + } + let mut bytes = std::fs::read(path)?; + if self.short { + bytes.pop(); + } + dl.bytes.fetch_add(bytes.len() as u64, Ordering::Relaxed); + std::fs::write(staging.join(staged_name(path)?), bytes)?; + if self.grow && n == 1 { + std::fs::write(self.root.join("new.sav"), b"written meanwhile")?; + } + Ok(()) + } + + fn delete(&self) -> Result<()> { + self.deletes.fetch_add(1, Ordering::SeqCst); + std::fs::remove_dir_all(&self.root)?; + Ok(()) + } + } + + /// A temporary folder that goes when the test ends, passed or failed. + struct Scratch(PathBuf); + impl Scratch { + fn new(tag: &str) -> Self { + let n: [u8; 8] = ava1::keys::random_bytes().unwrap(); + let hex: String = n.iter().map(|b| format!("{b:02x}")).collect(); + let p = std::env::temp_dir().join(format!("relay-{tag}-{hex}")); + std::fs::create_dir_all(&p).unwrap(); + Self(p) + } + } + impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + + /// A game folder `game` with a file, a subfolder with a file, and an empty subfolder. + fn game(at: &Path) -> PathBuf { + let root = at.join("game"); + std::fs::create_dir_all(root.join("sce_sys")).unwrap(); + std::fs::create_dir_all(root.join("empty")).unwrap(); + std::fs::write(root.join("eboot.bin"), b"eboot bytes").unwrap(); + std::fs::write(root.join("sce_sys/param.json"), b"{\"a\":1}").unwrap(); + root + } + + /// Runs a copy or move of `console` into `/shared/PS5` on `fs`, from a thread outside the + /// runtime as the job's blocking thread is. + fn run(fs: &dyn RemoteFs, console: &DirConsole, remove: bool, staging: &Path) -> Result { + let rt = tokio::runtime::Runtime::new().unwrap(); + let counters = ps5upload_ava1::download::Counters::default(); + let cancel = Arc::new(AtomicBool::new(false)); + copy_or_move( + rt.handle(), + fs, + console, + "/shared/PS5", + remove, + &counters, + &cancel, + staging, + ) + } + + #[test] + fn a_move_deletes_the_source_only_once_the_copy_is_on_the_server() { + let tmp = Scratch::new("move"); + let console = DirConsole::new(&game(&tmp.0)); + let fs = MemFs::new(&[]); + let staging = tmp.0.join("staging"); + assert_eq!(run(&fs, &console, true, &staging).unwrap(), 18); + assert_eq!( + fs.bytes("/shared/PS5/game/eboot.bin").unwrap(), + b"eboot bytes" + ); + assert_eq!( + fs.bytes("/shared/PS5/game/sce_sys/param.json").unwrap(), + b"{\"a\":1}" + ); + assert!(futures_block(fs.stat("/shared/PS5/game/empty")).is_dir); + assert_eq!(console.deletes.load(Ordering::SeqCst), 1); + assert!( + !console.root.exists(), + "the source goes after a checked copy" + ); + // Nothing left in staging on this computer. + assert_eq!(std::fs::read_dir(&staging).unwrap().count(), 0); + } + + #[test] + fn a_copy_keeps_the_source() { + let tmp = Scratch::new("copy"); + let console = DirConsole::new(&game(&tmp.0)); + let fs = MemFs::new(&[]); + run(&fs, &console, false, &tmp.0.join("staging")).unwrap(); + assert_eq!( + fs.bytes("/shared/PS5/game/eboot.bin").unwrap(), + b"eboot bytes" + ); + assert_eq!(console.deletes.load(Ordering::SeqCst), 0); + assert!(console.root.join("eboot.bin").exists()); + } + + #[test] + fn a_move_that_fails_part_way_keeps_the_source() { + let tmp = Scratch::new("fail"); + let mut console = DirConsole::new(&game(&tmp.0)); + console.fail_at = Some(2); + let fs = MemFs::new(&[]); + let e = run(&fs, &console, true, &tmp.0.join("staging")).unwrap_err(); + assert!(e.to_string().contains("dropped"), "{e}"); + assert_eq!(console.deletes.load(Ordering::SeqCst), 0); + assert!(console.root.join("eboot.bin").exists()); + assert!(console.root.join("sce_sys/param.json").exists()); + } + + #[test] + fn a_cancelled_move_keeps_the_source() { + let tmp = Scratch::new("cancel"); + let mut console = DirConsole::new(&game(&tmp.0)); + console.cancel_at = Some(2); + let fs = MemFs::new(&[]); + let e = run(&fs, &console, true, &tmp.0.join("staging")).unwrap_err(); + assert_eq!(e.to_string(), "transfer_cancelled"); + assert_eq!(console.deletes.load(Ordering::SeqCst), 0); + assert!(console.root.join("eboot.bin").exists()); + assert!(fs.paths().iter().all(|p| !p.ends_with(".ps5upload-tmp"))); + } + + #[test] + fn a_move_whose_copy_does_not_match_keeps_the_source() { + let tmp = Scratch::new("short"); + let mut console = DirConsole::new(&game(&tmp.0)); + console.short = true; + let fs = MemFs::new(&[]); + let e = run(&fs, &console, true, &tmp.0.join("staging")).unwrap_err(); + assert!(e.to_string().contains("kept"), "{e}"); + assert_eq!(console.deletes.load(Ordering::SeqCst), 0); + assert!(console.root.join("eboot.bin").exists()); + } + + #[test] + fn a_move_whose_source_changed_meanwhile_keeps_it() { + let tmp = Scratch::new("grow"); + let mut console = DirConsole::new(&game(&tmp.0)); + console.grow = true; + let fs = MemFs::new(&[]); + let e = run(&fs, &console, true, &tmp.0.join("staging")).unwrap_err(); + assert!(e.to_string().contains("changed"), "{e}"); + assert_eq!(console.deletes.load(Ordering::SeqCst), 0); + assert!(console.root.join("new.sav").exists()); + } + + /// A link is never copied (the console lists it as a link, not a file), so a move with one + /// in the tree keeps the whole source: deleting it would lose the link (#953). + #[cfg(unix)] + #[test] + fn a_move_whose_tree_holds_a_link_keeps_the_source() { + let tmp = Scratch::new("link"); + let root = game(&tmp.0); + std::os::unix::fs::symlink("eboot.bin", root.join("sce_sys/alias")).unwrap(); + let console = DirConsole::new(&root); + let (_, _, skipped) = console.files().unwrap(); + assert_eq!(skipped, ["game/sce_sys/alias"]); + let fs = MemFs::new(&[]); + let e = run(&fs, &console, true, &tmp.0.join("staging")).unwrap_err(); + assert!( + e.to_string().contains("game/sce_sys/alias is a link"), + "{e}" + ); + assert!(e.to_string().contains("kept"), "{e}"); + assert_eq!(console.deletes.load(Ordering::SeqCst), 0); + assert!(root.join("sce_sys/alias").symlink_metadata().is_ok()); + // The files themselves were copied; a copy (not a move) of the same tree succeeds. + assert_eq!( + fs.bytes("/shared/PS5/game/eboot.bin").unwrap(), + b"eboot bytes" + ); + run(&fs, &console, false, &tmp.0.join("staging")).unwrap(); + } + + #[test] + fn a_single_file_moves_too() { + let tmp = Scratch::new("file"); + let root = game(&tmp.0); + struct OneFile(DirConsole, PathBuf); + impl ConsoleSide for OneFile { + fn files(&self) -> Result { + let len = std::fs::metadata(&self.1)?.len(); + Ok(( + vec![(self.1.to_string_lossy().into(), "eboot.bin".into(), len)], + Vec::new(), + Vec::new(), + )) + } + fn pull( + &self, + path: &str, + staging: &Path, + dl: &ps5upload_ava1::download::Counters, + cancel: &Arc, + ) -> Result<()> { + self.0.pull(path, staging, dl, cancel) + } + fn delete(&self) -> Result<()> { + Ok(std::fs::remove_file(&self.1)?) + } + } + let one = OneFile(DirConsole::new(&root), root.join("eboot.bin")); + let fs = MemFs::new(&[]); + let rt = tokio::runtime::Runtime::new().unwrap(); + let cancel = Arc::new(AtomicBool::new(false)); + copy_or_move( + rt.handle(), + &fs, + &one, + "/shared", + true, + &Default::default(), + &cancel, + &tmp.0.join("staging"), + ) + .unwrap(); + assert_eq!(fs.bytes("/shared/eboot.bin").unwrap(), b"eboot bytes"); + assert!(!root.join("eboot.bin").exists()); + assert!( + root.join("sce_sys/param.json").exists(), + "only the file goes" + ); + } + + #[test] + fn only_items_inside_a_drive_can_be_moved() { + for ok in [ + "/data/game", + "/data/a/b", + "/mnt/usb0/PS5", + "/mnt/ext1/x/y", + "/user/x", + ] { + assert!(movable_source(ok), "{ok}"); + } + for bad in [ + "/", + "", + "/data", + "/data/", + "/mnt", + "/mnt/usb0", + "/mnt/usb0/", + "data/x", + ] { + assert!(!movable_source(bad), "{bad}"); + } + assert!(!movable_source("/data/../mnt/usb0")); + } + + fn futures_block(f: impl std::future::Future>) -> T { + tokio::runtime::Runtime::new().unwrap().block_on(f).unwrap() + } + + /// The same move against real Samba (memory: smb-test-server recipe), with a writable share: + /// `PS5UPLOAD_SAMBA_TEST=127.0.0.1:445 PS5UPLOAD_SAMBA_SHARE=games PS5UPLOAD_SAMBA_USER=tester + /// PS5UPLOAD_SAMBA_PASS=pw123 cargo test -p ps5upload-engine -- --ignored moves_onto_samba`. + #[test] + #[ignore = "needs a Samba server; see the doc comment"] + fn moves_onto_samba() { + let Ok(addr) = std::env::var("PS5UPLOAD_SAMBA_TEST") else { + return; + }; + use crate::remote::store::Secret; + let (host, port) = addr.split_once(':').unwrap(); + let mut conn = crate::remote::store::conn("t", crate::remote::store::Protocol::Smb); + conn.host = host.into(); + conn.port = port.parse().unwrap(); + conn.share = std::env::var("PS5UPLOAD_SAMBA_SHARE").unwrap_or_default(); + conn.user = std::env::var("PS5UPLOAD_SAMBA_USER").unwrap_or_default(); + let secret = match std::env::var("PS5UPLOAD_SAMBA_PASS") { + Ok(password) => Secret::Password { password }, + Err(_) => Secret::None, + }; + let rt = tokio::runtime::Runtime::new().unwrap(); + let fs = rt + .block_on(crate::remote::smb_fs::SmbFs::connect(&conn, &secret)) + .unwrap(); + let tmp = Scratch::new("samba"); + let dest = format!("/relay-test-{}", std::process::id()); + let cancel = Arc::new(AtomicBool::new(false)); + let go = |console: &DirConsole| { + copy_or_move( + rt.handle(), + &fs, + console, + &dest, + true, + &Default::default(), + &cancel, + &tmp.0.join("staging"), + ) + }; + // A failed move first: nothing deleted. + let mut failing = DirConsole::new(&game(&tmp.0)); + failing.fail_at = Some(2); + assert!(go(&failing).is_err()); + assert!(failing.root.join("eboot.bin").exists()); + // Then the real one. + let console = DirConsole::new(&failing.root); + go(&console).unwrap(); + assert!(!console.root.exists()); + let st = rt + .block_on(fs.stat(&format!("{dest}/game/sce_sys/param.json"))) + .unwrap(); + assert_eq!(st.size, 7); + assert!( + rt.block_on(fs.stat(&format!("{dest}/game/empty"))) + .unwrap() + .is_dir + ); + // Leave the share as it was. + for p in [ + "game/eboot.bin", + "game/sce_sys/param.json", + "game/sce_sys", + "game/empty", + "game", + "", + ] { + let path = format!("{dest}/{p}"); + let path = path.trim_end_matches('/'); + let _ = rt.block_on(fs.remove_file(path)); + let _ = rt.block_on(fs.remove_dir(path)); + } + } + #[tokio::test] async fn a_cancelled_write_leaves_nothing_behind() { let fs = MemFs::new(&[]); - let dir = std::env::temp_dir().join(format!("relay-c-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("relay-c-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let staged = dir.join("x.bin"); std::fs::write(&staged, vec![7u8; 3 << 20]).unwrap(); diff --git a/engine/crates/ps5upload-engine/src/event_journal.rs b/engine/crates/ps5upload-engine/src/event_journal.rs index dfa660072..c8a357ceb 100644 --- a/engine/crates/ps5upload-engine/src/event_journal.rs +++ b/engine/crates/ps5upload-engine/src/event_journal.rs @@ -487,7 +487,7 @@ mod tests { struct TmpDir(PathBuf); impl TmpDir { fn new(tag: &str) -> Self { - let p = std::env::temp_dir().join(format!("evj-{tag}-{}", std::process::id())); + let p = crate::test_tmp::temp_path(format!("evj-{tag}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&p); std::fs::create_dir_all(&p).unwrap(); TmpDir(p) diff --git a/engine/crates/ps5upload-engine/src/ffmpeg_tool_tests.rs b/engine/crates/ps5upload-engine/src/ffmpeg_tool_tests.rs index 5fc3c943d..c2a761e57 100644 --- a/engine/crates/ps5upload-engine/src/ffmpeg_tool_tests.rs +++ b/engine/crates/ps5upload-engine/src/ffmpeg_tool_tests.rs @@ -4,7 +4,7 @@ use super::*; fn tmp() -> PathBuf { - let d = std::env::temp_dir().join(format!("ps5upload-ffmpeg-{}", uuid::Uuid::new_v4())); + let d = crate::test_tmp::temp_path(format!("ps5upload-ffmpeg-{}", uuid::Uuid::new_v4())); std::fs::create_dir_all(&d).unwrap(); d } diff --git a/engine/crates/ps5upload-engine/src/folder_build.rs b/engine/crates/ps5upload-engine/src/folder_build.rs index 99e5b4d46..128645e16 100644 --- a/engine/crates/ps5upload-engine/src/folder_build.rs +++ b/engine/crates/ps5upload-engine/src/folder_build.rs @@ -29,7 +29,7 @@ mod tests { fn scratch(tag: &str) -> std::path::PathBuf { let root = - std::env::temp_dir().join(format!("ps5upload-fold-{tag}-{}", std::process::id())); + crate::test_tmp::temp_path(format!("ps5upload-fold-{tag}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&root); std::fs::create_dir_all(&root).unwrap(); root diff --git a/engine/crates/ps5upload-engine/src/fpkg_api.rs b/engine/crates/ps5upload-engine/src/fpkg_api.rs index 5182395c1..2123552f7 100644 --- a/engine/crates/ps5upload-engine/src/fpkg_api.rs +++ b/engine/crates/ps5upload-engine/src/fpkg_api.rs @@ -4630,7 +4630,7 @@ mod extract_tests { /// folder of that name, or nothing there, counts for none. #[test] fn a_stopped_builds_partial_counts_as_room() { - let base = std::env::temp_dir().join(format!("fpkg-leftover-{}", Uuid::new_v4())); + let base = crate::test_tmp::temp_path(format!("fpkg-leftover-{}", Uuid::new_v4())); std::fs::create_dir_all(base.join("dir.exfat.partial")).unwrap(); std::fs::write(base.join("game.exfat.partial"), vec![0u8; 4096]).unwrap(); assert_eq!(leftover_bytes(&base.join("game.exfat.partial")), 4096); @@ -4644,7 +4644,7 @@ mod extract_tests { #[test] fn a_failed_unpack_leaves_no_files_behind() { use std::io::Write; - let base = std::env::temp_dir().join(format!("fpkg-failed-unpack-{}", Uuid::new_v4())); + let base = crate::test_tmp::temp_path(format!("fpkg-failed-unpack-{}", Uuid::new_v4())); std::fs::create_dir_all(&base).unwrap(); let zip_path = base.join("game.zip"); { @@ -4691,7 +4691,7 @@ mod extract_tests { /// anywhere else is never touched. #[test] fn a_build_removes_the_unpack_folder_it_read_from() { - let base = std::env::temp_dir().join(format!("ps5upload-scaffold-{}", std::process::id())); + let base = crate::test_tmp::temp_path(format!("ps5upload-scaffold-{}", std::process::id())); let _ = std::fs::remove_dir_all(&base); let root = base.join(format!("{EXTRACT_PREFIX}run")); let game = root.join("Game"); @@ -4709,7 +4709,7 @@ mod extract_tests { #[test] fn a_leftover_partial_goes_but_a_second_build_of_the_same_output_is_refused() { - let out = std::env::temp_dir().join(format!("ps5upload-partial-{}", std::process::id())); + let out = crate::test_tmp::temp_path(format!("ps5upload-partial-{}", std::process::id())); let _ = std::fs::remove_dir_all(&out); std::fs::create_dir_all(&out).unwrap(); std::fs::write(out.join("A.pkg.partial"), b"x").unwrap(); @@ -4760,7 +4760,7 @@ mod extract_tests { fn a_failed_or_interrupted_conversion_leaves_nothing_behind() { // #432: a failed image build kept its `.partial` (as large as the image) in the output // folder, and an interrupted one was never cleared. - let out = std::env::temp_dir().join(format!("ps5upload-leftovers-{}", std::process::id())); + let out = crate::test_tmp::temp_path(format!("ps5upload-leftovers-{}", std::process::id())); let _ = std::fs::remove_dir_all(&out); std::fs::create_dir_all(out.join(format!("{EXTRACT_PREFIX}old"))).unwrap(); for n in [ @@ -4819,7 +4819,7 @@ mod extract_tests { fn another_process_s_unfinished_output_is_never_swept() { use ps5upload_convert_core::writing::ClaimLock; let out = - std::env::temp_dir().join(format!("ps5upload-other-claim-{}", std::process::id())); + crate::test_tmp::temp_path(format!("ps5upload-other-claim-{}", std::process::id())); let _ = std::fs::remove_dir_all(&out); std::fs::create_dir_all(&out).unwrap(); let theirs = out.join("A.exfat.partial"); @@ -4960,7 +4960,7 @@ mod extract_tests { #[test] fn stale_unpacks_go_but_active_ones_stay() { - let out = std::env::temp_dir().join(format!("ps5upload-stale-{}", std::process::id())); + let out = crate::test_tmp::temp_path(format!("ps5upload-stale-{}", std::process::id())); let _ = std::fs::remove_dir_all(&out); let (old, live, keep) = ( out.join(".ps5upload-extract-old"), @@ -4985,7 +4985,7 @@ mod delete_tests { /// Delete package removes only what this engine built, once. #[test] fn only_a_package_this_engine_built_can_be_deleted() { - let dir = std::env::temp_dir().join(format!("fpkg-del-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("fpkg-del-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let ours = dir.join("ours.pkg"); let theirs = dir.join("theirs.pkg"); @@ -5036,7 +5036,7 @@ mod panic_tests { bytes_finalized: 0, }, ); - let dest = std::env::temp_dir().join(format!("fpkg-panic-{job_id}")); + let dest = crate::test_tmp::temp_path(format!("fpkg-panic-{job_id}")); std::fs::create_dir_all(&dest).unwrap(); active_extracts().lock().unwrap().insert(dest.clone()); let spinning = tokio::spawn(async { @@ -5073,7 +5073,7 @@ mod panic_tests { /// A finished unpack keeps its folder. #[test] fn a_found_game_keeps_its_folder() { - let dest = std::env::temp_dir().join(format!("fpkg-keep-{}", Uuid::new_v4())); + let dest = crate::test_tmp::temp_path(format!("fpkg-keep-{}", Uuid::new_v4())); std::fs::create_dir_all(&dest).unwrap(); let mut unpacking = Unpacking(Some(dest.clone())); unpacking.0 = None; @@ -5091,7 +5091,7 @@ mod title_param_tests { /// param.sfo in sce_sys. #[tokio::test] async fn a_folder_needs_param_json_or_param_sfo() { - let dir = std::env::temp_dir().join(format!("fpkg-param-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("fpkg-param-{}", std::process::id())); let sys = dir.join("sce_sys"); std::fs::create_dir_all(&sys).unwrap(); std::fs::write(dir.join("eboot.bin"), b"x").unwrap(); @@ -5247,7 +5247,7 @@ mod source_option_tests { /// A game folder `/PPSA01234` and a small exFAT image of it beside it. fn game(tag: &str) -> (PathBuf, PathBuf, PathBuf) { - let root = std::env::temp_dir().join(format!("fpkg-srcopt-{tag}-{}", std::process::id())); + let root = crate::test_tmp::temp_path(format!("fpkg-srcopt-{tag}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&root); let dir = root.join("PPSA01234"); std::fs::create_dir_all(dir.join("sce_sys")).unwrap(); @@ -5530,7 +5530,7 @@ mod source_option_tests { /// same archive with the game alone does go. #[tokio::test(flavor = "multi_thread")] async fn delete_source_keeps_a_source_the_conversion_left_something_of() { - let root = std::env::temp_dir().join(format!("fpkg-leftout-{}", std::process::id())); + let root = crate::test_tmp::temp_path(format!("fpkg-leftout-{}", std::process::id())); let _ = std::fs::remove_dir_all(&root); std::fs::create_dir_all(&root).unwrap(); let root = std::fs::canonicalize(&root).unwrap(); diff --git a/engine/crates/ps5upload-engine/src/golive_dest.rs b/engine/crates/ps5upload-engine/src/golive_dest.rs index f623cdec2..e3caa0497 100644 --- a/engine/crates/ps5upload-engine/src/golive_dest.rs +++ b/engine/crates/ps5upload-engine/src/golive_dest.rs @@ -674,9 +674,9 @@ static STORE_ERROR: Mutex> = Mutex::new(None); /// The folder they live in. Tests keep to one of their own. fn store_dir() -> Option { if cfg!(test) { - return Some( + return Some(crate::test_scratch( std::env::temp_dir().join(format!("ps5upload-golive-store-{}", std::process::id())), - ); + )); } crate::remote::store::data_dir() } diff --git a/engine/crates/ps5upload-engine/src/golive_dest_tests.rs b/engine/crates/ps5upload-engine/src/golive_dest_tests.rs index afacbd877..b74ed4537 100644 --- a/engine/crates/ps5upload-engine/src/golive_dest_tests.rs +++ b/engine/crates/ps5upload-engine/src/golive_dest_tests.rs @@ -14,7 +14,7 @@ fn session(codec: &'static str, height: u32, fps: u32, kbps: u32) -> SessionInfo } fn tmp() -> std::path::PathBuf { - let d = std::env::temp_dir().join(format!("ps5upload-golive-{}", uuid::Uuid::new_v4())); + let d = crate::test_tmp::temp_path(format!("ps5upload-golive-{}", uuid::Uuid::new_v4())); std::fs::create_dir_all(&d).unwrap(); d } diff --git a/engine/crates/ps5upload-engine/src/icon_cache.rs b/engine/crates/ps5upload-engine/src/icon_cache.rs index aaa3809af..b8a869a76 100644 --- a/engine/crates/ps5upload-engine/src/icon_cache.rs +++ b/engine/crates/ps5upload-engine/src/icon_cache.rs @@ -370,7 +370,7 @@ mod tests { static ONCE: std::sync::Once = std::sync::Once::new(); ONCE.call_once(|| { let dir = - std::env::temp_dir().join(format!("ps5upload-icontest-{}", std::process::id())); + crate::test_tmp::temp_path(format!("ps5upload-icontest-{}", std::process::id())); let _ = fs::remove_dir_all(&dir); // SAFETY: single-threaded test setup, before any read of the var. unsafe { std::env::set_var("PS5UPLOAD_CACHE_DIR", &dir) }; diff --git a/engine/crates/ps5upload-engine/src/image_browse.rs b/engine/crates/ps5upload-engine/src/image_browse.rs index e52e2174a..af0901785 100644 --- a/engine/crates/ps5upload-engine/src/image_browse.rs +++ b/engine/crates/ps5upload-engine/src/image_browse.rs @@ -184,7 +184,7 @@ mod tests { fn scratch(tag: &str) -> PathBuf { let root = - std::env::temp_dir().join(format!("ps5upload-browse-{tag}-{}", std::process::id())); + crate::test_tmp::temp_path(format!("ps5upload-browse-{tag}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&root); std::fs::create_dir_all(&root).unwrap(); root diff --git a/engine/crates/ps5upload-engine/src/image_build.rs b/engine/crates/ps5upload-engine/src/image_build.rs index c2d7707b8..33414e7c1 100644 --- a/engine/crates/ps5upload-engine/src/image_build.rs +++ b/engine/crates/ps5upload-engine/src/image_build.rs @@ -538,7 +538,8 @@ mod tests { /// read-back does: a cancel leaves nothing that looks like a good image. #[test] fn a_cancel_during_the_pack_read_back_removes_the_image() { - let root = std::env::temp_dir().join(format!("ps5upload-lz4cancel-{}", std::process::id())); + let root = + crate::test_tmp::temp_path(format!("ps5upload-lz4cancel-{}", std::process::id())); let _ = std::fs::remove_dir_all(&root); let src = ampr_game(&root); let packs = Lz4Packs { @@ -583,7 +584,7 @@ mod tests { /// this app installs) kept. #[test] fn an_lz4_packed_image_unpacks_into_the_plain_game() { - let root = std::env::temp_dir().join(format!("ps5upload-imgunlz4-{}", std::process::id())); + let root = crate::test_tmp::temp_path(format!("ps5upload-imgunlz4-{}", std::process::id())); let _ = std::fs::remove_dir_all(&root); let src = ampr_game(&root); let out = root.join("PPSA99999-app.exfat"); diff --git a/engine/crates/ps5upload-engine/src/image_build/to_console/tests.rs b/engine/crates/ps5upload-engine/src/image_build/to_console/tests.rs index c44a1d2cd..5ade3a785 100644 --- a/engine/crates/ps5upload-engine/src/image_build/to_console/tests.rs +++ b/engine/crates/ps5upload-engine/src/image_build/to_console/tests.rs @@ -44,7 +44,7 @@ pub(crate) struct Loopback { impl Loopback { pub(crate) async fn start(tag: &str, chaos: Option) -> Self { let dir = - std::env::temp_dir().join(format!("ps5upload-tocon-{tag}-{}", std::process::id())); + crate::test_tmp::temp_path(format!("ps5upload-tocon-{tag}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); let ava = dir.join("engine"); let key = Identity::load_or_create(&ava.join("identity")) @@ -478,7 +478,7 @@ fn not_enough_room_is_refused_with_the_consoles_figures() { #[test] fn a_second_try_keeps_the_first_tries_time_until_the_image_is_done() { - let data = std::env::temp_dir().join(format!("ps5upload-tocon-stamp-{}", std::process::id())); + let data = crate::test_tmp::temp_path(format!("ps5upload-tocon-stamp-{}", std::process::id())); let _ = std::fs::remove_dir_all(&data); let first = console_stamp(Some(&data), "10.0.0.2", "/data/g.exfat"); std::thread::sleep(Duration::from_millis(1100)); diff --git a/engine/crates/ps5upload-engine/src/image_edit_in_place.rs b/engine/crates/ps5upload-engine/src/image_edit_in_place.rs index 05c3d902e..4b718ebaf 100644 --- a/engine/crates/ps5upload-engine/src/image_edit_in_place.rs +++ b/engine/crates/ps5upload-engine/src/image_edit_in_place.rs @@ -1624,7 +1624,7 @@ mod tests { fn new(tag: &str) -> Self { static N: AtomicUsize = AtomicUsize::new(0); let n = N.fetch_add(1, Ordering::Relaxed); - let dir = std::env::temp_dir().join(format!( + let dir = crate::test_tmp::temp_path(format!( "ps5upload-inplace-{tag}-{}-{n}", std::process::id() )); diff --git a/engine/crates/ps5upload-engine/src/inspect.rs b/engine/crates/ps5upload-engine/src/inspect.rs index e7d8ec4f6..b0a98fdba 100644 --- a/engine/crates/ps5upload-engine/src/inspect.rs +++ b/engine/crates/ps5upload-engine/src/inspect.rs @@ -854,7 +854,7 @@ pub(crate) mod test_fixtures { /// A fresh scratch directory per call. pub fn scratch() -> PathBuf { - let d = std::env::temp_dir().join(format!( + let d = crate::test_tmp::temp_path(format!( "ps5upload-inspect-{}-{}", std::process::id(), N.fetch_add(1, Ordering::SeqCst) diff --git a/engine/crates/ps5upload-engine/src/install/history.rs b/engine/crates/ps5upload-engine/src/install/history.rs index 8bd69daf0..2ebd06d82 100644 --- a/engine/crates/ps5upload-engine/src/install/history.rs +++ b/engine/crates/ps5upload-engine/src/install/history.rs @@ -154,7 +154,7 @@ mod tests { .duration_since(std::time::UNIX_EPOCH) .unwrap() .as_nanos(); - let p = std::env::temp_dir().join(format!( + let p = crate::test_tmp::temp_path(format!( "ps5u-hist-{}-{}-{}", std::process::id(), n, diff --git a/engine/crates/ps5upload-engine/src/install/mod.rs b/engine/crates/ps5upload-engine/src/install/mod.rs index ef2f327d9..679744c64 100644 --- a/engine/crates/ps5upload-engine/src/install/mod.rs +++ b/engine/crates/ps5upload-engine/src/install/mod.rs @@ -1253,7 +1253,9 @@ pub struct InstallRequest { fn history_dir() -> std::path::PathBuf { // A test that ends a job must not write to the user's own history. if cfg!(test) { - return std::env::temp_dir().join(format!("ps5u-install-history-{}", std::process::id())); + return crate::test_scratch( + std::env::temp_dir().join(format!("ps5u-install-history-{}", std::process::id())), + ); } crate::remote::store::data_dir() .unwrap_or_else(|| std::path::PathBuf::from(".ps5upload")) @@ -3097,7 +3099,7 @@ mod certainly_a_game_tests { /// The stream route reads the header from the file on this computer. #[tokio::test] async fn the_stream_route_reads_the_add_on_header_from_the_file_here() { - let dir = std::env::temp_dir().join(format!("ps5u-724-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("ps5u-724-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let mut verdicts = Vec::new(); for (name, (t, f)) in [("addon.pkg", ADD_ON), ("game.pkg", GAME)] { diff --git a/engine/crates/ps5upload-engine/src/join_net/join_tests.rs b/engine/crates/ps5upload-engine/src/join_net/join_tests.rs index 9a9f202a5..f74419bfc 100644 --- a/engine/crates/ps5upload-engine/src/join_net/join_tests.rs +++ b/engine/crates/ps5upload-engine/src/join_net/join_tests.rs @@ -1215,7 +1215,7 @@ async fn invites_work_only_on_the_wifi_keeps_to_the_home_networks_link() { /// (`internet_invites` false) reads as Only on my Wi-Fi, a missing or broken one as nothing saved. #[test] fn invites_work_is_saved_and_an_old_off_reads_as_wifi() { - let dir = std::env::temp_dir().join(format!("ps5u-invites-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("ps5u-invites-{}", std::process::id())); let p = dir.join(INVITES_FILE); let d = crate::self_host::defaults(); let with = |anywhere: bool, port: u16| Settings { @@ -1251,7 +1251,7 @@ fn invites_work_is_saved_and_an_old_off_reads_as_wifi() { /// saved value that wins over a default from the environment. #[test] fn hub_page_base_and_stun_are_kept_until_reset() { - let dir = std::env::temp_dir().join(format!("ps5u-hub-kept-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("ps5u-hub-kept-{}", std::process::id())); let p = dir.join(INVITES_FILE); let d = crate::self_host::defaults(); let custom = Settings { diff --git a/engine/crates/ps5upload-engine/src/lib.rs b/engine/crates/ps5upload-engine/src/lib.rs index 03d6bf013..dffe591ea 100644 --- a/engine/crates/ps5upload-engine/src/lib.rs +++ b/engine/crates/ps5upload-engine/src/lib.rs @@ -11849,6 +11849,11 @@ struct TransferDownloadReq { /// with `unescape_names` puts it back exactly. The saves code's downloads (#729). #[serde(default)] escape_names: bool, + /// A move to a saved server (`dest_dir` is `remote://…`): once the copy is complete and + /// checked on the server, the source is deleted on the console. A failed or cancelled copy + /// leaves it (download_relay::finish_move). Refused with any other destination. + #[serde(default)] + remove_source: bool, } /// Where an AVA1 download lands (Task 25). @@ -11858,8 +11863,9 @@ enum Ava1DownloadTarget { Folder(std::path::PathBuf, bool), /// One `.zip` at this path, Stored (resumable) or Deflated (cannot resume). Zip(std::path::PathBuf, ps5upload_ava1::download::ZipCompression), - /// A folder on a saved server (`remote://id/dir`), through this engine (download_relay.rs). - Server(String), + /// A folder on a saved server (`remote://id/dir`), through this engine (download_relay.rs); + /// `true` moves (the source is deleted once the copy is checked). + Server(String, bool), } /// Starts a console -> computer download over AVA1 and answers `ACCEPTED` with the job id. @@ -11896,7 +11902,7 @@ fn start_ava1_download( let dest_display = match &target { Ava1DownloadTarget::Folder(dir, _) => dir.join(&basename).to_string_lossy().to_string(), Ava1DownloadTarget::Zip(zip, _) => zip.to_string_lossy().to_string(), - Ava1DownloadTarget::Server(dir) => format!("{}/{basename}", dir.trim_end_matches('/')), + Ava1DownloadTarget::Server(dir, _) => format!("{}/{basename}", dir.trim_end_matches('/')), }; crate::log_info!("transfer_download: job={job_id} protocol=ava1 src={src} dest={dest_display}"); let progress = Arc::new(AtomicU64::new(0)); @@ -12000,12 +12006,13 @@ fn start_ava1_download( &counters, Some(cancel), ), - Ava1DownloadTarget::Server(dir) => download_relay::to_server( + Ava1DownloadTarget::Server(dir, remove_source) => download_relay::to_server( &addr, &src, kind, dir, unsafe_read, + *remove_source, &counters, cancel, &crate::remote::store::data_dir() @@ -12127,15 +12134,30 @@ async fn transfer_download_handler( if let Err(e) = crate::remote::path::parse(&req.dest_dir) { return json_err(StatusCode::BAD_REQUEST, format!("{e}")).into_response(); } + // A move deletes on the console: only what Files could delete, never a whole drive. + if req.remove_source && (req_unsafe || !download_relay::movable_source(trimmed_src)) { + return json_err( + StatusCode::BAD_REQUEST, + format!("{trimmed_src} can't be moved off the PS5; copy it instead"), + ) + .into_response(); + } return start_ava1_download( &state, mgmt_addr, req.src_path.clone(), kind, req_unsafe, - Ava1DownloadTarget::Server(req.dest_dir.clone()), + Ava1DownloadTarget::Server(req.dest_dir.clone(), req.remove_source), ); } + if req.remove_source { + return json_err( + StatusCode::BAD_REQUEST, + "remove_source needs a saved server as dest_dir", + ) + .into_response(); + } let dest_dir = std::path::PathBuf::from(&req.dest_dir); // rsplit on a non-empty string always yields at least one piece, @@ -15340,7 +15362,7 @@ mod cancel_registry_tests { #[tokio::test(flavor = "multi_thread")] async fn a_cancelled_download_job_ends_cancelled() { - let dir = std::env::temp_dir().join(format!("dl-cancel-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("dl-cancel-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(dir.join("host/share")).unwrap(); std::fs::write(dir.join("host/share/f.bin"), vec![7u8; 1 << 20]).unwrap(); @@ -15418,7 +15440,7 @@ mod helpers_tests { /// "N bytes of 0" while the whole tree was sent. #[test] fn the_folder_plan_matches_excludes_inside_the_source_only() { - let base = std::env::temp_dir().join(format!("ps5u-plan-{}", std::process::id())); + let base = crate::test_tmp::temp_path(format!("ps5u-plan-{}", std::process::id())); let root = base.join("data").join("Games").join("G"); std::fs::create_dir_all(root.join("data")).unwrap(); std::fs::write(root.join("eboot.bin"), b"12345").unwrap(); @@ -15452,7 +15474,7 @@ mod helpers_tests { /// A stopped folder upload's walk ends at its next folder, not at the end of the source. #[test] fn a_stopped_walk_ends_at_once() { - let root = std::env::temp_dir().join(format!("ps5upload-walkstop-{}", std::process::id())); + let root = crate::test_tmp::temp_path(format!("ps5upload-walkstop-{}", std::process::id())); let _ = std::fs::remove_dir_all(&root); std::fs::create_dir_all(root.join("a/b")).unwrap(); std::fs::write(root.join("a/b/f.bin"), b"xyz").unwrap(); @@ -16916,7 +16938,7 @@ mod archive_packages_tests { #[test] fn a_zip_lists_only_its_packages_at_any_depth() { - let dir = std::env::temp_dir().join(format!("ps5upload-arcpkg-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("ps5upload-arcpkg-{}", std::process::id())); std::fs::create_dir_all(&dir).expect("mkdir"); let path = dir.join("bundle.zip"); let mut zw = zip::ZipWriter::new(std::fs::File::create(&path).expect("create")); @@ -16960,7 +16982,7 @@ mod speed_test_file_tests { /// test's 2 GiB); anything younger may be another engine's and stays. #[test] fn the_start_sweep_takes_what_was_there_before_and_nothing_newer() { - let dir = std::env::temp_dir().join(format!("ps5upload-sweep-{}", uuid::Uuid::new_v4())); + let dir = crate::test_tmp::temp_path(format!("ps5upload-sweep-{}", uuid::Uuid::new_v4())); std::fs::create_dir_all(dir.join("old-share")).unwrap(); std::fs::write(dir.join("old-share").join("save.zip"), b"x").unwrap(); std::fs::write(dir.join("ps5upload-speedtest.bin"), b"x").unwrap(); @@ -16979,7 +17001,8 @@ mod speed_test_file_tests { #[test] fn a_forgotten_speed_test_is_removed_unless_a_newer_one_runs() { - let dir = std::env::temp_dir().join(format!("ps5upload-speedexp-{}", uuid::Uuid::new_v4())); + let dir = + crate::test_tmp::temp_path(format!("ps5upload-speedexp-{}", uuid::Uuid::new_v4())); std::fs::create_dir_all(dir.join("back")).unwrap(); std::fs::write(dir.join("ps5upload-speedtest.bin"), b"x").unwrap(); let latest = std::sync::atomic::AtomicU64::new(2); @@ -17000,7 +17023,7 @@ mod speed_test_file_tests { #[test] fn the_file_has_the_asked_size_and_does_not_repeat() { - let dir = std::env::temp_dir().join(format!("ps5upload-speedfile-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("ps5upload-speedfile-{}", std::process::id())); let path = dir.join("f.bin"); assert_eq!( write_speed_test_file(&path, 2).expect("write"), @@ -17021,7 +17044,7 @@ mod module_case_upload_tests { #[test] fn a_game_folder_uploads_its_modules_under_the_eboot_spelling() { - let d = std::env::temp_dir().join(format!("ps5u-modcase-{}", std::process::id())); + let d = crate::test_tmp::temp_path(format!("ps5u-modcase-{}", std::process::id())); let _ = std::fs::remove_dir_all(&d); std::fs::create_dir_all(d.join("Media/Modules")).unwrap(); let mut eboot = vec![0u8; 4096]; @@ -17094,3 +17117,17 @@ mod no_delay_tests { assert!(io.nodelay().unwrap()); } } + +// Test scratch paths removed when the test process exits (engine/test-support/test_tmp.rs). +#[cfg(test)] +#[path = "../../../test-support/test_tmp.rs"] +mod test_tmp; + +/// A per-process scratch folder that product code picks under `cfg!(test)` (a test data +/// directory): under `cargo test` it is removed when the test process exits; otherwise unchanged. +pub(crate) fn test_scratch(path: std::path::PathBuf) -> std::path::PathBuf { + #[cfg(test)] + return test_tmp::remove_at_exit(path); + #[cfg(not(test))] + path +} diff --git a/engine/crates/ps5upload-engine/src/link.rs b/engine/crates/ps5upload-engine/src/link.rs index 0ee7d35f9..1e41c3a5a 100644 --- a/engine/crates/ps5upload-engine/src/link.rs +++ b/engine/crates/ps5upload-engine/src/link.rs @@ -1234,7 +1234,7 @@ mod served_tests { assert_eq!(info.image, Some(ImageKind::Exfat)); assert_eq!(info.unpacked_name, "tool.elf.exfat"); - let dir = std::env::temp_dir().join(format!("link-lz4-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("link-lz4-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); let ava = dir.join("engine"); let key = Identity::load_or_create(&ava.join("identity")) @@ -1294,7 +1294,7 @@ mod served_tests { use ava1::server::{self, ServerCtx}; use ps5upload_ava1::Pool; - let dir = std::env::temp_dir().join(format!("link-whole-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("link-whole-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); let ava = dir.join("engine"); let key = Identity::load_or_create(&ava.join("identity")) @@ -1363,7 +1363,7 @@ mod served_tests { let b = base(); let total = 5 * 1024 * 1024 + 123; - let dir = std::env::temp_dir().join(format!("link-dl-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("link-dl-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); let ava = dir.join("engine"); let key = Identity::load_or_create(&ava.join("identity")) diff --git a/engine/crates/ps5upload-engine/src/local_fs.rs b/engine/crates/ps5upload-engine/src/local_fs.rs index ba9e154ca..eb9b27571 100644 --- a/engine/crates/ps5upload-engine/src/local_fs.rs +++ b/engine/crates/ps5upload-engine/src/local_fs.rs @@ -373,7 +373,7 @@ mod tests { #[test] fn list_dir_sorts_dirs_first_then_files_case_insensitive() { - let tmp = std::env::temp_dir().join(format!("ps5_engine_lf_{}", std::process::id())); + let tmp = crate::test_tmp::temp_path(format!("ps5_engine_lf_{}", std::process::id())); let _ = std::fs::remove_dir_all(&tmp); std::fs::create_dir_all(tmp.join("Zsub")).unwrap(); std::fs::create_dir_all(tmp.join("alpha")).unwrap(); @@ -417,7 +417,7 @@ mod tests { } fn tmp_dir(tag: &str) -> String { - let p = std::env::temp_dir().join(format!("ps5_browse_{}_{tag}", std::process::id())); + let p = crate::test_tmp::temp_path(format!("ps5_browse_{}_{tag}", std::process::id())); std::fs::create_dir_all(&p).unwrap(); p.to_string_lossy().into_owned() } diff --git a/engine/crates/ps5upload-engine/src/log_levels.rs b/engine/crates/ps5upload-engine/src/log_levels.rs index 5dfe587e6..09da679e5 100644 --- a/engine/crates/ps5upload-engine/src/log_levels.rs +++ b/engine/crates/ps5upload-engine/src/log_levels.rs @@ -400,7 +400,7 @@ mod tests { #[test] fn a_save_leaves_the_file_whole_and_no_temporary_behind() { - let dir = std::env::temp_dir().join(format!( + let dir = crate::test_tmp::temp_path(format!( "ps5upload-log-levels-save-{}-{}", std::process::id(), clog::now_ms() diff --git a/engine/crates/ps5upload-engine/src/mcp/access.rs b/engine/crates/ps5upload-engine/src/mcp/access.rs index 1c41b1175..ca92026f0 100644 --- a/engine/crates/ps5upload-engine/src/mcp/access.rs +++ b/engine/crates/ps5upload-engine/src/mcp/access.rs @@ -318,7 +318,7 @@ mod tests { #[test] fn the_switch_is_kept_in_its_file() { - let dir = std::env::temp_dir().join(format!( + let dir = crate::test_tmp::temp_path(format!( "ps5upload-agent-access-{}-{}", std::process::id(), SEQ_TEST.fetch_add(1, Ordering::Relaxed) diff --git a/engine/crates/ps5upload-engine/src/mcp/catalog_routes.rs b/engine/crates/ps5upload-engine/src/mcp/catalog_routes.rs index 45eabc2f5..6f065d803 100644 --- a/engine/crates/ps5upload-engine/src/mcp/catalog_routes.rs +++ b/engine/crates/ps5upload-engine/src/mcp/catalog_routes.rs @@ -469,8 +469,12 @@ pub(crate) const ROUTES: &[(&str, &str)] = &[ ("GET", "/api/payloads/pm-sync"), ("PUT", "/api/payloads/pm-sync"), ("POST", "/api/payloads/pm-sync/run"), + ("GET", "/api/payloads/repos"), ("POST", "/api/payloads/repos"), + ("POST", "/api/payloads/repos/preview"), ("DELETE", "/api/payloads/repos/{id}"), + ("POST", "/api/payloads/repos/{id}/download"), + ("PUT", "/api/payloads/repos/{id}/file"), ("GET", "/api/payloads/sources"), ("POST", "/api/payloads/sources"), ("POST", "/api/payloads/sources/refresh"), diff --git a/engine/crates/ps5upload-engine/src/mcp/tests.rs b/engine/crates/ps5upload-engine/src/mcp/tests.rs index a6200bcfe..8b721670c 100644 --- a/engine/crates/ps5upload-engine/src/mcp/tests.rs +++ b/engine/crates/ps5upload-engine/src/mcp/tests.rs @@ -2745,6 +2745,24 @@ async fn the_routes_that_say_host_get_the_console_as_host() { } } +#[tokio::test] +async fn the_payload_source_tools_reach_their_routes() { + let server = echo_server(); + let asked = route_of(&server, "payloads_sources", json!({"check": true})).await; + assert_eq!(asked["path"], "/api/payloads/repos"); + assert_eq!(asked["query"]["check"], "true"); + let asked = route_of( + &server, + "payloads_source_download", + json!({"id": "custom-0a1b2c3d4e5f"}), + ) + .await; + assert_eq!( + asked["path"], + "/api/payloads/repos/custom-0a1b2c3d4e5f/download" + ); +} + #[tokio::test] async fn the_payload_update_tools_reach_their_routes() { let server = echo_server(); diff --git a/engine/crates/ps5upload-engine/src/mcp/tools/mod.rs b/engine/crates/ps5upload-engine/src/mcp/tools/mod.rs index e33bf60aa..460c6b535 100644 --- a/engine/crates/ps5upload-engine/src/mcp/tools/mod.rs +++ b/engine/crates/ps5upload-engine/src/mcp/tools/mod.rs @@ -895,6 +895,8 @@ mod tests { assert_eq!(hints("rp_stop"), (false, true)); assert_eq!(hints("shell_run"), (false, true)); assert_eq!(hints("payloads_send"), (false, true)); + assert_eq!(hints("payloads_sources"), (true, false)); + assert_eq!(hints("payloads_source_download"), (false, true)); assert_eq!(hints("consoles_discover"), (true, false)); for tool in all() { assert_eq!( diff --git a/engine/crates/ps5upload-engine/src/mcp/tools/payloads.rs b/engine/crates/ps5upload-engine/src/mcp/tools/payloads.rs index 44392a2d6..4e71d4124 100644 --- a/engine/crates/ps5upload-engine/src/mcp/tools/payloads.rs +++ b/engine/crates/ps5upload-engine/src/mcp/tools/payloads.rs @@ -1,10 +1,13 @@ -//! Payloads: the engine's library (`payloads_catalog`), new versions (`payloads_updates`, +//! Payloads: the engine's library (`payloads_catalog`), the payload sources the user added +//! (`payloads_sources`, `payloads_source_download`), new versions (`payloads_updates`, //! `payloads_updates_check`, `payloads_rollback`), keeping a console's Payload Manager in step //! (`payloads_pm_choice`, `payloads_pm_sync`), sending one to a //! console (`payloads_send`), and the console's Payload Manager (`payloads_list`, //! `payloads_launch`, `payloads_store`, `payloads_delete`, `payloads_autoload`). //! -//! ps5upload never downloads a payload: the user gets the file from the project page. +//! The built-in catalogue is never downloaded: the user gets those files from the project page. +//! Only a source the user added themselves is downloaded, and adding one is the user's own step +//! in the app (it asks them to trust the project), so no tool adds or removes one. use serde_json::json; @@ -24,6 +27,46 @@ pub(super) fn tools() -> Vec { schema: object(json!({}), &[]), run: route!(path: "/api/payloads", done: "The payload library."), }, + ToolDef { + name: "payloads_sources", + title: "Payload sources the user added", + description: "The payload sources the user added in Payloads: a GitHub, Gitea or \ + Forgejo project and the file picked from its releases. For each: the \ + copy on the engine's computer (release, size, SHA-256, `path`) and, \ + after a check, the newest release's file and `update_available`. \ + Without `check` nothing asks the network. A project's releases are \ + read at most every ten minutes unless `force`; GitHub allows 60 reads \ + an hour, and a limited host answers `rate_limited` with `retry_at`.", + kind: Kind::Read, + schema: object( + json!({ + "check": flag("Read each source's newest releases."), + "force": flag("With `check`: read them even when read in the last ten minutes."), + }), + &[], + ), + run: route!(path: "/api/payloads/repos", done: "The payload sources."), + }, + ToolDef { + name: "payloads_source_download", + title: "Download a payload source's file", + description: "Downloads the newest release's file of a payload source the user \ + added (an id from payloads_sources) into the engine's payload folder, \ + replacing the copy there once the new one is checked (its size, and \ + the release's checksum file when it has one). Sends nothing: \ + payloads_send with the same id as `payload_id` does, and only when the \ + user asked for it.", + kind: Kind::Destructive { idempotent: true }, + schema: object( + json!({ "id": text("The source's id, from payloads_sources.") }), + &["id"], + ), + run: route!( + method: "POST", + path: "/api/payloads/repos/{id}/download", + done: "Downloaded the source's file.", + ), + }, ToolDef { name: "payloads_updates", title: "Payload updates, as last checked", @@ -127,10 +170,10 @@ pub(super) fn tools() -> Vec { title: "Send a payload to a console", description: "Sends a payload to a console's loader, which runs it: a file on the \ engine's computer (`path`) or the local copy of a library payload \ - (`payload_id`). Nothing is downloaded: without a local copy it fails \ - with `not_on_this_computer`, and the user gets the file from the \ - project page. A payload is a program with full access to the console: \ - only one the user asked for.", + (`payload_id`: a catalogue id, or a payload source's id from \ + payloads_sources). Nothing is downloaded: without a local copy it fails \ + with `not_on_this_computer`. A payload is a program with full access to \ + the console: only one the user asked for.", kind: Kind::Destructive { idempotent: false }, schema: object( json!({ diff --git a/engine/crates/ps5upload-engine/src/mesh_drive.rs b/engine/crates/ps5upload-engine/src/mesh_drive.rs index 9d58f4400..cfeb2f82b 100644 --- a/engine/crates/ps5upload-engine/src/mesh_drive.rs +++ b/engine/crates/ps5upload-engine/src/mesh_drive.rs @@ -5526,7 +5526,7 @@ mod tests { /// this disk really does. #[test] fn a_folder_says_itself_whether_it_ignores_case() { - let dir = std::env::temp_dir().join(format!("ps5u-mesh-case-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("ps5u-mesh-case-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); std::fs::write(dir.join("probe.txt"), b"x").unwrap(); @@ -5595,7 +5595,7 @@ mod tests { #[test] fn only_a_folder_with_nothing_of_the_drive_left_is_pruned() { use super::Side; - let root = std::env::temp_dir().join(format!("mesh-prune-{}", std::process::id())); + let root = crate::test_tmp::temp_path(format!("mesh-prune-{}", std::process::id())); std::fs::create_dir_all(root.join("gone/inner")).unwrap(); std::fs::write(root.join("gone/.DS_Store"), b"x").unwrap(); std::fs::create_dir_all(root.join("kept")).unwrap(); @@ -6165,7 +6165,7 @@ mod tests { #[test] fn a_local_walk_goes_on_past_a_folder_it_cannot_open() { use std::os::unix::fs::PermissionsExt; - let root = std::env::temp_dir().join(format!("ps5u-mesh-walk-{}", new_id())); + let root = crate::test_tmp::temp_path(format!("ps5u-mesh-walk-{}", new_id())); std::fs::create_dir_all(root.join("shut")).unwrap(); std::fs::write(root.join("shut/inside.txt"), b"x").unwrap(); std::fs::write(root.join("open.txt"), b"x").unwrap(); @@ -6978,7 +6978,7 @@ mod tests { impl AwayRig { fn new(name: &str) -> Self { - let dir = std::env::temp_dir().join(format!( + let dir = crate::test_tmp::temp_path(format!( "ps5u-mesh-{name}-{}-{}", std::process::id(), new_id() @@ -7134,7 +7134,7 @@ mod tests { #[test] fn a_refused_request_takes_back_only_what_it_made() { - let root = std::env::temp_dir().join(format!("ps5u-mesh-prep-{}", new_id())); + let root = crate::test_tmp::temp_path(format!("ps5u-mesh-prep-{}", new_id())); std::fs::create_dir_all(&root).unwrap(); // A new folder: all of it goes. let fresh = root.join("fresh"); @@ -7303,7 +7303,7 @@ mod tests { #[test] fn a_local_folder_is_checked_before_use() { - let root = std::env::temp_dir().join(format!("mesh-check-{}", new_id())); + let root = crate::test_tmp::temp_path(format!("mesh-check-{}", new_id())); std::fs::create_dir_all(root.join("has")).unwrap(); std::fs::write(root.join("has").join("one.txt"), b"1").unwrap(); std::fs::write(root.join("file.txt"), b"x").unwrap(); @@ -7335,7 +7335,7 @@ mod tests { #[test] fn a_local_walk_skips_markers_trash_and_clutter() { - let dir = std::env::temp_dir().join(format!("mesh-walk-{}", new_id())); + let dir = crate::test_tmp::temp_path(format!("mesh-walk-{}", new_id())); std::fs::create_dir_all(dir.join("sub")).unwrap(); std::fs::create_dir_all(dir.join(TRASH).join("2026-01-01")).unwrap(); std::fs::write(dir.join(MARKER), b"x").unwrap(); diff --git a/engine/crates/ps5upload-engine/src/mgmt_route.rs b/engine/crates/ps5upload-engine/src/mgmt_route.rs index 7c17191b0..ac3664562 100644 --- a/engine/crates/ps5upload-engine/src/mgmt_route.rs +++ b/engine/crates/ps5upload-engine/src/mgmt_route.rs @@ -95,7 +95,7 @@ mod tests { /// A paired loopback AVA1 console running `handler`, and the transport over its pool. async fn console(tag: &str, handler: RpcHandler) -> Arc { - let base = std::env::temp_dir().join(format!("p5-route-{tag}-{}", std::process::id())); + let base = crate::test_tmp::temp_path(format!("p5-route-{tag}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&base); let ava = base.join("ava"); std::fs::create_dir_all(&ava).unwrap(); @@ -161,7 +161,7 @@ mod tests { #[tokio::test(flavor = "multi_thread")] async fn a_console_without_ava1_is_helper_not_ava1() { // Nothing listens on this address: the transport has no session to open. - let base = std::env::temp_dir().join(format!("p5-route-none-{}", std::process::id())); + let base = crate::test_tmp::temp_path(format!("p5-route-none-{}", std::process::id())); std::fs::create_dir_all(&base).unwrap(); let pool: &'static Pool = Box::leak(Box::new(Pool::new(base).with_addr("127.0.0.1:1"))); let t: Arc = Arc::new(AvaTransport::with_pool(pool)); diff --git a/engine/crates/ps5upload-engine/src/migrate_6.rs b/engine/crates/ps5upload-engine/src/migrate_6.rs index 347afe846..de5618ef9 100644 --- a/engine/crates/ps5upload-engine/src/migrate_6.rs +++ b/engine/crates/ps5upload-engine/src/migrate_6.rs @@ -105,7 +105,7 @@ mod tests { use std::sync::Mutex; fn temp(tag: &str) -> std::path::PathBuf { - let d = std::env::temp_dir().join(format!("migrate6-{tag}-{}", std::process::id())); + let d = crate::test_tmp::temp_path(format!("migrate6-{tag}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&d); std::fs::create_dir_all(&d).unwrap(); d diff --git a/engine/crates/ps5upload-engine/src/payload_updates_api.rs b/engine/crates/ps5upload-engine/src/payload_updates_api.rs index 094553b9b..7cd0af958 100644 --- a/engine/crates/ps5upload-engine/src/payload_updates_api.rs +++ b/engine/crates/ps5upload-engine/src/payload_updates_api.rs @@ -202,6 +202,7 @@ mod tests { status: 404, location: None, content_length: Some(0), + retry_at: None, body: Box::new(std::io::Cursor::new(Vec::new())), }) } @@ -247,7 +248,7 @@ mod tests { } async fn serve(tag: &str) -> Harness { - let dir = std::env::temp_dir().join(format!( + let dir = crate::test_tmp::temp_path(format!( "ps5upload-payload-updates-{tag}-{}", std::process::id() )); diff --git a/engine/crates/ps5upload-engine/src/payloads_api.rs b/engine/crates/ps5upload-engine/src/payloads_api.rs index 385bac672..2ba197c36 100644 --- a/engine/crates/ps5upload-engine/src/payloads_api.rs +++ b/engine/crates/ps5upload-engine/src/payloads_api.rs @@ -4,18 +4,19 @@ //! The library's folder is `PS5UPLOAD_PAYLOADS_DIR` (the desktop app points its sidecar at its //! own cache), else `payloads` under the engine's data folder. //! -//! ps5upload no longer downloads payloads: users get a payload from its project page and send -//! the file. The routes that used to download (or add a repo or a payload list to download from) -//! answer 410 `payload_downloads_removed` with where to get the file. +//! The built-in catalogue is a list of links: its payloads are never downloaded (their old download +//! routes answer 410 `payload_downloads_removed` with where to get the file). The payload sources a +//! user adds (`/api/payloads/repos`) are: their releases are read when asked, and their file is +//! downloaded when asked, never in the background. use axum::{ extract::{Path, Query, State}, http::StatusCode, response::{IntoResponse, Response}, - routing::{delete, get, post}, + routing::{delete, get, post, put}, Json, Router, }; -use ps5upload_core::payload_library::{Library, LibraryError, PayloadInfo}; +use ps5upload_core::payload_library::{Library, LibraryError, PayloadInfo, SourceError}; use serde::Deserialize; use serde_json::json; @@ -53,6 +54,27 @@ fn status_of(code: &str) -> StatusCode { } } +/// The status for a payload source's error code. +fn source_status(code: &str) -> StatusCode { + match code { + c if c.starts_with("url_") => StatusCode::BAD_REQUEST, + "invalid_file_name" | "needs_file" => StatusCode::BAD_REQUEST, + "unknown_source" | "project_not_found" | "no_matching_file" => StatusCode::NOT_FOUND, + "rate_limited" => StatusCode::TOO_MANY_REQUESTS, + other => status_of(other), + } +} + +/// A payload source's error: `{error, code, retry_at?}` (`retry_at`: when the host said to ask +/// again, seconds since the Unix epoch). +fn source_error(e: &SourceError) -> Response { + let mut body = json!({ "error": e.message, "code": e.code }); + if let Some(at) = e.retry_at { + body["retry_at"] = json!(at); + } + (source_status(&e.code), Json(body)).into_response() +} + pub(crate) fn library_error(e: &LibraryError) -> Response { ( status_of(e.code), @@ -116,6 +138,27 @@ impl Api { } } +impl Api { + /// As [`Api::run`], for the payload sources' calls and their errors. + async fn run_source( + &self, + f: impl FnOnce(Library) -> Result + Send + 'static, + ) -> Response { + let Some(lib) = self.0.clone() else { + return no_library(); + }; + match tokio::task::spawn_blocking(move || f(lib)).await { + Ok(Ok(v)) => (StatusCode::OK, Json(v)).into_response(), + Ok(Err(e)) => source_error(&e), + Err(e) => ( + StatusCode::INTERNAL_SERVER_ERROR, + Json(json!({ "error": e.to_string() })), + ) + .into_response(), + } + } +} + pub fn router() -> Router { // A merge, so the API description's generator follows it to the routes. Router::new().merge(router_with(library())) @@ -124,8 +167,11 @@ pub fn router() -> Router { fn router_with(library: Option) -> Router { Router::new() .route("/api/payloads", get(list)) - .route("/api/payloads/repos", post(add_repo)) + .route("/api/payloads/repos", get(list_repos).post(add_repo)) + .route("/api/payloads/repos/preview", post(preview_repo)) .route("/api/payloads/repos/{id}", delete(remove_repo)) + .route("/api/payloads/repos/{id}/file", put(set_repo_file)) + .route("/api/payloads/repos/{id}/download", post(download_repo)) .route("/api/payloads/sources", get(list_sources).post(add_source)) .route("/api/payloads/sources/refresh", post(refresh_sources)) .route("/api/payloads/sources/{id}", delete(remove_source)) @@ -200,17 +246,78 @@ async fn download(State(api): State, Path(id): Path) -> Response { downloads_removed(downloads_removed_text(info.as_ref())) } -/// POST /api/payloads/repos: refused (410 `payload_downloads_removed`). Repos added earlier stay -/// listed and can be removed. -async fn add_repo() -> Response { - downloads_removed( - "ps5upload no longer downloads payloads, so repos can't be added: get the payload from \ - its project page and send the file." - .to_string(), - ) +#[derive(Deserialize, Default)] +struct SourcesQuery { + #[serde(default)] + check: Option, + #[serde(default)] + force: Option, } -/// DELETE /api/payloads/repos/{id} → {removed} +fn is_yes(v: &Option) -> bool { + matches!(v.as_deref(), Some("1") | Some("true")) +} + +/// GET /api/payloads/repos?check=1&force=1 → {sources}: the payload sources the user added. +/// Without `check`, nothing asks the network (a release list read in the last ten minutes is +/// shown). With it, each source's releases are read (a list from the last ten minutes is used +/// unless `force`). +async fn list_repos(State(api): State, Query(q): Query) -> Response { + let (check, force) = (is_yes(&q.check), is_yes(&q.force)); + api.run_source(move |lib| Ok(json!({ "sources": lib.user_sources(check, force)? }))) + .await +} + +#[derive(Deserialize)] +struct PreviewBody { + url: String, +} + +/// POST /api/payloads/repos/preview {url} → the project's newest releases with `.elf` and `.bin` +/// files, for picking the file. Saves nothing. +async fn preview_repo(State(api): State, Json(b): Json) -> Response { + api.run_source(move |lib| lib.preview_user_source(&b.url)) + .await +} + +#[derive(Deserialize)] +struct AddBody { + url: String, + file_name: String, +} + +/// POST /api/payloads/repos {url, file_name} → the source: adds a project as a payload source +/// with the file picked from its releases (adding one again changes its file). Asks no network. +async fn add_repo(State(api): State, Json(b): Json) -> Response { + api.run_source(move |lib| lib.add_user_source(&b.url, &b.file_name)) + .await +} + +#[derive(Deserialize)] +struct FileBody { + file_name: String, +} + +/// PUT /api/payloads/repos/{id}/file {file_name} → the source: change the file it downloads, or +/// pick it for a source added before 12.6.0. +async fn set_repo_file( + State(api): State, + Path(id): Path, + Json(b): Json, +) -> Response { + api.run_source(move |lib| lib.set_user_source_file(&id, &b.file_name)) + .await +} + +/// POST /api/payloads/repos/{id}/download → the source: downloads the newest release's file into +/// the payload folder (through a temporary file, checked against its size and the release's +/// checksum file when there is one). The copy it replaces stays if anything fails. +async fn download_repo(State(api): State, Path(id): Path) -> Response { + api.run_source(move |lib| lib.download_user_source(&id)) + .await +} + +/// DELETE /api/payloads/repos/{id} → {removed}: the source and its downloaded file. async fn remove_repo(State(api): State, Path(id): Path) -> Response { api.run(move |lib| Ok(json!({ "removed": lib.remove_custom_repo(&id)? }))) .await @@ -279,12 +386,16 @@ mod tests { } async fn serve(tag: &str) -> Harness { - let dir = std::env::temp_dir().join(format!( + serve_lib(tag, Library::new).await + } + + async fn serve_lib(tag: &str, make: impl FnOnce(std::path::PathBuf) -> Library) -> Harness { + let dir = crate::test_tmp::temp_path(format!( "ps5upload-payloads-api-{tag}-{}", std::process::id() )); let _ = std::fs::remove_dir_all(&dir); - let app: Router = router_with(Some(Library::new(dir.join("payloads")))); + let app: Router = router_with(Some(make(dir.join("payloads")))); let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let base = format!("http://{}", listener.local_addr().unwrap()); tokio::spawn(async move { @@ -324,6 +435,19 @@ mod tests { .await .unwrap() } + async fn put(&self, path: &str, body: Value) -> (u16, Value) { + let (agent, url) = (self.agent.clone(), format!("{}{path}", self.base)); + tokio::task::spawn_blocking(move || { + let mut r = agent + .put(&url) + .header("content-type", "application/json") + .send(body.to_string()) + .unwrap(); + (r.status().as_u16(), read_body(&mut r)) + }) + .await + .unwrap() + } async fn delete(&self, path: &str) -> (u16, Value) { let (agent, url) = (self.agent.clone(), format!("{}{path}", self.base)); tokio::task::spawn_blocking(move || { @@ -387,11 +511,7 @@ mod tests { ); let (status, v) = h.post("/api/payloads/nope/download", json!({})).await; assert_eq!((status, v["code"].as_str()), (410, Some(DOWNLOADS_REMOVED))); - for path in [ - "/api/payloads/repos", - "/api/payloads/sources", - "/api/payloads/sources/refresh", - ] { + for path in ["/api/payloads/sources", "/api/payloads/sources/refresh"] { let (status, v) = h .post(path, json!({"host": "github.com", "owner": "a", "name": "b", "url": "https://x.org/p.json"})) .await; @@ -408,6 +528,161 @@ mod tests { assert_eq!((status, v["removed"].clone()), (200, json!(false))); } + /// One scripted answer: status, body, and when to ask again. + type Answer = (u16, Vec, Option); + + /// A made-up GitHub: url → answer. Unknown urls answer 404. + #[derive(Default)] + struct FakeHost(std::sync::Mutex>); + + impl FakeHost { + fn answer(&self, url: &str, status: u16, body: &[u8], retry_at: Option) { + self.0 + .lock() + .unwrap() + .insert(url.to_string(), (status, body.to_vec(), retry_at)); + } + } + + impl ps5upload_core::payload_library::HttpClient for FakeHost { + fn get( + &self, + url: &str, + _: Option<&str>, + _: ps5upload_core::payload_library::FetchKind, + ) -> Result { + let (status, body, retry_at) = + self.0 + .lock() + .unwrap() + .get(url) + .cloned() + .unwrap_or((404, Vec::new(), None)); + Ok(ps5upload_core::payload_library::HttpResponse { + status, + location: None, + content_length: Some(body.len() as u64), + retry_at, + body: Box::new(std::io::Cursor::new(body)), + }) + } + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn a_source_is_added_checked_downloaded_and_removed() { + let host = std::sync::Arc::new(FakeHost::default()); + let api_url = "https://api.github.com/repos/me/kstuff/releases?per_page=10"; + let file_url = "https://github.com/me/kstuff/releases/download/v1.6.0/kstuff-v1.6.0.elf"; + let mut elf = b"\x7FELF".to_vec(); + elf.resize(64, 7); + let list = json!([{ + "tag_name": "v1.6.0", "name": "kstuff 1.6.0", "published_at": "2026-11-01T00:00:00Z", + "html_url": "https://github.com/me/kstuff/releases/tag/v1.6.0", + "assets": [{ "name": "kstuff-v1.6.0.elf", "browser_download_url": file_url, "size": 64 }], + }]); + host.answer(api_url, 200, list.to_string().as_bytes(), None); + host.answer(file_url, 200, &elf, None); + let fake = host.clone(); + let h = serve_lib("sources", move |dir| Library::with_http(dir, fake)).await; + + let (status, v) = h.get("/api/payloads/repos").await; + assert_eq!((status, v["sources"].clone()), (200, json!([]))); + + let url = "https://github.com/me/kstuff"; + let (status, v) = h + .post("/api/payloads/repos/preview", json!({ "url": url })) + .await; + assert_eq!(status, 200, "{v}"); + assert_eq!(v["releases"][0]["files"][0]["pattern"], "kstuff-v*.elf"); + + let (status, v) = h + .post( + "/api/payloads/repos", + json!({ "url": url, "file_name": "kstuff-v1.6.0.elf" }), + ) + .await; + assert_eq!(status, 200, "{v}"); + let id = v["id"].as_str().unwrap().to_string(); + assert!(v.get("have").is_none()); + + let (_, v) = h.get("/api/payloads/repos?check=1").await; + assert_eq!(v["sources"][0]["latest"]["tag"], "v1.6.0"); + + let (status, v) = h + .post(&format!("/api/payloads/repos/{id}/download"), json!({})) + .await; + assert_eq!(status, 200, "{v}"); + assert_eq!(v["have"]["size"], 64); + assert_eq!(v["have"]["sha256"].as_str().unwrap().len(), 64); + let path = v["have"]["path"].as_str().unwrap().to_string(); + assert_eq!(std::fs::read(&path).unwrap(), elf); + // The library lists it as a local copy too, so a send by id finds it. + let (_, v) = h.get("/api/payloads").await; + assert!(v["local"] + .as_array() + .unwrap() + .iter() + .any(|l| l["payload_id"] == id)); + + let (status, v) = h + .put( + &format!("/api/payloads/repos/{id}/file"), + json!({ "file_name": "x.zip" }), + ) + .await; + assert_eq!( + (status, v["code"].as_str()), + (400, Some("invalid_file_name")) + ); + + let (status, v) = h.delete(&format!("/api/payloads/repos/{id}")).await; + assert_eq!((status, v["removed"].clone()), (200, json!(true))); + assert!(!std::path::Path::new(&path).exists()); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn source_errors_say_why_with_a_fitting_status() { + let host = std::sync::Arc::new(FakeHost::default()); + host.answer( + "https://api.github.com/repos/me/kstuff/releases?per_page=10", + 403, + b"{}", + Some(1_900_000_000), + ); + let fake = host.clone(); + let h = serve_lib("source-errors", move |dir| Library::with_http(dir, fake)).await; + let (status, v) = h + .post( + "/api/payloads/repos/preview", + json!({ "url": "https://github.com/me/kstuff" }), + ) + .await; + assert_eq!((status, v["code"].as_str()), (429, Some("rate_limited"))); + assert_eq!(v["retry_at"], 1_900_000_000); + let (status, v) = h + .post( + "/api/payloads/repos/preview", + json!({ "url": "http://github.com/me/kstuff" }), + ) + .await; + assert_eq!((status, v["code"].as_str()), (400, Some("url_not_https"))); + let (status, v) = h + .post( + "/api/payloads/repos/preview", + json!({ "url": "https://127.0.0.1:19113/a/b" }), + ) + .await; + assert_eq!( + (status, v["code"].as_str()), + (400, Some("url_host_not_allowed")) + ); + let (status, v) = h + .post("/api/payloads/repos/custom-0a/download", json!({})) + .await; + assert_eq!((status, v["code"].as_str()), (404, Some("unknown_source"))); + assert!(!h.dir.join("payloads").exists(), "nothing written"); + } + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn errors_carry_a_code_and_a_fitting_status() { let h = serve("errors").await; diff --git a/engine/crates/ps5upload-engine/src/pkg_install.rs b/engine/crates/ps5upload-engine/src/pkg_install.rs index 37df7c280..b0f11f5b4 100644 --- a/engine/crates/ps5upload-engine/src/pkg_install.rs +++ b/engine/crates/ps5upload-engine/src/pkg_install.rs @@ -4652,7 +4652,7 @@ mod persist_tests { "serve_only": true, "staging_path": null, "created_at_unix": now_unix(), "last_activity_unix": now_unix() }]); - let dir = std::env::temp_dir().join(format!("ps5u-persist-{id}")); + let dir = crate::test_tmp::temp_path(format!("ps5u-persist-{id}")); std::fs::create_dir_all(&dir).unwrap(); let file = dir.join("s.json"); std::fs::write(&file, saved.to_string()).unwrap(); @@ -4663,7 +4663,7 @@ mod persist_tests { /// The same package going to two consoles is two installs, not a retry to refuse. #[test] fn a_rival_is_the_same_package_for_the_same_console() { - let dir = std::env::temp_dir().join(format!("ps5u-rival-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("ps5u-rival-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let pkg = dir.join("game.pkg"); std::fs::write(&pkg, vec![7u8; 64]).unwrap(); @@ -4686,7 +4686,7 @@ mod persist_tests { /// unchanged. #[test] fn sessions_survive_a_restart_while_their_files_do() { - let dir = std::env::temp_dir().join(format!("ps5u-persist-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("ps5u-persist-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let pkg = dir.join("game.pkg"); std::fs::write(&pkg, vec![7u8; 4096]).unwrap(); @@ -4727,7 +4727,7 @@ mod persist_tests { /// "already running" — measured on the Phat, 0 of 820 MB "in flight". #[test] fn a_released_session_stops_blocking_and_is_not_restored() { - let dir = std::env::temp_dir().join(format!("ps5u-release-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("ps5u-release-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let pkg = dir.join("game.pkg"); std::fs::write(&pkg, vec![7u8; 4096]).unwrap(); @@ -5408,7 +5408,7 @@ Marvel's%20Spider-Man%202%20-%20PPSA03016%20-%20v1.4.3%20-%20US%20-%20BASE.pkg"; /// keeps a rename off it (`pkg_name_api`). Another package's session never does. #[test] fn serving_names_the_session_that_reads_a_package() { - let dir = std::env::temp_dir().join(format!("ps5upload-serving-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("ps5upload-serving-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let (a, b) = (dir.join("a.pkg"), dir.join("b.pkg")); std::fs::write(&a, b"a").unwrap(); @@ -5583,7 +5583,7 @@ Marvel's%20Spider-Man%202%20-%20PPSA03016%20-%20v1.4.3%20-%20US%20-%20BASE.pkg"; } fn scratch_dir(tag: &str) -> PathBuf { - let d = std::env::temp_dir().join(format!("ps5upload-crc-{tag}-{}", Uuid::new_v4())); + let d = crate::test_tmp::temp_path(format!("ps5upload-crc-{tag}-{}", Uuid::new_v4())); std::fs::create_dir_all(&d).unwrap(); d } @@ -5884,7 +5884,7 @@ Marvel's%20Spider-Man%202%20-%20PPSA03016%20-%20v1.4.3%20-%20US%20-%20BASE.pkg"; #[test] fn split_range_reads_within_one_part() { - let dir = std::env::temp_dir().join(format!("pkg-test-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("pkg-test-{}", std::process::id())); let _ = std::fs::create_dir_all(&dir); let p1 = dir.join("a.pkg"); std::fs::write(&p1, b"abcdefghij").unwrap(); @@ -5895,7 +5895,7 @@ Marvel's%20Spider-Man%202%20-%20PPSA03016%20-%20v1.4.3%20-%20US%20-%20BASE.pkg"; #[test] fn split_range_crosses_parts() { - let dir = std::env::temp_dir().join(format!("pkg-test2-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("pkg-test2-{}", std::process::id())); let _ = std::fs::create_dir_all(&dir); let p1 = dir.join("a.pkg"); let p2 = dir.join("a.pkg.0"); @@ -5913,7 +5913,7 @@ Marvel's%20Spider-Man%202%20-%20PPSA03016%20-%20v1.4.3%20-%20US%20-%20BASE.pkg"; /// bytes when a chunk crosses into the next part or the reads go backwards. #[test] fn split_range_read_chunk_by_chunk_keeps_the_part_open() { - let dir = std::env::temp_dir().join(format!("pkg-test3-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("pkg-test3-{}", std::process::id())); let _ = std::fs::create_dir_all(&dir); let (p1, p2) = (dir.join("a.pkg"), dir.join("a.pkg.0")); std::fs::write(&p1, b"AAAAaa").unwrap(); @@ -6398,7 +6398,7 @@ mod browser_file_intake_tests { /// and be refused as "an install of this exact package is already running". #[tokio::test] async fn two_copy_link_clicks_at_once_get_one_link() { - let dir = std::env::temp_dir().join(format!("ps5u-link-race-{}", Uuid::new_v4())); + let dir = crate::test_tmp::temp_path(format!("ps5u-link-race-{}", Uuid::new_v4())); std::fs::create_dir_all(&dir).unwrap(); let pkg = dir.join("game.pkg"); let mut bytes: Vec = (0..8192).map(|i| (i * 31 + 7) as u8).collect(); diff --git a/engine/crates/ps5upload-engine/src/pkg_name_api/tests.rs b/engine/crates/ps5upload-engine/src/pkg_name_api/tests.rs index c62bd7eec..17ab51f49 100644 --- a/engine/crates/ps5upload-engine/src/pkg_name_api/tests.rs +++ b/engine/crates/ps5upload-engine/src/pkg_name_api/tests.rs @@ -24,7 +24,7 @@ struct TempDir(PathBuf); impl TempDir { fn new(name: &str) -> Self { static N: AtomicU32 = AtomicU32::new(0); - let dir = std::env::temp_dir().join(format!( + let dir = crate::test_tmp::temp_path(format!( "ps5upload-pkg-name-{}-{}-{name}", std::process::id(), N.fetch_add(1, Ordering::Relaxed) diff --git a/engine/crates/ps5upload-engine/src/profile_image.rs b/engine/crates/ps5upload-engine/src/profile_image.rs index 30f0fe9b2..743379a26 100644 --- a/engine/crates/ps5upload-engine/src/profile_image.rs +++ b/engine/crates/ps5upload-engine/src/profile_image.rs @@ -129,7 +129,7 @@ mod tests { #[test] fn engine_file_paths_still_work() { - let path = std::env::temp_dir().join(format!("avatar-{}", uuid::Uuid::new_v4())); + let path = crate::test_tmp::temp_path(format!("avatar-{}", uuid::Uuid::new_v4())); std::fs::write(&path, b"native image").unwrap(); let bytes = read(path.to_str().unwrap()); std::fs::remove_file(path).unwrap(); diff --git a/engine/crates/ps5upload-engine/src/queue_api.rs b/engine/crates/ps5upload-engine/src/queue_api.rs index ba5720bb2..66ffcb539 100644 --- a/engine/crates/ps5upload-engine/src/queue_api.rs +++ b/engine/crates/ps5upload-engine/src/queue_api.rs @@ -1991,7 +1991,7 @@ mod tests { // And it is what frees the package. let state = crate::pkg_install::PkgInstallState::default(); - let dir = std::env::temp_dir().join(format!("ps5u-queue-release-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("ps5u-queue-release-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let pkg = dir.join("a.pkg"); std::fs::write(&pkg, b"a").unwrap(); diff --git a/engine/crates/ps5upload-engine/src/queue_api_tests.rs b/engine/crates/ps5upload-engine/src/queue_api_tests.rs index d3e559c64..cc713cd6e 100644 --- a/engine/crates/ps5upload-engine/src/queue_api_tests.rs +++ b/engine/crates/ps5upload-engine/src/queue_api_tests.rs @@ -180,7 +180,7 @@ fn engine_on(path: Option, fake: Option<&Fake>) -> Engine { } fn scratch(name: &str) -> PathBuf { - let dir = std::env::temp_dir().join(format!( + let dir = crate::test_tmp::temp_path(format!( "ps5u-queue-{name}-{}-{}", std::process::id(), Uuid::new_v4().simple() diff --git a/engine/crates/ps5upload-engine/src/remote/fetch.rs b/engine/crates/ps5upload-engine/src/remote/fetch.rs index 5e1cc9410..580e172a4 100644 --- a/engine/crates/ps5upload-engine/src/remote/fetch.rs +++ b/engine/crates/ps5upload-engine/src/remote/fetch.rs @@ -918,6 +918,12 @@ pub fn sweep_stale_copies() { /// Where a server folder's metadata files are mirrored for a look at it. The answer points at the /// mirror's icon, so a mirror outlives the request; it goes once it is an hour old. fn inspect_root() -> PathBuf { + if cfg!(test) { + // A folder of the test process's own, removed when it exits. + return crate::test_scratch( + std::env::temp_dir().join(format!("ps5upload-inspect-root-{}", std::process::id())), + ); + } std::env::temp_dir().join("ps5upload-inspect") } @@ -1033,7 +1039,7 @@ mod tests { /// not put over the first (on a drive that folds case, `README.TXT` after `Readme.txt`). #[test] fn a_second_file_under_one_name_does_not_replace_the_first() { - let dir = std::env::temp_dir().join(format!("ps5upload-twins-{}", Uuid::new_v4())); + let dir = crate::test_tmp::temp_path(format!("ps5upload-twins-{}", Uuid::new_v4())); std::fs::create_dir_all(&dir).unwrap(); let local = dir.join("Readme.txt"); let partial = dir.join("Readme.txt.partial"); @@ -1054,7 +1060,7 @@ mod tests { /// goes once nothing is left in it. #[test] fn the_output_sweep_takes_only_what_no_build_is_using() { - let out = std::env::temp_dir().join(format!("ps5upload-source-{}", Uuid::new_v4())); + let out = crate::test_tmp::temp_path(format!("ps5upload-source-{}", Uuid::new_v4())); let root = out.join(OUTPUT_COPY_DIR); let (left, writing, held) = (root.join("left"), root.join("writing"), root.join("held")); for d in [&left, &writing, &held] { diff --git a/engine/crates/ps5upload-engine/src/remote/name_bytes.rs b/engine/crates/ps5upload-engine/src/remote/name_bytes.rs index 7c805bd7e..c6d33225a 100644 --- a/engine/crates/ps5upload-engine/src/remote/name_bytes.rs +++ b/engine/crates/ps5upload-engine/src/remote/name_bytes.rs @@ -157,7 +157,7 @@ mod tests { assert_eq!(encode(&decode(raw)), raw); // The file system here takes such a name. let name = decode(b"\xFF\xFE.bin"); - let path = std::env::temp_dir().join(format!("ps5u-name-{}-{name}", std::process::id())); + let path = crate::test_tmp::temp_path(format!("ps5u-name-{}-{name}", std::process::id())); std::fs::write(&path, b"x").expect("a name with the stand-ins can be made here"); std::fs::remove_file(&path).unwrap(); } diff --git a/engine/crates/ps5upload-engine/src/remote/nfs_fs.rs b/engine/crates/ps5upload-engine/src/remote/nfs_fs.rs index d4f893e44..dd57d6c63 100644 --- a/engine/crates/ps5upload-engine/src/remote/nfs_fs.rs +++ b/engine/crates/ps5upload-engine/src/remote/nfs_fs.rs @@ -1646,7 +1646,7 @@ mod tests { fs.create_dir("/t").await.unwrap(); fs.create_dir("/t").await.unwrap(); - let src = std::env::temp_dir().join(format!("nfs-put-{}", std::process::id())); + let src = crate::test_tmp::temp_path(format!("nfs-put-{}", std::process::id())); std::fs::write(&src, &all[..3_000_000]).unwrap(); let sent = Arc::new(std::sync::atomic::AtomicU64::new(0)); let add = Arc::clone(&sent); diff --git a/engine/crates/ps5upload-engine/src/remote/store.rs b/engine/crates/ps5upload-engine/src/remote/store.rs index f3320a3dc..c9874c9c9 100644 --- a/engine/crates/ps5upload-engine/src/remote/store.rs +++ b/engine/crates/ps5upload-engine/src/remote/store.rs @@ -130,11 +130,15 @@ pub fn data_dir() -> Option { /// and fills the Docker Desktop VM's disk), and on Fedora and Arch desktops it is RAM. Neither is a /// place for tens of gigabytes. pub fn staging_root() -> PathBuf { - staging_root_from( - std::env::var_os("PS5UPLOAD_STAGING_DIR"), - // A test's copies stay in the temp folder, not in the user's data folder. - if cfg!(test) { None } else { data_dir() }, - ) + let pinned = std::env::var_os("PS5UPLOAD_STAGING_DIR"); + // A test's copies stay in a temp folder of the test process's own (removed when it exits), + // not in the user's data folder. + if cfg!(test) && pinned.as_ref().is_none_or(|v| v.is_empty()) { + return crate::test_scratch( + std::env::temp_dir().join(format!("ps5upload-staging-{}", std::process::id())), + ); + } + staging_root_from(pinned, data_dir()) } fn staging_root_from(pinned: Option, data: Option) -> PathBuf { @@ -472,7 +476,7 @@ fn decrypt(key: &[u8; 32], blob: &str) -> Option { #[cfg(test)] pub(crate) fn test_dir() -> PathBuf { - let d = std::env::temp_dir().join(format!("ps5upload-remote-{}", uuid::Uuid::new_v4())); + let d = crate::test_tmp::temp_path(format!("ps5upload-remote-{}", uuid::Uuid::new_v4())); std::fs::create_dir_all(&d).unwrap(); d } diff --git a/engine/crates/ps5upload-engine/src/remote_download.rs b/engine/crates/ps5upload-engine/src/remote_download.rs index e7c7b4241..78fcb9cf4 100644 --- a/engine/crates/ps5upload-engine/src/remote_download.rs +++ b/engine/crates/ps5upload-engine/src/remote_download.rs @@ -857,7 +857,7 @@ mod tests { #[test] fn an_existing_file_is_refused_unless_the_user_chose_resume_or_replace() { - let dir = std::env::temp_dir().join(format!("ps5u-dl-takeover-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("ps5u-dl-takeover-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let path = dir.join("game.pkg"); let partial = partial_path(&path); @@ -886,7 +886,7 @@ mod tests { /// start; only a complete one gets the real name. #[test] fn a_whole_download_replaces_the_partial_and_is_named_only_when_complete() { - let dir = std::env::temp_dir().join(format!("ps5u-dl-whole-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("ps5u-dl-whole-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let path = dir.join("game.pkg"); let partial = partial_path(&path); @@ -997,7 +997,7 @@ mod tests { } fn scratch(tag: &str) -> PathBuf { - let d = std::env::temp_dir().join(format!("ps5u-dl-{tag}-{}", uuid::Uuid::new_v4())); + let d = crate::test_tmp::temp_path(format!("ps5u-dl-{tag}-{}", uuid::Uuid::new_v4())); std::fs::create_dir_all(&d).unwrap(); d } diff --git a/engine/crates/ps5upload-engine/src/remote_pkg.rs b/engine/crates/ps5upload-engine/src/remote_pkg.rs index f4df3a38f..7fc1bd029 100644 --- a/engine/crates/ps5upload-engine/src/remote_pkg.rs +++ b/engine/crates/ps5upload-engine/src/remote_pkg.rs @@ -197,26 +197,116 @@ pub(crate) const ORIGIN_CHANGED: &str = "the file at this link changed while it was being read, so what was \ read so far can't be finished with it; start again"; -/// Whether a 200 to `If-Range` means another file. The body is the origin's whole current file, so -/// its length and date say more than the validator: a mirror that spells its ETag differently (or -/// a new one per response) serves the same bytes. Without a date to compare, a validator that had -/// been honoured and no longer is means the file changed; one never honoured says nothing. -fn origin_changed_on_200( +/// How many of the file's first bytes are kept from its first read, to tell the same file from +/// another one when an origin stops matching its own validator (see [`judge_whole_answer`]). A +/// package's header is in there, and it carries digests of the whole package. +const HEAD_SAMPLE: u64 = 64 * 1024; + +/// What a 200 to `If-Range` (the whole current file instead of the range) says about the file. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum WholeAnswer { + /// Another file: `.0` names the evidence (for the log). + Changed(&'static str), + /// The same file (its first bytes match): this node just does not match the validator. + Same, + /// Nothing that tells it apart from a node with validators of its own: not a change. + Unknown, +} + +/// The headers of a 200 to `If-Range` that [`judge_whole_answer`] looks at. +#[derive(Debug, Default, Clone, Copy)] +struct WholeHeaders<'a> { + content_length: Option, + content_encoding: Option<&'a str>, + last_modified: Option<&'a str>, +} + +/// A body sent with an encoding (gzip, br) has a Content-Length and bytes that are not the file's. +fn encoded(content_encoding: Option<&str>) -> bool { + content_encoding.is_some_and(|e| { + let e = e.trim(); + !e.is_empty() && !e.eq_ignore_ascii_case("identity") + }) +} + +/// Two HTTP dates as one origin's nodes may spell them: spacing and letter case aside. +fn same_date(a: &str, b: &str) -> bool { + let norm = |s: &str| { + s.split_whitespace() + .collect::>() + .join(" ") + .to_ascii_lowercase() + }; + norm(a) == norm(b) +} + +/// A strong ETag as given; `None` for a weak (`W/"…"`) or empty one. +fn strong_etag(v: Option<&str>) -> Option<&str> { + v.map(str::trim) + .filter(|e| !e.is_empty() && !e.starts_with("W/")) +} + +/// Whether the file behind a link changed, from a 200 to `If-Range`. Big files are served by many +/// nodes (CDN edges, mirrors behind one name), and each may have its own ETag and Last-Modified for +/// the very same bytes, so a validator that stops matching proves nothing by itself. The file +/// counts as changed only on evidence that holds whichever node answered: +/// +/// 1. Its size: the 200's Content-Length differs from the size the install started with (only for +/// a body sent as it is, with no Content-Encoding). A 206 whose Content-Range total differs is +/// the same evidence (see `read_into`). +/// 2. Same size, and the file's first bytes are known (kept from its first read): the 200's first +/// bytes against them. Different is a change; the same is the same file, whatever its +/// validators say. +/// 3. Same size, first bytes not known (a resumed download that never read the start): a +/// Last-Modified that differs from the one the install started with, and only from an origin +/// that has been consistent (`consistent`): it honoured `If-Range` before, and none of its +/// answers so far carried another date or another strong ETag. +/// +/// Weak ETags, missing validators, validators only some answers carry and ETags that differ +/// between answers are unknown, never a change: an ETag alone never decides. A change found here +/// is still asked once more, on another connection, before the read is failed (`fetch_piece`). +fn judge_whole_answer( known: &OriginValidators, total_size: u64, - content_length: Option, - last_modified: Option<&str>, - validator_honoured: bool, -) -> bool { - if content_length.is_some_and(|l| l != total_size) { - return true; + whole: WholeHeaders<'_>, + head: Option<(&[u8], &[u8])>, + consistent: bool, +) -> WholeAnswer { + let plain = !encoded(whole.content_encoding); + if plain && whole.content_length.is_some_and(|l| l != total_size) { + return WholeAnswer::Changed("its size"); + } + if let (true, Some((known_head, got))) = (plain, head) { + return if known_head == got { + WholeAnswer::Same + } else { + WholeAnswer::Changed("its first bytes") + }; } - match (known.last_modified.as_deref(), last_modified) { - (Some(a), Some(b)) => a.trim() != b.trim(), - _ => validator_honoured, + match (known.last_modified.as_deref(), whole.last_modified) { + (Some(a), Some(b)) if consistent && !same_date(a, b) => WholeAnswer::Changed("its date"), + _ => WholeAnswer::Unknown, } } +/// Whether a 206's validators say the origin's nodes disagree with the ones the install started +/// with (another date, or another strong ETag): a date that differs later then says nothing. +fn validators_disagree( + known: &OriginValidators, + etag: Option<&str>, + last_modified: Option<&str>, +) -> bool { + let other_date = matches!( + (known.last_modified.as_deref(), last_modified), + (Some(a), Some(b)) if !same_date(a, b) + ); + let other_etag = matches!( + (strong_etag(known.etag.as_deref()), strong_etag(etag)), + (Some(a), Some(b)) if a != b + ); + other_date || other_etag +} + /// `bytes 5-9/100` as (5, Some(100)); a `*` total is `None`. pub(crate) fn parse_content_range(value: &str) -> Option<(u64, Option)> { let spec = value.trim().strip_prefix("bytes")?.trim_start(); @@ -237,6 +327,11 @@ pub struct RemoteSource { validators: OriginValidators, /// The origin honoured `If-Range` at least once. validator_honoured: std::sync::atomic::AtomicBool, + /// Every 206 so far carried the probe's date and strong ETag, or none: its nodes agree, so a + /// date that differs later can mean a change (rule 3 of [`judge_whole_answer`]). + validators_consistent: std::sync::atomic::AtomicBool, + /// The file's first bytes (up to [`HEAD_SAMPLE`]) as first read, to compare a 200 with. + head_sample: std::sync::OnceLock>, /// Its `If-Range` turned out to be unusable (an ETag per response, say): not sent any more. validator_off: std::sync::atomic::AtomicBool, /// The file changed: every later read fails at once, with the reason. @@ -851,6 +946,8 @@ impl RemoteSource { total_size, validators: OriginValidators::default(), validator_honoured: std::sync::atomic::AtomicBool::new(false), + validators_consistent: std::sync::atomic::AtomicBool::new(true), + head_sample: std::sync::OnceLock::new(), validator_off: std::sync::atomic::AtomicBool::new(false), origin_changed: std::sync::atomic::AtomicBool::new(false), window_bytes, @@ -1407,6 +1504,8 @@ impl RemoteSource { let mut stalls = 0u32; let mut attempts = 0u32; let mut last_err = String::from("no attempt was made"); + // The answer just before this one also said the file changed. + let mut change_seen = false; while filled < len { if self.stopped() { return Err(FETCH_STOPPED.to_string()); @@ -1433,7 +1532,12 @@ impl RemoteSource { attempts += 1; let from = start + filled; let to = start + len - 1; - match self.read_into(agent, from, to, &mut dst[filled as usize..]) { + let answer = self.read_into(agent, from, to, &mut dst[filled as usize..]); + let was_change_seen = std::mem::replace( + &mut change_seen, + matches!(answer, Err(FetchErr::OriginChanged)), + ); + match answer { Ok((0, ttfb)) => { stat.record_ttfb(ttfb); stalls += 1; @@ -1474,9 +1578,10 @@ impl RemoteSource { return Err(FETCH_STOPPED.to_string()); } } - // Said once more on another connection in case a mirror answered: the second answer - // settles it, and asking any longer would only read a package that cannot be used. - Err(FetchErr::OriginChanged) if stalls > 0 => { + // Said once more on another connection in case a mirror answered: two such answers + // in a row settle it (an earlier timeout or short read does not count as one), and + // asking any longer would only read a package that cannot be used. + Err(FetchErr::OriginChanged) if was_change_seen => { self.origin_changed.store(true, Ordering::Relaxed); return Err(ORIGIN_CHANGED.to_string()); } @@ -1512,7 +1617,10 @@ impl RemoteSource { let mut request = agent .get(&self.url) .header("User-Agent", "ps5upload") - .header("Range", &format!("bytes={start}-{end}")); + .header("Range", &format!("bytes={start}-{end}")) + // The file's own bytes: a compressed answer's length and bytes are not the file's, + // and would read as another file (see `judge_whole_answer`). + .header("Accept-Encoding", "identity"); if let Some(v) = if_range { request = request.header("If-Range", v); } @@ -1536,19 +1644,50 @@ impl RemoteSource { // `If-Range` did not match: the whole current file is on its way instead of the range. if status == 200 && if_range.is_some() { let content_length = header("content-length").and_then(|v| v.trim().parse().ok()); - if origin_changed_on_200( + let content_encoding = header("content-encoding"); + let last_modified = header("last-modified"); + // The whole file starts at its first byte: read as many as were kept from the start. + let known_head = self.head_sample.get(); + let got_head = known_head + .filter(|_| !encoded(content_encoding.as_deref())) + .and_then(|known| { + let mut got = Vec::with_capacity(known.len()); + let mut body = resp.into_body().into_reader().take(known.len() as u64); + body.read_to_end(&mut got).ok()?; + // A body cut short tells nothing about the bytes it did not send. + (got.len() == known.len()).then_some(got) + }); + let verdict = judge_whole_answer( &self.validators, self.total_size, - content_length, - header("last-modified").as_deref(), - self.validator_honoured.load(Ordering::Relaxed), - ) { + WholeHeaders { + content_length, + content_encoding: content_encoding.as_deref(), + last_modified: last_modified.as_deref(), + }, + known_head + .zip(got_head.as_deref()) + .map(|(k, g)| (k.as_slice(), g)), + self.validator_honoured.load(Ordering::Relaxed) + && self.validators_consistent.load(Ordering::Relaxed), + ); + if let WholeAnswer::Changed(evidence) = verdict { + // What decided it, for a bug report; never the link's path or query. + crate::log_info!( + "url-install origin {}: the file looks changed ({evidence}) at offset {start}", + log_host(&self.url) + ); return Err(FetchErr::OriginChanged); } - // The same file: this origin's validator just cannot be used. + // The same file, or nothing says otherwise: this node's validator just cannot be used. if !self.validator_off.swap(true, Ordering::Relaxed) { crate::log_info!( - "url-install origin: it does not honour its own validator; going on without one" + "url-install origin: it does not honour its own validator ({}); going on without one", + if verdict == WholeAnswer::Same { + "same first bytes" + } else { + "no evidence of a change" + } ); } return Err(FetchErr::Other( @@ -1569,7 +1708,12 @@ impl RemoteSource { .as_deref() .and_then(parse_content_range) { - if got_total.is_some_and(|t| t != self.total_size) { + if let Some(t) = got_total.filter(|t| *t != self.total_size) { + crate::log_info!( + "url-install origin {}: the file looks changed (its size: {t}, not {}) at offset {start}", + log_host(&self.url), + self.total_size + ); return Err(FetchErr::OriginChanged); } if got_start != start { @@ -1581,6 +1725,18 @@ impl RemoteSource { if if_range.is_some() { self.validator_honoured.store(true, Ordering::Relaxed); } + if validators_disagree( + &self.validators, + header("etag").as_deref(), + header("last-modified").as_deref(), + ) && self.validators_consistent.swap(false, Ordering::Relaxed) + { + crate::log_info!( + "url-install origin {}: its answers carry other validators than the first; \ + only its size and first bytes can tell a change now", + log_host(&self.url) + ); + } let mut reader = resp.into_body().into_reader(); let mut filled = 0usize; while filled < dst.len() { @@ -1607,6 +1763,12 @@ impl RemoteSource { let mut scratch = [0u8; 1]; let _ = reader.read(&mut scratch); } + // The file's first bytes, kept from the first read of them: what a 200 to `If-Range` is + // compared with (`judge_whole_answer`). + let sample = HEAD_SAMPLE.min(self.total_size) as usize; + if start == 0 && filled >= sample && self.head_sample.get().is_none() { + let _ = self.head_sample.set(dst[..sample].to_vec()); + } Ok((filled as u64, ttfb)) } } @@ -1917,10 +2079,15 @@ pub(crate) mod origin_tests { out } - /// What `If-Range` not matching sends: the head of the whole file. The body is never read. - fn whole(len: usize, headers: &str) -> Vec { - format!("HTTP/1.1 200 OK\r\nContent-Length: {len}\r\n{headers}Connection: close\r\n\r\n") - .into_bytes() + /// What `If-Range` not matching sends: the whole current file. Only its start is ever read. + fn whole(data: &[u8], headers: &str) -> Vec { + let mut out = format!( + "HTTP/1.1 200 OK\r\nContent-Length: {}\r\n{headers}Connection: close\r\n\r\n", + data.len() + ) + .into_bytes(); + out.extend_from_slice(data); + out } const TEST_WINDOW: u64 = 64 * 1024; @@ -1979,7 +2146,7 @@ pub(crate) mod origin_tests { let addr = spawn_scripted_origin(move |asked| { let (data, tag) = &*served.lock().unwrap(); if asked.if_range.as_deref().is_some_and(|v| v != tag) { - return whole(data.len(), ""); + return whole(data, ""); } partial(data, asked, &format!("ETag: {tag}\r\n")) }); @@ -2009,7 +2176,7 @@ pub(crate) mod origin_tests { let served = data.clone(); let addr = spawn_scripted_origin(move |asked| { if asked.if_range.is_some() { - return whole(served.len(), "ETag: \"fresh\"\r\n"); + return whole(&served, "ETag: \"fresh\"\r\n"); } partial(&served, asked, "ETag: \"fresh\"\r\n") }); @@ -2030,7 +2197,7 @@ pub(crate) mod origin_tests { let addr = spawn_scripted_origin(move |asked| { // The first answer is the mirror the probe saw, the second another one. if asked.if_range.is_some() && counter.fetch_add(1, Ordering::SeqCst) == 1 { - return whole(served.len(), &format!("Last-Modified: {DATE}\r\n")); + return whole(&served, &format!("Last-Modified: {DATE}\r\n")); } partial(&served, asked, &format!("Last-Modified: {DATE}\r\n")) }); @@ -2049,53 +2216,218 @@ pub(crate) mod origin_tests { assert!(!src.origin_changed.load(Ordering::Relaxed)); } + /// The rule `judge_whole_answer` documents, case by case. #[test] - fn a_new_length_or_date_on_a_200_is_a_change() { + fn only_strong_evidence_makes_a_200_a_change() { let known = OriginValidators { etag: Some("\"a\"".into()), - last_modified: Some("old".into()), + last_modified: Some("Tue, 03 Nov 2026 10:00:00 GMT".into()), }; let total = 100; - assert!(origin_changed_on_200( - &known, - total, - Some(99), - Some("old"), - false - )); - assert!(origin_changed_on_200( - &known, - total, - Some(100), - Some("new"), - false - )); - assert!(!origin_changed_on_200( + let h = |len: Option, enc: Option<&'static str>, date: Option<&'static str>| { + WholeHeaders { + content_length: len, + content_encoding: enc, + last_modified: date, + } + }; + let judge = |w, head, consistent| judge_whole_answer(&known, total, w, head, consistent); + let new_date = Some("Wed, 04 Nov 2026 10:00:00 GMT"); + + // 1. Another size is another file, whatever else is said. + assert_eq!( + judge(h(Some(99), None, None), None, false), + WholeAnswer::Changed("its size") + ); + // ...but not the length of a compressed body. + assert_eq!( + judge(h(Some(40), Some("gzip"), None), None, false), + WholeAnswer::Unknown + ); + assert_eq!( + judge(h(Some(99), Some("identity"), None), None, false), + WholeAnswer::Changed("its size") + ); + + // 2. Same size: the first bytes decide, over any date. + let a: &[u8] = b"head"; + assert_eq!( + judge(h(Some(100), None, new_date), Some((a, b"head")), true), + WholeAnswer::Same + ); + assert_eq!( + judge(h(Some(100), None, None), Some((a, b"HEAD")), false), + WholeAnswer::Changed("its first bytes") + ); + + // 3. No first bytes: a new date, only from an origin that has been consistent. + assert_eq!( + judge(h(Some(100), None, new_date), None, true), + WholeAnswer::Changed("its date") + ); + assert_eq!( + judge(h(Some(100), None, new_date), None, false), + WholeAnswer::Unknown + ); + // The same date spelled with other spacing or case is the same date. + assert_eq!( + judge( + h(Some(100), None, Some("tue, 03 Nov 2026 10:00:00 gmt")), + None, + true + ), + WholeAnswer::Unknown + ); + // No date: nothing to go by, however the ETag went (it never decides on its own). + assert_eq!( + judge(h(Some(100), None, None), None, true), + WholeAnswer::Unknown + ); + assert_eq!(judge(h(None, None, None), None, true), WholeAnswer::Unknown); + } + + #[test] + fn nodes_with_other_validators_are_told_apart() { + let known = OriginValidators { + etag: Some("\"a\"".into()), + last_modified: Some("Tue, 03 Nov 2026 10:00:00 GMT".into()), + }; + assert!(!validators_disagree(&known, Some("\"a\""), None)); + assert!(!validators_disagree(&known, None, None)); + // A weak ETag says nothing about the bytes. + assert!(!validators_disagree(&known, Some("W/\"b\""), None)); + assert!(validators_disagree(&known, Some("\"b\""), None)); + assert!(validators_disagree( &known, - total, - Some(100), - Some("old"), - true - )); - // No date to go by: honoured before and not now says it changed; never honoured says - // nothing about the file. - let no_date = etag("\"a\""); - assert!(origin_changed_on_200( - &no_date, - total, - Some(100), - None, - true - )); - assert!(!origin_changed_on_200( - &no_date, - total, - Some(100), None, - false + Some("Wed, 04 Nov 2026 10:00:00 GMT") )); } + /// Weak ETags (here a new one on every answer) are never sent as `If-Range` and never read as + /// a change. + #[test] + fn a_weak_etag_is_not_a_change() { + let data = test_bytes(7); + let served = data.clone(); + let n = Arc::new(AtomicUsize::new(0)); + let (count, if_ranges) = (n.clone(), Arc::new(AtomicUsize::new(0))); + let seen = if_ranges.clone(); + let addr = spawn_scripted_origin(move |asked| { + if asked.if_range.is_some() { + seen.fetch_add(1, Ordering::SeqCst); + } + let i = count.fetch_add(1, Ordering::SeqCst); + partial(&served, asked, &format!("ETag: W/\"n{i}\"\r\n")) + }); + let src = source_of(addr, etag("W/\"n0\"")); + let got = src.read_range(0, TEST_TOTAL as u64 - 1).expect("read"); + assert_eq!(got, data); + assert!(!src.origin_changed()); + assert_eq!(if_ranges.load(Ordering::SeqCst), 0); + } + + /// Two nodes behind one name: one sends the ETag the probe saw and honours it, the other drops + /// the ETag (and so answers `If-Range` with the whole file). Same bytes: not a change, whether + /// or not the file's start was read first. + #[test] + fn an_etag_only_some_answers_carry_is_not_a_change() { + for from_start in [true, false] { + let data = test_bytes(8); + let served = data.clone(); + let n = Arc::new(AtomicUsize::new(0)); + let count = n.clone(); + let addr = spawn_scripted_origin(move |asked| { + if count.fetch_add(1, Ordering::SeqCst).is_multiple_of(2) { + return partial(&served, asked, "ETag: \"a\"\r\n"); + } + if asked.if_range.is_some() { + return whole(&served, ""); + } + partial(&served, asked, "") + }); + let src = source_of(addr, etag("\"a\"")); + if !from_start { + let far = src + .read_range(2 * TEST_WINDOW, 3 * TEST_WINDOW - 1) + .expect("the same file"); + assert_eq!( + far, + data[2 * TEST_WINDOW as usize..3 * TEST_WINDOW as usize] + ); + } + let got = src.read_range(0, TEST_TOTAL as u64 - 1).expect("read"); + assert_eq!(got, data, "from_start={from_start}"); + assert!(!src.origin_changed(), "from_start={from_start}"); + } + } + + /// Mirrors that keep their own ETag and date for the very same bytes (nginx derives its ETag + /// from the file's time, which differs between copies): the size is the same, and the first + /// bytes, read at the start, show it is the same file. + #[test] + fn two_nodes_with_their_own_strong_etags_for_the_same_bytes_are_not_a_change() { + let data = test_bytes(9); + let served = data.clone(); + let n = Arc::new(AtomicUsize::new(0)); + let count = n.clone(); + let node = |tag: &str, date: &str| format!("ETag: \"{tag}\"\r\nLast-Modified: {date}\r\n"); + let (a, b) = ( + node("a", "Tue, 03 Nov 2026 10:00:00 GMT"), + node("b", "Wed, 04 Nov 2026 11:00:00 GMT"), + ); + let addr = spawn_scripted_origin(move |asked| { + let on_a = count.fetch_add(1, Ordering::SeqCst).is_multiple_of(2); + let headers = if on_a { &a } else { &b }; + if !on_a && asked.if_range.is_some() { + return whole(&served, headers); + } + partial(&served, asked, headers) + }); + let src = source_of( + addr, + OriginValidators { + etag: Some("\"a\"".into()), + last_modified: Some("Tue, 03 Nov 2026 10:00:00 GMT".into()), + }, + ); + // The start first, as a link install does (it reads the package's header). + assert_eq!(src.read_range(0, 1023).unwrap(), data[..1024].to_vec()); + let got = src.read_range(0, TEST_TOTAL as u64 - 1).expect("read"); + assert_eq!(got, data); + assert!(!src.origin_changed()); + } + + /// A real change: the file at the link is replaced with a longer one half-way. Its size says + /// so on every node, as a 206's total and as a 200's length. + #[test] + fn a_file_whose_size_changes_is_a_change() { + for answer_whole in [false, true] { + let state = Arc::new(Mutex::new(test_bytes(10))); + let served = state.clone(); + let addr = spawn_scripted_origin(move |asked| { + let data = served.lock().unwrap().clone(); + if answer_whole && data.len() != TEST_TOTAL && asked.if_range.is_some() { + return whole(&data, "ETag: \"two\"\r\n"); + } + partial(&data, asked, "") + }); + let src = source_of(addr, etag("\"one\"")); + assert_eq!( + src.read_range(0, 15).unwrap(), + test_bytes(10)[..16].to_vec() + ); + let mut longer = test_bytes(11); + longer.extend_from_slice(&[0; 7]); + *state.lock().unwrap() = longer; + let err = src + .read_range(2 * TEST_WINDOW, 2 * TEST_WINDOW + 1023) + .expect_err("another file"); + assert!(err.to_string().contains("changed"), "{err}"); + assert!(src.origin_changed(), "answer_whole={answer_whole}"); + } + } + /// A 206 is only the bytes asked for if it says so. #[test] fn a_range_from_another_offset_is_not_copied() { diff --git a/engine/crates/ps5upload-engine/src/remove_backport.rs b/engine/crates/ps5upload-engine/src/remove_backport.rs index 273b29f4f..bc22c1017 100644 --- a/engine/crates/ps5upload-engine/src/remove_backport.rs +++ b/engine/crates/ps5upload-engine/src/remove_backport.rs @@ -606,7 +606,7 @@ mod tests { use ps5upload_fpkg::sample::VerifyMode; use std::sync::atomic::AtomicBool; - let root = std::env::temp_dir().join(format!("ps5upload-rmbp-{}", std::process::id())); + let root = crate::test_tmp::temp_path(format!("ps5upload-rmbp-{}", std::process::id())); let _ = std::fs::remove_dir_all(&root); let game_dir = root.join("PPSA01234"); let mut on_disk = game(0x1200_0038); diff --git a/engine/crates/ps5upload-engine/src/rp_live_tests.rs b/engine/crates/ps5upload-engine/src/rp_live_tests.rs index 882a1f537..5c3dc6efe 100644 --- a/engine/crates/ps5upload-engine/src/rp_live_tests.rs +++ b/engine/crates/ps5upload-engine/src/rp_live_tests.rs @@ -222,7 +222,7 @@ fn readers_are_capped() { // ---- With ffmpeg: real codec data through the feed and muxer, checked by ffprobe ---- pub(crate) fn tmp_dir(name: &str) -> PathBuf { - let d = std::env::temp_dir().join(format!("ps5upload-rp-live-{name}-{}", std::process::id())); + let d = crate::test_tmp::temp_path(format!("ps5upload-rp-live-{name}-{}", std::process::id())); std::fs::create_dir_all(&d).unwrap(); d } diff --git a/engine/crates/ps5upload-engine/src/rp_stream_api.rs b/engine/crates/ps5upload-engine/src/rp_stream_api.rs index 2e194a500..b8a40f543 100644 --- a/engine/crates/ps5upload-engine/src/rp_stream_api.rs +++ b/engine/crates/ps5upload-engine/src/rp_stream_api.rs @@ -2558,7 +2558,7 @@ mod slot_held_tests { #[test] fn the_last_session_survives_a_restart_on_disk() { - let dir = std::env::temp_dir().join(format!("ps5u-rp-slot-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("ps5u-rp-slot-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let p = dir.join(SLOT_FILE); let mut m = std::collections::HashMap::new(); diff --git a/engine/crates/ps5upload-engine/src/save_backup.rs b/engine/crates/ps5upload-engine/src/save_backup.rs index 0a409186c..1fdd99e01 100644 --- a/engine/crates/ps5upload-engine/src/save_backup.rs +++ b/engine/crates/ps5upload-engine/src/save_backup.rs @@ -2853,7 +2853,7 @@ mod tests { #[test] fn a_file_that_cannot_be_read_is_kept_aside_not_emptied() { - let dir = std::env::temp_dir().join(format!("ps5u-state-load-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("ps5u-state-load-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); let path = dir.join("save-sync.json"); @@ -3287,7 +3287,7 @@ mod tests { /// Save Data's "Backed up …" line: the newest of each game and user, tags left off. #[test] fn the_newest_backup_of_each_game_and_user() { - let base = std::env::temp_dir().join(format!("ps5u-latest-{}", std::process::id())); + let base = crate::test_tmp::temp_path(format!("ps5u-latest-{}", std::process::id())); let _ = std::fs::remove_dir_all(&base); let t = base.join("PPSA01234"); std::fs::create_dir_all(&t).unwrap(); @@ -3349,7 +3349,7 @@ mod tests { /// it carries files; the sender's sce_sys never goes in. #[test] fn a_shared_save_is_checked_and_its_sce_sys_left_out() { - let base = std::env::temp_dir().join(format!("ps5u-share-{}", std::process::id())); + let base = crate::test_tmp::temp_path(format!("ps5u-share-{}", std::process::id())); let _ = std::fs::remove_dir_all(&base); let dir = base.join("PPSA01234"); std::fs::create_dir_all(dir.join(SYS_DIR)).unwrap(); @@ -3382,7 +3382,7 @@ mod tests { /// the API has no sign-in, so a path from a request must not reach the rest of the disk). #[test] fn a_ps4_import_reads_only_inside_the_backup_folder() { - let base = std::env::temp_dir().join(format!("ps5u-src-{}", std::process::id())); + let base = crate::test_tmp::temp_path(format!("ps5u-src-{}", std::process::id())); let root = base.join("backups"); let inside = root .join("PS4 10.0.0.2 1 2026-10-30 1200") @@ -3750,7 +3750,7 @@ mod tests { #[test] fn a_loose_save_restores_only_its_own_entries() { - let dir = std::env::temp_dir().join(format!("ps5u-ps2-loose-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("ps5u-ps2-loose-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(dir.join("Mcd002.ps2")).unwrap(); std::fs::write(dir.join("Mcd001.ps2"), b"card").unwrap(); @@ -3941,7 +3941,7 @@ mod tests { #[test] fn backups_are_listed_newest_first_and_names_cannot_escape() { - let dir = std::env::temp_dir().join(format!("ps5upload-savebk-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("ps5upload-savebk-{}", std::process::id())); let title = dir.join("PPSA01234"); std::fs::create_dir_all(&title).unwrap(); for s in [ @@ -3991,7 +3991,7 @@ mod tests { st.move_to(""); assert_eq!(st.read_dirs(), ["/old", "/new"]); - let base = std::env::temp_dir().join(format!("ps5u-dirs-{}", std::process::id())); + let base = crate::test_tmp::temp_path(format!("ps5u-dirs-{}", std::process::id())); let _ = std::fs::remove_dir_all(&base); let (old, new) = (base.join("old"), base.join("new")); for (dir, stamp) in [ diff --git a/engine/crates/ps5upload-engine/src/save_backup_pass.rs b/engine/crates/ps5upload-engine/src/save_backup_pass.rs index 5b52cc8ff..0a0fc76d5 100644 --- a/engine/crates/ps5upload-engine/src/save_backup_pass.rs +++ b/engine/crates/ps5upload-engine/src/save_backup_pass.rs @@ -2018,7 +2018,7 @@ mod tests { /// what was left, and leaves what was verified alone. #[test] fn a_run_continues_after_an_engine_restart() { - let dir = std::env::temp_dir().join(format!("ps5u-pass-restart-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("ps5u-pass-restart-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); let file = dir.join("save-backup-runs.json"); @@ -2328,8 +2328,10 @@ mod tests { }; assert_eq!(on_share(&fs).len(), 1, "{how:?}"); let zip = fs.bytes(&on_share(&fs)[0]).unwrap(); - let local = std::env::temp_dir() - .join(format!("ps5u-folder-{}-{how:?}.zip", std::process::id())); + let local = crate::test_tmp::temp_path(format!( + "ps5u-folder-{}-{how:?}.zip", + std::process::id() + )); std::fs::write(&local, &zip).unwrap(); assert_eq!(folders::noted_path(&local).as_deref(), Some(GRIM)); let _ = std::fs::remove_file(&local); diff --git a/engine/crates/ps5upload-engine/src/save_backup_run.rs b/engine/crates/ps5upload-engine/src/save_backup_run.rs index 6cb9e226c..ef0053059 100644 --- a/engine/crates/ps5upload-engine/src/save_backup_run.rs +++ b/engine/crates/ps5upload-engine/src/save_backup_run.rs @@ -824,7 +824,7 @@ mod tests { use super::*; fn temp(name: &str) -> PathBuf { - let d = std::env::temp_dir().join(format!("ps5u-runs-{}-{name}", std::process::id())); + let d = crate::test_tmp::temp_path(format!("ps5u-runs-{}-{name}", std::process::id())); let _ = std::fs::remove_dir_all(&d); std::fs::create_dir_all(&d).unwrap(); d.join(FILE) diff --git a/engine/crates/ps5upload-engine/src/save_backup_server.rs b/engine/crates/ps5upload-engine/src/save_backup_server.rs index dd269e0d6..fe6a35fce 100644 --- a/engine/crates/ps5upload-engine/src/save_backup_server.rs +++ b/engine/crates/ps5upload-engine/src/save_backup_server.rs @@ -1806,7 +1806,7 @@ mod tests { } fn scratch(name: &str) -> PathBuf { - let d = std::env::temp_dir().join(format!("ps5u-srvbk-{}-{name}", std::process::id())); + let d = crate::test_tmp::temp_path(format!("ps5u-srvbk-{}-{name}", std::process::id())); let _ = std::fs::remove_dir_all(&d); std::fs::create_dir_all(&d).unwrap(); d diff --git a/engine/crates/ps5upload-engine/src/save_folders.rs b/engine/crates/ps5upload-engine/src/save_folders.rs index 8c1eea8f7..66262ce0e 100644 --- a/engine/crates/ps5upload-engine/src/save_folders.rs +++ b/engine/crates/ps5upload-engine/src/save_folders.rs @@ -1338,7 +1338,7 @@ mod tests { } fn scratch(name: &str) -> PathBuf { - let d = std::env::temp_dir().join(format!("ps5u-folders-{}-{name}", std::process::id())); + let d = crate::test_tmp::temp_path(format!("ps5u-folders-{}-{name}", std::process::id())); let _ = std::fs::remove_dir_all(&d); std::fs::create_dir_all(&d).unwrap(); d diff --git a/engine/crates/ps5upload-engine/src/server_out/tests.rs b/engine/crates/ps5upload-engine/src/server_out/tests.rs index b662ebb57..f8b7676e0 100644 --- a/engine/crates/ps5upload-engine/src/server_out/tests.rs +++ b/engine/crates/ps5upload-engine/src/server_out/tests.rs @@ -36,8 +36,10 @@ impl Nas { .id; let dest = ServerDest::with(remote, &id, "/out", tokio::runtime::Handle::current()).unwrap(); - let dir = - std::env::temp_dir().join(format!("ps5upload-toserver-{tag}-{}", uuid::Uuid::new_v4())); + let dir = crate::test_tmp::temp_path(format!( + "ps5upload-toserver-{tag}-{}", + uuid::Uuid::new_v4() + )); std::fs::create_dir_all(&dir).unwrap(); Self { mem, dest, dir } } @@ -754,7 +756,7 @@ async fn against_a_real_server() { std::process::id() ); let dest = ServerDest::with(remote, &id, &run, tokio::runtime::Handle::current()).unwrap(); - let scratch = std::env::temp_dir().join(format!("ps5u-e2e-{}", uuid::Uuid::new_v4())); + let scratch = crate::test_tmp::temp_path(format!("ps5u-e2e-{}", uuid::Uuid::new_v4())); std::fs::create_dir_all(&scratch).unwrap(); let (src, _) = game(&scratch, 24 << 20); let never = Arc::new(AtomicBool::new(false)); diff --git a/engine/crates/ps5upload-engine/src/share/manifest.rs b/engine/crates/ps5upload-engine/src/share/manifest.rs index 8a1c17f66..dd25587ab 100644 --- a/engine/crates/ps5upload-engine/src/share/manifest.rs +++ b/engine/crates/ps5upload-engine/src/share/manifest.rs @@ -465,7 +465,7 @@ pub(crate) mod tests { use super::*; pub(crate) fn tmp(name: &str) -> PathBuf { - let d = std::env::temp_dir().join(format!( + let d = crate::test_tmp::temp_path(format!( "ps5u-share-{name}-{}-{}", std::process::id(), crate::join_net::random_b64(6).unwrap() diff --git a/engine/crates/ps5upload-engine/src/share/mod.rs b/engine/crates/ps5upload-engine/src/share/mod.rs index ee27ebede..98fbd3930 100644 --- a/engine/crates/ps5upload-engine/src/share/mod.rs +++ b/engine/crates/ps5upload-engine/src/share/mod.rs @@ -349,7 +349,9 @@ pub fn sweep_left_shares() { fn shares_dir() -> Option { if cfg!(test) { - return Some(std::env::temp_dir().join(format!("ps5u-shares-{}", std::process::id()))); + return Some(crate::test_scratch( + std::env::temp_dir().join(format!("ps5u-shares-{}", std::process::id())), + )); } crate::remote::store::data_dir().map(|d| d.join("shares")) } diff --git a/engine/crates/ps5upload-engine/src/shared_state.rs b/engine/crates/ps5upload-engine/src/shared_state.rs index 611392848..a42a923a9 100644 --- a/engine/crates/ps5upload-engine/src/shared_state.rs +++ b/engine/crates/ps5upload-engine/src/shared_state.rs @@ -365,7 +365,7 @@ mod place_tests { #[test] fn a_directory_that_cannot_be_made_is_nowhere_too() { - let file = std::env::temp_dir().join(format!("shared-state-{}", std::process::id())); + let file = crate::test_tmp::temp_path(format!("shared-state-{}", std::process::id())); std::fs::write(&file, b"x").unwrap(); let got = place_from(Some(file.join("sub").display().to_string()), None, false); let _ = std::fs::remove_file(&file); @@ -375,7 +375,7 @@ mod place_tests { #[test] fn tests_stay_in_memory_unless_given_a_directory() { assert_eq!(place_from(None, None, true), Place::Memory); - let dir = std::env::temp_dir().join(format!("shared-state-dir-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("shared-state-dir-{}", std::process::id())); let got = place_from(Some(dir.display().to_string()), None, true); assert_eq!(got, Place::File(dir.join("web-shared.json"))); let _ = std::fs::remove_dir_all(&dir); @@ -383,7 +383,7 @@ mod place_tests { #[test] fn the_data_directory_is_used_when_nothing_is_set() { - let dir = std::env::temp_dir().join(format!("shared-state-data-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("shared-state-data-{}", std::process::id())); let got = place_from(None, Some(dir.clone()), false); assert_eq!(got, Place::File(dir.join("state").join("web-shared.json"))); let _ = std::fs::remove_dir_all(&dir); @@ -418,7 +418,7 @@ mod tests { #[test] fn saved_and_loaded_through_the_file() { - let dir = std::env::temp_dir().join(format!("ps5upload-shared-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("ps5upload-shared-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let file = dir.join("web-shared.json"); let mut docs = Docs::new(); @@ -431,7 +431,8 @@ mod tests { #[test] fn a_damaged_file_loads_empty_and_is_kept_under_a_new_name() { - let dir = std::env::temp_dir().join(format!("ps5upload-shared-bad-{}", std::process::id())); + let dir = + crate::test_tmp::temp_path(format!("ps5upload-shared-bad-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let file = dir.join("web-shared.json"); std::fs::write(&file, b"{ not json").unwrap(); diff --git a/engine/crates/ps5upload-engine/src/source_removal.rs b/engine/crates/ps5upload-engine/src/source_removal.rs index c7f3cf343..26ac4f43f 100644 --- a/engine/crates/ps5upload-engine/src/source_removal.rs +++ b/engine/crates/ps5upload-engine/src/source_removal.rs @@ -343,7 +343,7 @@ mod tests { fn scratch(tag: &str) -> PathBuf { let root = - std::env::temp_dir().join(format!("ps5upload-srcrm-{tag}-{}", std::process::id())); + crate::test_tmp::temp_path(format!("ps5upload-srcrm-{tag}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&root); std::fs::create_dir_all(&root).unwrap(); std::fs::canonicalize(&root).unwrap() diff --git a/engine/crates/ps5upload-engine/src/state_io.rs b/engine/crates/ps5upload-engine/src/state_io.rs index ec7053f48..af5e212bd 100644 --- a/engine/crates/ps5upload-engine/src/state_io.rs +++ b/engine/crates/ps5upload-engine/src/state_io.rs @@ -215,7 +215,7 @@ mod tests { if process_ids().map(|(u, _)| u) == Some(0) { return; } - let dir = std::env::temp_dir().join(format!("ps5u-probe-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("ps5u-probe-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); assert!(probe_write(&dir).is_ok()); std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o555)).unwrap(); @@ -249,7 +249,7 @@ mod tests { if process_ids().map(|(u, _)| u) == Some(0) { return; } - let dir = std::env::temp_dir().join(format!("ps5u-ro-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("ps5u-ro-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o555)).unwrap(); let err = crate::remote::store::Store::open(&dir.join("state")).err(); @@ -265,7 +265,7 @@ mod tests { #[cfg(unix)] #[test] fn a_writable_dir_opens() { - let dir = std::env::temp_dir().join(format!("ps5u-rw-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("ps5u-rw-{}", std::process::id())); let r = crate::remote::store::Store::open(&dir); let _ = std::fs::remove_dir_all(&dir); assert!(r.is_ok()); diff --git a/engine/crates/ps5upload-engine/src/tailnet_engine.rs b/engine/crates/ps5upload-engine/src/tailnet_engine.rs index 6083be97d..aeec9214b 100644 --- a/engine/crates/ps5upload-engine/src/tailnet_engine.rs +++ b/engine/crates/ps5upload-engine/src/tailnet_engine.rs @@ -1023,7 +1023,7 @@ mod tests { } fn tmp(tag: &str) -> PathBuf { - let d = std::env::temp_dir().join(format!("tn-{tag}-{}", std::process::id())); + let d = crate::test_tmp::temp_path(format!("tn-{tag}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&d); let _ = std::fs::create_dir_all(&d); d diff --git a/engine/crates/ps5upload-engine/src/telemetry.rs b/engine/crates/ps5upload-engine/src/telemetry.rs index 9c6e6b5d2..ec8028bc3 100644 --- a/engine/crates/ps5upload-engine/src/telemetry.rs +++ b/engine/crates/ps5upload-engine/src/telemetry.rs @@ -723,7 +723,7 @@ mod refused_upload_tests { default_ps5_addr: "127.0.0.1".to_string(), events_tx: events_tx.clone(), }; - let missing = std::env::temp_dir().join(format!( + let missing = crate::test_tmp::temp_path(format!( "ps5upload-untagged-{}-missing.bin", std::process::id() )); diff --git a/engine/crates/ps5upload-engine/src/telemetry/tests.rs b/engine/crates/ps5upload-engine/src/telemetry/tests.rs index a61587ef3..963d9d66f 100644 --- a/engine/crates/ps5upload-engine/src/telemetry/tests.rs +++ b/engine/crates/ps5upload-engine/src/telemetry/tests.rs @@ -1,7 +1,7 @@ use super::*; fn tmp(name: &str) -> PathBuf { - let d = std::env::temp_dir().join(format!("ps5up-telem-{name}-{}", std::process::id())); + let d = crate::test_tmp::temp_path(format!("ps5up-telem-{name}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&d); std::fs::create_dir_all(&d).unwrap(); d diff --git a/engine/crates/ps5upload-engine/src/unpack_packs.rs b/engine/crates/ps5upload-engine/src/unpack_packs.rs index 1c2e28a2f..5c0300bb3 100644 --- a/engine/crates/ps5upload-engine/src/unpack_packs.rs +++ b/engine/crates/ps5upload-engine/src/unpack_packs.rs @@ -129,7 +129,7 @@ pub(crate) mod tests { fn temp(name: &str) -> PathBuf { let root = - std::env::temp_dir().join(format!("ps5upload-unpack-{name}-{}", std::process::id())); + crate::test_tmp::temp_path(format!("ps5upload-unpack-{name}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&root); std::fs::create_dir_all(&root).unwrap(); root diff --git a/engine/crates/ps5upload-engine/src/workshop_api.rs b/engine/crates/ps5upload-engine/src/workshop_api.rs index 9ff54d220..7758cdd8e 100644 --- a/engine/crates/ps5upload-engine/src/workshop_api.rs +++ b/engine/crates/ps5upload-engine/src/workshop_api.rs @@ -248,7 +248,7 @@ mod tests { #[test] fn the_setting_round_trips_and_a_missing_file_is_off() { - let dir = std::env::temp_dir().join(format!("ps5u-workshop-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("ps5u-workshop-{}", std::process::id())); let path = dir.join(FILE); let _ = std::fs::remove_file(&path); assert_eq!(read_from(&path), Stored { gentle: false }); diff --git a/engine/crates/ps5upload-engine/src/zstd_runtime.rs b/engine/crates/ps5upload-engine/src/zstd_runtime.rs index 60219f9c0..12c4bad11 100644 --- a/engine/crates/ps5upload-engine/src/zstd_runtime.rs +++ b/engine/crates/ps5upload-engine/src/zstd_runtime.rs @@ -314,7 +314,7 @@ mod tests { } fn cache(name: &str) -> PathBuf { - let dir = std::env::temp_dir().join(format!( + let dir = crate::test_tmp::temp_path(format!( "ps5upload-zstd-runtime-{name}-{}", std::process::id() )); diff --git a/engine/crates/ps5upload-fpkg/src/ampr_pack/image.rs b/engine/crates/ps5upload-fpkg/src/ampr_pack/image.rs index 0b9c4798d..fc22cf1ee 100644 --- a/engine/crates/ps5upload-fpkg/src/ampr_pack/image.rs +++ b/engine/crates/ps5upload-fpkg/src/ampr_pack/image.rs @@ -692,7 +692,7 @@ mod tests { /// are kept as they were. #[test] fn the_overlay_swaps_packed_files_for_the_pack_set() { - let root = std::env::temp_dir().join(format!( + let root = crate::test_tmp::temp_path(format!( "ampr-overlay-{}-{:?}", std::process::id(), std::thread::current().id() @@ -770,7 +770,7 @@ mod tests { /// a packed file edited after the measure fails the read instead of giving other bytes. #[test] fn a_streamed_packed_game_is_the_spooled_one() { - let root = std::env::temp_dir().join(format!( + let root = crate::test_tmp::temp_path(format!( "ampr-streamed-{}-{:?}", std::process::id(), std::thread::current().id() @@ -865,7 +865,7 @@ mod tests { /// the runtime's version and whether it serves packs. #[test] fn readiness_reads_the_games_ampr_emu() { - let root = std::env::temp_dir().join(format!( + let root = crate::test_tmp::temp_path(format!( "ampr-ready-{}-{:?}", std::process::id(), std::thread::current().id() @@ -948,7 +948,7 @@ mod tests { #[test] fn installing_the_runtime_replaces_and_keeps_the_original() { use crate::source::SourceTree; - let root = std::env::temp_dir().join(format!("ps5upload-rt-{}", std::process::id())); + let root = crate::test_tmp::temp_path(format!("ps5upload-rt-{}", std::process::id())); let _ = std::fs::remove_dir_all(&root); std::fs::create_dir_all(root.join("fakelib")).unwrap(); std::fs::write(root.join("eboot.bin"), b"libSceAmpr.prx").unwrap(); diff --git a/engine/crates/ps5upload-fpkg/src/ampr_pack/mod.rs b/engine/crates/ps5upload-fpkg/src/ampr_pack/mod.rs index 89c94f356..9aa91d704 100644 --- a/engine/crates/ps5upload-fpkg/src/ampr_pack/mod.rs +++ b/engine/crates/ps5upload-fpkg/src/ampr_pack/mod.rs @@ -144,7 +144,7 @@ mod tests { struct Dir(PathBuf); impl Dir { fn new(name: &str) -> Self { - let p = std::env::temp_dir().join(format!( + let p = crate::test_tmp::temp_path(format!( "ampr-pack-{}-{name}-{:?}", std::process::id(), std::thread::current().id() diff --git a/engine/crates/ps5upload-fpkg/src/browse.rs b/engine/crates/ps5upload-fpkg/src/browse.rs index 2eac7a64d..37399f21c 100644 --- a/engine/crates/ps5upload-fpkg/src/browse.rs +++ b/engine/crates/ps5upload-fpkg/src/browse.rs @@ -773,7 +773,7 @@ mod tests { } fn scratch(tag: &str) -> PathBuf { - let dir = std::env::temp_dir().join(format!("fpkg-browse-{tag}-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("fpkg-browse-{tag}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); dir diff --git a/engine/crates/ps5upload-fpkg/src/build.rs b/engine/crates/ps5upload-fpkg/src/build.rs index 395e0bc4f..cf145c3e6 100644 --- a/engine/crates/ps5upload-fpkg/src/build.rs +++ b/engine/crates/ps5upload-fpkg/src/build.rs @@ -1106,7 +1106,7 @@ mod tests { #[test] fn inspect_tells_ps4_kinds_apart() { use crate::ps4_pkg::Ps4Kind; - let dir = std::env::temp_dir().join(format!("fpkg-ps4-kinds-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("fpkg-ps4-kinds-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let put = |name: &str| { let path = dir.join(format!("{name}.pkg")); @@ -1157,7 +1157,7 @@ mod tests { /// A build's `.partial` goes on every way out but success, a panic included; kept, it stays. #[test] fn a_leftover_is_removed_unless_kept() { - let dir = std::env::temp_dir().join(format!("fpkg-leftover-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("fpkg-leftover-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let (a, b, c) = ( dir.join("a.partial"), diff --git a/engine/crates/ps5upload-fpkg/src/exfat.rs b/engine/crates/ps5upload-fpkg/src/exfat.rs index bb50ac7ec..edb8d70fe 100644 --- a/engine/crates/ps5upload-fpkg/src/exfat.rs +++ b/engine/crates/ps5upload-fpkg/src/exfat.rs @@ -937,7 +937,7 @@ mod tests { let mut img = image_with_dirs(); let at = 2 * 512 + (cluster as usize - 2) * 4096 + 64 + at; img[at..at + 2].copy_from_slice(&unit.to_le_bytes()); - let path = std::env::temp_dir().join(format!( + let path = crate::test_tmp::temp_path(format!( "fpkg-exfat-{}-bad-name-{cluster}", std::process::id() )); @@ -994,7 +994,7 @@ mod tests { } fn synthetic_at(name: &str) -> (std::path::PathBuf, ExFat) { - let path = std::env::temp_dir().join(format!("fpkg-exfat-{}-{name}", std::process::id())); + let path = crate::test_tmp::temp_path(format!("fpkg-exfat-{}-{name}", std::process::id())); std::fs::write(&path, synthetic_image()).unwrap(); let volume = ExFat::open(&path).unwrap(); (path, volume) @@ -1088,7 +1088,7 @@ mod tests { let at = HEAP + (5 - 2) * CLUSTER; img[at..at + 96].copy_from_slice(&flat(ghost)); let path = - std::env::temp_dir().join(format!("fpkg-exfat-{}-full-root", std::process::id())); + crate::test_tmp::temp_path(format!("fpkg-exfat-{}-full-root", std::process::id())); std::fs::write(&path, img).unwrap(); let mut volume = ExFat::open(&path).unwrap(); let walked = volume.walk_tree(); @@ -1111,7 +1111,7 @@ mod tests { // big.bin's stream record is the root's second record: valid length 4096 of 8192. let at = HEAP + (4 - 2) * CLUSTER + 32; img[at + 8..at + 16].copy_from_slice(&4096u64.to_le_bytes()); - let path = std::env::temp_dir().join(format!("fpkg-exfat-{}-valid", std::process::id())); + let path = crate::test_tmp::temp_path(format!("fpkg-exfat-{}-valid", std::process::id())); std::fs::write(&path, img).unwrap(); let mut volume = ExFat::open(&path).unwrap(); let files = volume.walk().unwrap(); @@ -1163,7 +1163,7 @@ mod tests { #[test] fn empty_directories_are_kept() { let path = - std::env::temp_dir().join(format!("fpkg-exfat-{}-empty-dirs", std::process::id())); + crate::test_tmp::temp_path(format!("fpkg-exfat-{}-empty-dirs", std::process::id())); std::fs::write(&path, image_with_dirs()).unwrap(); let source = ExFatSource::open(&path).unwrap(); std::fs::remove_file(&path).ok(); @@ -1181,7 +1181,7 @@ mod tests { // `nest/deeper` now starts where the root does. let at = 2 * 512 + (9 - 2) * 4096 + 32 + 20; img[at..at + 4].copy_from_slice(&4u32.to_le_bytes()); - let path = std::env::temp_dir().join(format!("fpkg-exfat-{}-cycle", std::process::id())); + let path = crate::test_tmp::temp_path(format!("fpkg-exfat-{}-cycle", std::process::id())); std::fs::write(&path, img).unwrap(); let err = ExFatSource::open(&path).err().unwrap(); std::fs::remove_file(&path).ok(); @@ -1196,7 +1196,7 @@ mod tests { // `big.bin`'s stream record: the second record of the root, in cluster 4. let at = 2 * 512 + (4 - 2) * 4096 + 32 + 24; img[at..at + 8].copy_from_slice(&(1u64 << 60).to_le_bytes()); - let path = std::env::temp_dir().join(format!("fpkg-exfat-{}-huge", std::process::id())); + let path = crate::test_tmp::temp_path(format!("fpkg-exfat-{}-huge", std::process::id())); std::fs::write(&path, img).unwrap(); let err = ExFatSource::open(&path).err().unwrap(); std::fs::remove_file(&path).ok(); @@ -1217,7 +1217,7 @@ mod tests { #[test] fn a_short_image_is_refused() { - let dir = std::env::temp_dir().join(format!("fpkg-exfat-short-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("fpkg-exfat-short-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let img = dir.join("short.exfat"); std::fs::write(&img, [0u8; 100]).unwrap(); @@ -1231,7 +1231,7 @@ mod tests { #[test] fn an_image_with_no_exfat_volume_is_refused() { - let dir = std::env::temp_dir().join(format!("fpkg-exfat-none-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("fpkg-exfat-none-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let img = dir.join("blank.exfat"); std::fs::write(&img, [0u8; 4096]).unwrap(); @@ -1245,7 +1245,7 @@ mod tests { #[test] fn a_bogus_cluster_shift_is_refused() { - let dir = std::env::temp_dir().join(format!("fpkg-exfat-shift-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("fpkg-exfat-shift-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let img = dir.join("shift.exfat"); let mut boot = vec![0u8; 8192]; @@ -1267,7 +1267,7 @@ mod tests { /// cap holds. #[test] fn a_cluster_over_32_mib_is_refused() { - let dir = std::env::temp_dir().join(format!("fpkg-exfat-big-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("fpkg-exfat-big-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let img = dir.join("big.exfat"); let mut boot = vec![0u8; 8192]; @@ -1287,7 +1287,7 @@ mod tests { #[test] fn a_heap_past_the_image_is_refused() { - let dir = std::env::temp_dir().join(format!("fpkg-exfat-heap-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("fpkg-exfat-heap-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let img = dir.join("heap.exfat"); let mut boot = vec![0u8; 8192]; @@ -1313,7 +1313,7 @@ mod tests { #[test] fn the_walk_reads_no_more_directory_bytes_than_the_volume_holds() { let path = - std::env::temp_dir().join(format!("fpkg-exfat-{}-dir-budget", std::process::id())); + crate::test_tmp::temp_path(format!("fpkg-exfat-{}-dir-budget", std::process::id())); std::fs::write(&path, image_with_dirs()).unwrap(); let mut volume = ExFat::open(&path).unwrap(); std::fs::remove_file(&path).ok(); @@ -1338,7 +1338,7 @@ mod tests { // And `junk` (the root's eleventh record) runs on over `nest` and `deeper`. let at = at + 3 * 32; img[at..at + 8].copy_from_slice(&(3 * 4096u64).to_le_bytes()); - let path = std::env::temp_dir().join(format!("fpkg-exfat-{}-overlap", std::process::id())); + let path = crate::test_tmp::temp_path(format!("fpkg-exfat-{}-overlap", std::process::id())); std::fs::write(&path, img).unwrap(); let err = ExFatSource::open(&path).err().map(|e| e.to_string()); std::fs::remove_file(&path).ok(); diff --git a/engine/crates/ps5upload-fpkg/src/exfat_write.rs b/engine/crates/ps5upload-fpkg/src/exfat_write.rs index 8d5068a92..eddac5a20 100644 --- a/engine/crates/ps5upload-fpkg/src/exfat_write.rs +++ b/engine/crates/ps5upload-fpkg/src/exfat_write.rs @@ -825,7 +825,7 @@ mod tests { fn out_path(name: &str) -> Out { use std::sync::atomic::{AtomicU64, Ordering}; static NEXT: AtomicU64 = AtomicU64::new(0); - let dir = std::env::temp_dir().join(format!( + let dir = crate::test_tmp::temp_path(format!( "ps5upload-exfatw-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed) diff --git a/engine/crates/ps5upload-fpkg/src/ffpfsc.rs b/engine/crates/ps5upload-fpkg/src/ffpfsc.rs index fa5ba02ef..6e3fbac3c 100644 --- a/engine/crates/ps5upload-fpkg/src/ffpfsc.rs +++ b/engine/crates/ps5upload-fpkg/src/ffpfsc.rs @@ -951,7 +951,7 @@ mod tests { } fn temp(name: &str) -> TempDir { - let d = std::env::temp_dir().join(format!("ffpfsc-{}-{name}", std::process::id())); + let d = crate::test_tmp::temp_path(format!("ffpfsc-{}-{name}", std::process::id())); let _ = std::fs::remove_dir_all(&d); std::fs::create_dir_all(&d).unwrap(); TempDir(d) diff --git a/engine/crates/ps5upload-fpkg/src/lib.rs b/engine/crates/ps5upload-fpkg/src/lib.rs index ddf6674aa..8083502b3 100644 --- a/engine/crates/ps5upload-fpkg/src/lib.rs +++ b/engine/crates/ps5upload-fpkg/src/lib.rs @@ -206,3 +206,8 @@ mod prealloc_tests { assert_eq!(prealloc(usize::MAX), PREALLOC_CAP); } } + +// Test scratch paths removed when the test process exits (engine/test-support/test_tmp.rs). +#[cfg(test)] +#[path = "../../../test-support/test_tmp.rs"] +mod test_tmp; diff --git a/engine/crates/ps5upload-fpkg/src/lih.rs b/engine/crates/ps5upload-fpkg/src/lih.rs index dc8879bd6..c64ef004b 100644 --- a/engine/crates/ps5upload-fpkg/src/lih.rs +++ b/engine/crates/ps5upload-fpkg/src/lih.rs @@ -639,7 +639,7 @@ mod tests { fn the_magic_names_a_patch() { assert!(is_lih(b"\x7FLIH\0\0")); assert!(!is_lih(b"\x7FFIH") && !is_lih(b"\x7FL")); - let dir = std::env::temp_dir().join(format!("fpkg-lih-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("fpkg-lih-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let (patch, whole) = (dir.join("patch.pkg"), dir.join("whole.pkg")); std::fs::write(&patch, b"\x7FLIH and the rest").unwrap(); diff --git a/engine/crates/ps5upload-fpkg/src/naps.rs b/engine/crates/ps5upload-fpkg/src/naps.rs index d921ce343..81e204325 100644 --- a/engine/crates/ps5upload-fpkg/src/naps.rs +++ b/engine/crates/ps5upload-fpkg/src/naps.rs @@ -648,7 +648,7 @@ mod tests { fn outer_file(pkg: &[u8], name: &str) -> Option> { use std::sync::atomic::{AtomicU32, Ordering}; static SEQ: AtomicU32 = AtomicU32::new(0); - let path = std::env::temp_dir().join(format!( + let path = crate::test_tmp::temp_path(format!( "naps-sample-{}-{}-{}.pkg", std::process::id(), name.replace(['/', '.'], "_"), diff --git a/engine/crates/ps5upload-fpkg/src/outer_write.rs b/engine/crates/ps5upload-fpkg/src/outer_write.rs index c867f1167..b66e9afb1 100644 --- a/engine/crates/ps5upload-fpkg/src/outer_write.rs +++ b/engine/crates/ps5upload-fpkg/src/outer_write.rs @@ -700,7 +700,7 @@ mod tests { "UP0000-PPSA01234_00-TESTGAME00000000", &outer.plaintext_digests, ); - let path = std::env::temp_dir().join(format!("outer-big-{}.bin", std::process::id())); + let path = crate::test_tmp::temp_path(format!("outer-big-{}.bin", std::process::id())); std::fs::write(&path, &outer.image).unwrap(); let mut file = crate::PkgFile::open(&path).unwrap(); let fih = crate::fih::Fih { @@ -741,7 +741,7 @@ mod tests { assert_eq!(outer.plaintext_digests.len(), 9); // Round-trip through the reader. - let path = std::env::temp_dir().join(format!("outer-write-{}.bin", std::process::id())); + let path = crate::test_tmp::temp_path(format!("outer-write-{}.bin", std::process::id())); let cnt = crate::cnt::test_support::minimal_cnt( "UP0000-PPSA01234_00-TESTGAME00000000", &outer.plaintext_digests, @@ -819,7 +819,7 @@ mod tests { "the seed slot carries the marker the console serves plaintext for" ); - let path = std::env::temp_dir().join(format!("outer-plain-{}.bin", std::process::id())); + let path = crate::test_tmp::temp_path(format!("outer-plain-{}.bin", std::process::id())); let cnt = crate::cnt::test_support::minimal_cnt( "UP0000-PPSA01234_00-TESTGAME00000000", &outer.plaintext_digests, diff --git a/engine/crates/ps5upload-fpkg/src/pkg_name/tests.rs b/engine/crates/ps5upload-fpkg/src/pkg_name/tests.rs index 6235f3235..79d376e12 100644 --- a/engine/crates/ps5upload-fpkg/src/pkg_name/tests.rs +++ b/engine/crates/ps5upload-fpkg/src/pkg_name/tests.rs @@ -19,7 +19,7 @@ struct TempDir(PathBuf); impl TempDir { fn new(name: &str) -> Self { static N: AtomicU32 = AtomicU32::new(0); - let dir = std::env::temp_dir().join(format!( + let dir = crate::test_tmp::temp_path(format!( "fpkg-name-{}-{}-{name}", std::process::id(), N.fetch_add(1, Ordering::Relaxed) diff --git a/engine/crates/ps5upload-fpkg/src/pkg_source.rs b/engine/crates/ps5upload-fpkg/src/pkg_source.rs index ed432b6ae..673c62509 100644 --- a/engine/crates/ps5upload-fpkg/src/pkg_source.rs +++ b/engine/crates/ps5upload-fpkg/src/pkg_source.rs @@ -1879,7 +1879,7 @@ mod tests { #[test] fn protected_container_entries_read_back_decrypted() { use crate::crypto::DEFAULT_PASSCODE; - let dir = std::env::temp_dir().join(format!("fpkg-protected-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("fpkg-protected-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); let (src, out) = (dir.join("src"), dir.join("out")); let put = |path: &str, data: &[u8]| { @@ -1964,7 +1964,7 @@ mod tests { #[test] fn game_files_kept_only_in_the_container_are_restored() { use crate::crypto::DEFAULT_PASSCODE; - let dir = std::env::temp_dir().join(format!("fpkg-restore-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("fpkg-restore-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); let (src, out) = (dir.join("src"), dir.join("out")); let put = |path: &str, data: &[u8]| { diff --git a/engine/crates/ps5upload-fpkg/src/ps4_pkg_write.rs b/engine/crates/ps5upload-fpkg/src/ps4_pkg_write.rs index 58c01d3f1..82b7c189a 100644 --- a/engine/crates/ps5upload-fpkg/src/ps4_pkg_write.rs +++ b/engine/crates/ps5upload-fpkg/src/ps4_pkg_write.rs @@ -2786,7 +2786,7 @@ mod tests { } fn scratch(name: &str) -> std::path::PathBuf { - let dir = std::env::temp_dir().join(format!( + let dir = crate::test_tmp::temp_path(format!( "ps4w-{}-{}-{name}", std::process::id(), std::time::SystemTime::now() diff --git a/engine/crates/ps5upload-fpkg/src/si.rs b/engine/crates/ps5upload-fpkg/src/si.rs index 86a0f376f..75e034821 100644 --- a/engine/crates/ps5upload-fpkg/src/si.rs +++ b/engine/crates/ps5upload-fpkg/src/si.rs @@ -97,13 +97,36 @@ pub fn read(file: &mut PkgFile) -> Result> { /// CRC-32C of every 64 KiB block before the SI ZIP, little-endian. pub fn chunk_crc_table(file: &mut PkgFile, zip_start: u64) -> Result> { + chunk_crc_table_with(file, zip_start, None, &mut |_| {}) +} + +/// [`chunk_crc_table`], which reads the whole package again: `progress` hears the bytes read so +/// far (of `zip_start`) every 256 blocks and at the end, and it stops with a "cancelled" error +/// once `cancel` is set (#951: a copy check of a 200 GB package sat at 100% through this pass, +/// with Cancel unheard). +pub fn chunk_crc_table_with( + file: &mut PkgFile, + zip_start: u64, + cancel: Option<&std::sync::atomic::AtomicBool>, + progress: &mut dyn FnMut(u64), +) -> Result> { let blocks = zip_start.div_ceil(BLOCK); let mut out = Vec::with_capacity(blocks as usize * 4); for i in 0..blocks { + if i.is_multiple_of(256) { + if crate::workshop::checkpoint_opt(cancel) { + return format_err("cancelled"); + } + progress(i * BLOCK); + } let start = i * BLOCK; let len = (zip_start - start).min(BLOCK) as usize; out.extend_from_slice(&crc32c(&file.read_at(start, len)?).to_le_bytes()); } + if crate::workshop::checkpoint_opt(cancel) { + return format_err("cancelled"); + } + progress(zip_start); Ok(out) } @@ -138,7 +161,7 @@ mod tests { /// not draw, and always catches a wrong first or last one or a wrong length. #[test] fn chunk_crc_sampled_checks_its_draw_and_the_length() { - let path = std::env::temp_dir().join(format!("ps5upload-crc-{}", std::process::id())); + let path = crate::test_tmp::temp_path(format!("ps5upload-crc-{}", std::process::id())); let bytes: Vec = (0..BLOCK * 300).map(|i| (i * 7 % 251) as u8).collect(); std::fs::write(&path, &bytes).unwrap(); let mut f = PkgFile::open(&path).unwrap(); diff --git a/engine/crates/ps5upload-fpkg/src/source.rs b/engine/crates/ps5upload-fpkg/src/source.rs index a0dadbae5..98ddad21b 100644 --- a/engine/crates/ps5upload-fpkg/src/source.rs +++ b/engine/crates/ps5upload-fpkg/src/source.rs @@ -1266,7 +1266,7 @@ mod tests { #[test] fn packed_kind_reads_the_pack_index_magic() { - let base = std::env::temp_dir().join(format!("fpkg-packed-kind-{}", std::process::id())); + let base = crate::test_tmp::temp_path(format!("fpkg-packed-kind-{}", std::process::id())); std::fs::remove_dir_all(&base).ok(); let kind = |name: &str, files: &[(&str, &[u8])]| { let dir = base.join(name); @@ -1296,7 +1296,7 @@ mod tests { /// A folder's `ampr_emu.index` that doesn't read: the finding says why, not only that. #[test] fn a_damaged_index_finding_names_the_reason() { - let dir = std::env::temp_dir().join(format!("fpkg-index-why-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("fpkg-index-why-{}", std::process::id())); std::fs::remove_dir_all(&dir).ok(); std::fs::create_dir_all(&dir).unwrap(); std::fs::write(dir.join("eboot.bin"), b"x").unwrap(); @@ -1323,7 +1323,7 @@ mod tests { /// the progress callback sees the count climb to the total. #[test] fn folder_heads_match_one_at_a_time_and_keep_order() { - let dir = std::env::temp_dir().join(format!("fpkg-heads-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("fpkg-heads-{}", std::process::id())); std::fs::remove_dir_all(&dir).ok(); std::fs::create_dir_all(dir.join("sub")).unwrap(); let mut paths = Vec::new(); @@ -1353,7 +1353,7 @@ mod tests { /// A file that cannot be opened fails the read with its own name, as before. #[test] fn folder_heads_name_the_missing_file() { - let dir = std::env::temp_dir().join(format!("fpkg-heads-miss-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("fpkg-heads-miss-{}", std::process::id())); std::fs::remove_dir_all(&dir).ok(); std::fs::create_dir_all(&dir).unwrap(); for i in 0..40 { @@ -1374,7 +1374,7 @@ mod tests { /// Stop while the headers are read ends the walk as cancelled. #[test] fn folder_heads_stop_when_asked() { - let dir = std::env::temp_dir().join(format!("fpkg-heads-stop-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("fpkg-heads-stop-{}", std::process::id())); std::fs::remove_dir_all(&dir).ok(); std::fs::create_dir_all(&dir).unwrap(); let paths: Vec = (0..2000).map(|i| format!("f{i}.bin")).collect(); @@ -1394,7 +1394,7 @@ mod tests { #[cfg(unix)] #[test] fn symlinks_count_as_their_targets() { - let base = std::env::temp_dir().join(format!("fpkg-symlink-{}", std::process::id())); + let base = crate::test_tmp::temp_path(format!("fpkg-symlink-{}", std::process::id())); let (real, staged) = (base.join("real"), base.join("staged")); std::fs::remove_dir_all(&base).ok(); std::fs::create_dir_all(real.join("sub")).unwrap(); @@ -1415,7 +1415,7 @@ mod tests { #[cfg(unix)] #[test] fn a_dangling_link_and_a_backslash_name_are_refused_by_name() { - let base = std::env::temp_dir().join(format!("fpkg-badname-{}", std::process::id())); + let base = crate::test_tmp::temp_path(format!("fpkg-badname-{}", std::process::id())); std::fs::remove_dir_all(&base).ok(); std::fs::create_dir_all(&base).unwrap(); std::fs::write(base.join("eboot.bin"), b"12345").unwrap(); @@ -1743,7 +1743,7 @@ mod tests { #[test] fn junk_is_skipped_and_sizes_are_recorded() { - let dir = std::env::temp_dir().join(format!("fpkg-scan-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("fpkg-scan-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(dir.join("sce_sys/about")).unwrap(); std::fs::write(dir.join("eboot.bin"), [0u8; 10]).unwrap(); @@ -1773,7 +1773,7 @@ mod tests { #[test] fn content_version_packs_as_bcd() { - let dir = std::env::temp_dir().join(format!("fpkg-ver-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("fpkg-ver-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(dir.join("sce_sys")).unwrap(); std::fs::write( @@ -1791,7 +1791,7 @@ mod tests { #[test] fn a_folder_source_reads_ranges_and_reports_itself() { - let dir = std::env::temp_dir().join(format!("fpkg-tree-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("fpkg-tree-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); std::fs::write(dir.join("eboot.bin"), b"0123456789").unwrap(); @@ -1826,7 +1826,7 @@ mod tests { /// is never called would be invisible, which is the failure this guards. #[test] fn readiness_reports_an_ampr_dependency() { - let dir = std::env::temp_dir().join(format!( + let dir = crate::test_tmp::temp_path(format!( "fpkg-ready-{}-{:?}", std::process::id(), std::thread::current().id() @@ -2009,7 +2009,7 @@ mod tests { #[test] fn readiness_names_the_source_and_its_size() { - let dir = std::env::temp_dir().join(format!("fpkg-named-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("fpkg-named-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(dir.join("sce_sys")).unwrap(); std::fs::write(dir.join("eboot.bin"), [0u8; 1024]).unwrap(); @@ -2039,7 +2039,7 @@ mod tests { #[test] fn an_unknown_source_kind_is_an_error() { - let dir = std::env::temp_dir().join(format!("fpkg-kind-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("fpkg-kind-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); let img = dir.join("game.iso"); @@ -2062,7 +2062,7 @@ mod tests { send::(); send::>(); - let dir = std::env::temp_dir().join(format!("fpkg-send-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("fpkg-send-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); std::fs::write(dir.join("eboot.bin"), b"moved").unwrap(); let mut tree = open(&dir).unwrap(); diff --git a/engine/crates/ps5upload-fpkg/src/verify.rs b/engine/crates/ps5upload-fpkg/src/verify.rs index 1714ab782..c672d9212 100644 --- a/engine/crates/ps5upload-fpkg/src/verify.rs +++ b/engine/crates/ps5upload-fpkg/src/verify.rs @@ -565,7 +565,7 @@ pub fn verify_streaming_sampled( seed: Option, progress: &mut dyn FnMut(u64, u64), ) -> Result { - verify_streaming_inner(path, passcode, seed, None, progress) + verify_streaming_inner(path, passcode, seed, None, progress, &mut |_| {}) } /// [`verify_streaming`] that stops with a "cancelled" error once `cancel` is set (checked @@ -576,7 +576,40 @@ pub fn verify_streaming_cancellable( cancel: &std::sync::atomic::AtomicBool, progress: &mut dyn FnMut(u64, u64), ) -> Result { - verify_streaming_inner(path, passcode, None, Some(cancel), progress) + verify_streaming_inner(path, passcode, None, Some(cancel), progress, &mut |_| {}) +} + +/// The passes a full read of a package makes, in order: what a caller can show beside the +/// progress, which counts both in one total. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Phase { + /// Every block of the image against its digest. + Blocks, + /// The PlayGo chunk CRCs (`playgo-chunk.crc`): a second read of everything before the SI ZIP, + /// in a full check of a debug package that carries one. + PlaygoCrc, +} + +impl Phase { + /// The word an API gives for it. + pub fn as_str(self) -> &'static str { + match self { + Phase::Blocks => "blocks", + Phase::PlaygoCrc => "playgo", + } + } +} + +/// [`verify_streaming_cancellable`] that also says which pass it is on (`phase`, each time it +/// starts one). +pub fn verify_streaming_phased( + path: &Path, + passcode: &str, + cancel: &std::sync::atomic::AtomicBool, + progress: &mut dyn FnMut(u64, u64), + phase: &mut dyn FnMut(Phase), +) -> Result { + verify_streaming_inner(path, passcode, None, Some(cancel), progress, phase) } /// [`verify_streaming_sampled`] that also stops with a "cancelled" error once `cancel` is set @@ -588,7 +621,7 @@ pub fn verify_streaming_controlled( cancel: Option<&std::sync::atomic::AtomicBool>, progress: &mut dyn FnMut(u64, u64), ) -> Result { - verify_streaming_inner(path, passcode, seed, cancel, progress) + verify_streaming_inner(path, passcode, seed, cancel, progress, &mut |_| {}) } fn verify_streaming_inner( @@ -597,6 +630,7 @@ fn verify_streaming_inner( seed: Option, cancel: Option<&std::sync::atomic::AtomicBool>, progress: &mut dyn FnMut(u64, u64), + phase: &mut dyn FnMut(Phase), ) -> Result { let cancelled = || cancel.is_some_and(crate::workshop::checkpoint); if cancelled() { @@ -747,6 +781,23 @@ fn verify_streaming_inner( let sweep = batches.as_ref().map_or(count, |v| { v.iter().map(|b| span(*b).end - span(*b).start).sum::() + (count - data) }); + // A full check also reads everything before the SI ZIP a second time for the PlayGo chunk + // CRCs (#951): counted in the same total, so the progress never says 100% while that pass + // still has a whole package to read. Asked of the SI here only for its size; the check + // itself reads it again below and says what is wrong with it. + let crc_bytes = match seed { + Some(_) => 0, + None => si::read(&mut file).ok().flatten().map_or(0, |s| { + let crc_name = format!("config/{}/playgo-chunk.crc", cnt.content_id); + if s.members.iter().any(|m| m.name == crc_name) { + s.zip_start + } else { + 0 + } + }), + }; + let total = sweep * BLOCK + crc_bytes; + phase(Phase::Blocks); let indices: Box> = match batches { None => Box::new(0..count), Some(v) => Box::new(v.into_iter().flat_map(span).chain(data..count)), @@ -778,14 +829,14 @@ fn verify_streaming_inner( if crate::workshop::checkpoint_opt(cancel) { return format_err("cancelled"); } - progress(done * BLOCK, sweep * BLOCK); + progress(done * BLOCK, total); } } // Every 256 blocks above; a smaller package (or the last few blocks) is checked here. if cancelled() { return format_err("cancelled"); } - progress(done * BLOCK, sweep * BLOCK); + progress(done * BLOCK, total); r.push_counted( Kind::Data, if plaintext_mode { @@ -845,7 +896,17 @@ fn verify_streaming_inner( let stored = file.read_at(m.offset, m.size as usize)?; // Sampled with the sweep: the whole table would read the package again. let ok = match seed { - None => stored == si::chunk_crc_table(&mut file, s.zip_start)?, + None => { + phase(Phase::PlaygoCrc); + let before = sweep * BLOCK; + let table = si::chunk_crc_table_with( + &mut file, + s.zip_start, + cancel, + &mut |read| progress(before + read, total.max(before + read)), + )?; + stored == table + } Some(seed) => si::chunk_crc_sampled(&mut file, s.zip_start, &stored, seed)?, }; r.push( diff --git a/engine/crates/ps5upload-fpkg/src/verify/tests.rs b/engine/crates/ps5upload-fpkg/src/verify/tests.rs index 2b63e80bd..39fc4e5b5 100644 --- a/engine/crates/ps5upload-fpkg/src/verify/tests.rs +++ b/engine/crates/ps5upload-fpkg/src/verify/tests.rs @@ -24,7 +24,7 @@ fn a_flat_path_table_is_read_no_further_than_it_goes() { /// as failing its checks. It used to index past the list and take the job down. #[test] fn an_image_without_its_first_inodes_is_reported_not_indexed() { - let dir = std::env::temp_dir().join(format!("fpkg-verify-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("fpkg-verify-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); let source = dir.join("game"); let put = |path: &str, data: &[u8]| { @@ -171,7 +171,7 @@ fn damage_names_the_worst_thing_the_checks_found() { /// cut short, and with only its trailing install manifest gone. #[test] fn a_damaged_package_says_how_it_is_damaged() { - let dir = std::env::temp_dir().join(format!("fpkg-verify-damage-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("fpkg-verify-damage-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); let source = dir.join("game"); let put = |path: &str, data: &[u8]| { @@ -250,3 +250,133 @@ fn a_damaged_package_says_how_it_is_damaged() { assert_eq!(r.damage(), Some(Damage::Truncated { have: 0, need: 0 })); std::fs::remove_dir_all(&dir).ok(); } + +/// A scratch folder that goes when the test ends, passed or not. +struct Scratch(std::path::PathBuf); + +impl Scratch { + fn new(tag: &str) -> Self { + let dir = std::env::temp_dir().join(format!("fpkg-verify-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + Scratch(dir) + } +} + +impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +/// A small debug package as Convert builds one: an SI ZIP with its playgo-chunk.crc. +fn built_package(dir: &Path) -> std::path::PathBuf { + let source = dir.join("game"); + std::fs::create_dir_all(source.join("sce_sys")).unwrap(); + std::fs::write(source.join("eboot.bin"), [7u8; 4096]).unwrap(); + std::fs::write(source.join("big.bin"), vec![0x5Au8; 3 << 20]).unwrap(); + std::fs::write( + source.join("sce_sys/param.json"), + br#"{"contentId":"UP0000-PPSA01234_00-TESTGAME00000000","contentVersion":"01.000.000","titleId":"PPSA01234"}"#, + ) + .unwrap(); + let out = dir.join("out"); + std::fs::create_dir_all(&out).unwrap(); + let request = BuildRequest { + time: Some((1_700_000_000, 0)), + ..BuildRequest::new(&source, &out) + }; + build::build(&request, &mut |_| {}).unwrap().path +} + +/// #951: a full check reads the package twice, its blocks and then the PlayGo chunk CRCs. Both +/// passes count in one total, so the progress reaches its total only when both are done, and +/// the second pass reports as it goes and says it is the second. +#[test] +fn progress_counts_the_playgo_crc_pass_and_reaches_its_total_only_at_the_end() { + let t = Scratch::new("phases"); + let path = built_package(&t.0); + let mut file = PkgFile::open(&path).unwrap(); + let zip_start = si::read(&mut file).unwrap().expect("an SI ZIP").zip_start; + drop(file); + + let cancel = std::sync::atomic::AtomicBool::new(false); + // Every report, with the pass it came in. + let events = std::cell::RefCell::new(Vec::<(Option, u64, u64)>::new()); + let current = std::cell::Cell::new(None::); + let report = verify_streaming_phased( + &path, + crate::crypto::DEFAULT_PASSCODE, + &cancel, + &mut |done, total| events.borrow_mut().push((current.get(), done, total)), + &mut |p| current.set(Some(p)), + ) + .unwrap(); + assert!(report.ok(), "{report}"); + let events = events.into_inner(); + let (_, _, total) = *events.last().unwrap(); + assert!(events.iter().all(|e| e.2 == total), "one total throughout"); + assert!( + events.windows(2).all(|w| w[0].1 <= w[1].1), + "never goes back" + ); + assert_eq!(events.last().unwrap().1, total, "done at the end"); + let blocks: Vec<_> = events + .iter() + .filter(|e| e.0 == Some(Phase::Blocks)) + .collect(); + let crc: Vec<_> = events + .iter() + .filter(|e| e.0 == Some(Phase::PlaygoCrc)) + .collect(); + assert!(!blocks.is_empty() && !crc.is_empty()); + // The block pass ends a whole CRC pass short of the total. + assert_eq!(total - blocks.last().unwrap().1, zip_start); + assert!( + blocks.iter().all(|e| e.1 < total), + "never 100% before the CRC pass" + ); + // The CRC pass reports from where the blocks left off, more than once (every 256 blocks + // and at its end), and reaches the total only with its last report. + assert!(crc.len() >= 2, "{crc:?}"); + assert!(crc[..crc.len() - 1].iter().all(|e| e.1 < total)); +} + +/// #951: Cancel is heard during the PlayGo CRC pass, not only during the block sweep. +#[test] +fn cancel_stops_the_playgo_crc_pass() { + let t = Scratch::new("crc-cancel"); + let path = built_package(&t.0); + let cancel = std::sync::atomic::AtomicBool::new(false); + let reached = std::cell::Cell::new(false); + let err = verify_streaming_phased( + &path, + crate::crypto::DEFAULT_PASSCODE, + &cancel, + &mut |_, _| {}, + &mut |p| { + if p == Phase::PlaygoCrc { + reached.set(true); + cancel.store(true, std::sync::atomic::Ordering::Relaxed); + } + }, + ) + .unwrap_err(); + assert!(reached.get()); + assert!(err.to_string().contains("cancelled"), "{err}"); +} + +/// The table read with progress is the plain table, and says how far it got. +#[test] +fn the_crc_table_with_progress_matches_the_plain_one() { + let t = Scratch::new("crc-table"); + let path = t.0.join("blob"); + let bytes: Vec = (0..BLOCK * 600 + 5).map(|i| (i * 13 % 251) as u8).collect(); + std::fs::write(&path, &bytes).unwrap(); + let mut f = PkgFile::open(&path).unwrap(); + let zip_start = BLOCK * 600; + let mut seen = Vec::new(); + let with = si::chunk_crc_table_with(&mut f, zip_start, None, &mut |n| seen.push(n)).unwrap(); + assert_eq!(with, si::chunk_crc_table(&mut f, zip_start).unwrap()); + assert_eq!(seen, [0, 256 * BLOCK, 512 * BLOCK, zip_start]); +} diff --git a/engine/crates/ps5upload-fpkg/src/workshop.rs b/engine/crates/ps5upload-fpkg/src/workshop.rs index d153eef9f..95b22088b 100644 --- a/engine/crates/ps5upload-fpkg/src/workshop.rs +++ b/engine/crates/ps5upload-fpkg/src/workshop.rs @@ -573,7 +573,7 @@ mod tests { #[test] fn a_paused_conversion_makes_no_progress_and_finishes_after_resume() { use crate::ffpfsc; - let dir = std::env::temp_dir().join(format!("workshop-pause-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("workshop-pause-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let source = dir.join("GAME00001.exfat"); let output = dir.join("GAME00001.ffpfsc"); diff --git a/engine/crates/ps5upload-fpkg/tests/ampr_pack.rs b/engine/crates/ps5upload-fpkg/tests/ampr_pack.rs index 7b251df25..455822f08 100644 --- a/engine/crates/ps5upload-fpkg/tests/ampr_pack.rs +++ b/engine/crates/ps5upload-fpkg/tests/ampr_pack.rs @@ -60,7 +60,7 @@ struct Temp(PathBuf); impl Temp { fn new(name: &str) -> Self { - let p = std::env::temp_dir().join(format!("fpkg-ampr-{}-{name}", std::process::id())); + let p = crate::test_tmp::temp_path(format!("fpkg-ampr-{}-{name}", std::process::id())); let _ = std::fs::remove_dir_all(&p); std::fs::create_dir_all(&p).unwrap(); Self(p) @@ -220,3 +220,7 @@ fn a_compress_profile_plans_what_drakmor_plans() { assert_eq!(&reader.read_file(i, &mut tree, "").unwrap(), data, "{rel}"); } } + +// Test scratch paths removed when the test process exits (engine/test-support/test_tmp.rs). +#[path = "../../../test-support/test_tmp.rs"] +mod test_tmp; diff --git a/engine/crates/ps5upload-fpkg/tests/mounts.rs b/engine/crates/ps5upload-fpkg/tests/mounts.rs index 64dfefc1c..074fbb142 100644 --- a/engine/crates/ps5upload-fpkg/tests/mounts.rs +++ b/engine/crates/ps5upload-fpkg/tests/mounts.rs @@ -23,7 +23,7 @@ impl Scratch { fn dir(tag: &str) -> Self { use std::sync::atomic::{AtomicU64, Ordering}; static NEXT: AtomicU64 = AtomicU64::new(0); - let root = std::env::temp_dir().join(format!( + let root = crate::test_tmp::temp_path(format!( "fpkg-mounts-{tag}-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed) @@ -334,7 +334,7 @@ fn outer_file(pkg: &Path, name: &str) -> Vec { #[test] fn a_build_from_an_exfat_mount_verifies_and_round_trips() { let fixture = fixture(); - let out = std::env::temp_dir().join(format!("fpkg-mount-build-{}", std::process::id())); + let out = crate::test_tmp::temp_path(format!("fpkg-mount-build-{}", std::process::id())); let _ = std::fs::remove_dir_all(&out); std::fs::create_dir_all(&out).unwrap(); @@ -758,3 +758,7 @@ fn a_remote_path_goes_to_the_registered_opener() { let tree = source::open(Path::new(&url)).unwrap(); assert_eq!(tree.files().len(), FIXTURE_FILES.len()); } + +// Test scratch paths removed when the test process exits (engine/test-support/test_tmp.rs). +#[path = "../../../test-support/test_tmp.rs"] +mod test_tmp; diff --git a/engine/crates/ps5upload-fpkg/tests/pkg_source.rs b/engine/crates/ps5upload-fpkg/tests/pkg_source.rs index fbe27797e..539d89a8c 100644 --- a/engine/crates/ps5upload-fpkg/tests/pkg_source.rs +++ b/engine/crates/ps5upload-fpkg/tests/pkg_source.rs @@ -19,7 +19,7 @@ struct TempDir(PathBuf); impl TempDir { fn new(name: &str) -> Self { let dir = - std::env::temp_dir().join(format!("fpkg-pkgsource-{}-{name}", std::process::id())); + crate::test_tmp::temp_path(format!("fpkg-pkgsource-{}-{name}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); Self(dir) @@ -678,3 +678,7 @@ fn a_package_browses_read_only() { ); assert_eq!(sub.empty_dirs(), ["hollow"]); } + +// Test scratch paths removed when the test process exits (engine/test-support/test_tmp.rs). +#[path = "../../../test-support/test_tmp.rs"] +mod test_tmp; diff --git a/engine/crates/ps5upload-fpkg/tests/samples.rs b/engine/crates/ps5upload-fpkg/tests/samples.rs index 8927737ed..21cff2425 100644 --- a/engine/crates/ps5upload-fpkg/tests/samples.rs +++ b/engine/crates/ps5upload-fpkg/tests/samples.rs @@ -91,7 +91,7 @@ fn a_single_flipped_byte_fails_verification() { }; // Inside outer block 3 (the inode table): its imagedigs check must fail. bytes[0x10000 + 3 * 0x10000 + 100] ^= 0x01; - let tmp = std::env::temp_dir().join(format!("fpkg-tamper-{}.pkg", std::process::id())); + let tmp = crate::test_tmp::temp_path(format!("fpkg-tamper-{}.pkg", std::process::id())); std::fs::write(&tmp, &bytes).unwrap(); let report = verify_package(&tmp, DEFAULT_PASSCODE).unwrap(); std::fs::remove_file(&tmp).ok(); @@ -101,3 +101,7 @@ fn a_single_flipped_byte_fails_verification() { .iter() .any(|c| !c.ok && c.name.starts_with("outer block 3"))); } + +// Test scratch paths removed when the test process exits (engine/test-support/test_tmp.rs). +#[path = "../../../test-support/test_tmp.rs"] +mod test_tmp; diff --git a/engine/crates/ps5upload-fpkg/tests/scale.rs b/engine/crates/ps5upload-fpkg/tests/scale.rs index f6812d930..5348c3fd2 100644 --- a/engine/crates/ps5upload-fpkg/tests/scale.rs +++ b/engine/crates/ps5upload-fpkg/tests/scale.rs @@ -13,7 +13,7 @@ struct TempDir(PathBuf); impl TempDir { fn new(name: &str) -> Self { - let dir = std::env::temp_dir().join(format!("fpkg-scale-{}-{name}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("fpkg-scale-{}-{name}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); Self(dir) @@ -129,13 +129,26 @@ fn the_streaming_writer_reports_progress() { .unwrap(); assert!(report.verify.ok()); assert!(!samples.is_empty()); - // One total throughout (the outer image), never exceeded, and the run ends complete. - // Each phase sweeps it — writing, then verifying — so the sequence steps back - // between phases, which is what the engine's per-phase progress expects. + // One total per phase, never exceeded, and the run ends complete. Writing sweeps the outer + // image; the read-back sweeps it again and, checking in full, reads everything before the + // SI ZIP once more for the PlayGo chunk CRCs (#951), which its total counts too. The + // sequence steps back between phases, which is what the engine's per-phase progress + // expects. let total = samples[0].1; - assert!(samples.iter().all(|(_, t)| *t == total), "{samples:?}"); + let check_total = samples.last().unwrap().1; + assert!(check_total > total, "{total} {check_total}"); + assert!( + samples + .iter() + .all(|(_, t)| *t == total || *t == check_total), + "{samples:?}" + ); assert!(samples.iter().all(|(done, t)| done <= t), "{samples:?}"); - assert_eq!(*samples.last().unwrap(), (total, total), "{samples:?}"); + assert_eq!( + *samples.last().unwrap(), + (check_total, check_total), + "{samples:?}" + ); } /// An image past the first indirect slot's 1820 blocks (12 + 1820 blocks = 114 MiB) makes @@ -731,3 +744,7 @@ fn a_sampled_sweep_reads_back_a_sample_and_a_full_sweep_all_of_it() { } assert!(sweep(&report.path, Some(seed)) && sweep(&report.path, None)); } + +// Test scratch paths removed when the test process exits (engine/test-support/test_tmp.rs). +#[path = "../../../test-support/test_tmp.rs"] +mod test_tmp; diff --git a/engine/crates/ps5upload-fpkg/tests/writer.rs b/engine/crates/ps5upload-fpkg/tests/writer.rs index 2293c5a65..4a43ae72d 100644 --- a/engine/crates/ps5upload-fpkg/tests/writer.rs +++ b/engine/crates/ps5upload-fpkg/tests/writer.rs @@ -14,7 +14,7 @@ struct TempDir(PathBuf); impl TempDir { fn new(name: &str) -> Self { - let dir = std::env::temp_dir().join(format!("fpkg-writer-{}-{name}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("fpkg-writer-{}-{name}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); Self(dir) @@ -967,3 +967,7 @@ fn estimates_rank_the_levels_and_cover_the_game() { assert!(e.balanced.bytes < 600 * 1024); assert!(e.fast.seconds <= e.smallest.seconds); } + +// Test scratch paths removed when the test process exits (engine/test-support/test_tmp.rs). +#[path = "../../../test-support/test_tmp.rs"] +mod test_tmp; diff --git a/engine/crates/ps5upload-hub/deploy/refresh-lock.sh b/engine/crates/ps5upload-hub/deploy/refresh-lock.sh index 30c91385c..7e6f4b768 100755 --- a/engine/crates/ps5upload-hub/deploy/refresh-lock.sh +++ b/engine/crates/ps5upload-hub/deploy/refresh-lock.sh @@ -6,6 +6,7 @@ set -eu crate=$(cd "$(dirname "$0")/.." && pwd) engine=$(cd "$crate/../.." && pwd) tmp=$(mktemp -d) +trap 'rm -rf "$tmp"' EXIT mkdir "$tmp/ps5upload-hub" cp "$crate/Cargo.toml" "$tmp/ps5upload-hub/" cp -R "$crate/src" "$crate/tests" "$tmp/ps5upload-hub/" @@ -19,4 +20,4 @@ offline=--offline [ "${HUB_LOCK_ONLINE:-}" = 1 ] && offline= (cd "$tmp" && cargo metadata --format-version 1 $offline >/dev/null) cp "$tmp/Cargo.lock" "$crate/deploy/Cargo.lock" -echo "wrote $crate/deploy/Cargo.lock (scratch copy left in $tmp)" +echo "wrote $crate/deploy/Cargo.lock" diff --git a/engine/crates/ps5upload-lab/src/bench.rs b/engine/crates/ps5upload-lab/src/bench.rs index 8f6599ad0..0c78e739f 100644 --- a/engine/crates/ps5upload-lab/src/bench.rs +++ b/engine/crates/ps5upload-lab/src/bench.rs @@ -2290,7 +2290,7 @@ mod tests { impl TempDir { fn new(name: &str) -> TempDir { let d = - std::env::temp_dir().join(format!("ps5upload-lab-{name}-{}", std::process::id())); + crate::test_tmp::temp_path(format!("ps5upload-lab-{name}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&d); std::fs::create_dir_all(&d).unwrap(); TempDir(d) diff --git a/engine/crates/ps5upload-lab/src/main.rs b/engine/crates/ps5upload-lab/src/main.rs index 0c428bb1f..77c03e69c 100644 --- a/engine/crates/ps5upload-lab/src/main.rs +++ b/engine/crates/ps5upload-lab/src/main.rs @@ -1550,3 +1550,8 @@ mod tests { assert_eq!(super::console_host("ps5.lan:9113"), "ps5.lan"); } } + +// Test scratch paths removed when the test process exits (engine/test-support/test_tmp.rs). +#[cfg(test)] +#[path = "../../../test-support/test_tmp.rs"] +mod test_tmp; diff --git a/engine/crates/ps5upload-pkg/src/lib.rs b/engine/crates/ps5upload-pkg/src/lib.rs index cf1b8e0c1..8bb73642e 100644 --- a/engine/crates/ps5upload-pkg/src/lib.rs +++ b/engine/crates/ps5upload-pkg/src/lib.rs @@ -2546,7 +2546,7 @@ mod tests { let mut d = std::env::temp_dir(); d.push(format!("ps5upload-pkg-test-{}", std::process::id())); let _ = std::fs::create_dir_all(&d); - d + crate::test_tmp::remove_at_exit(d) } /// A 4 KiB-block image whose root directory (inode 2) lists, besides `.` and `..`, the entries @@ -2688,7 +2688,7 @@ mod tests { "UP0000-PPSA01234_00-TESTGAME00000000", &[("TITLE", "Reader")], ); - let path = std::env::temp_dir().join(format!("pkg-reader-{}.pkg", std::process::id())); + let path = crate::test_tmp::temp_path(format!("pkg-reader-{}.pkg", std::process::id())); std::fs::write(&path, &bytes).unwrap(); let by_path = parse_pkg(&path).unwrap(); let mut cur = std::io::Cursor::new(bytes.clone()); @@ -2722,3 +2722,8 @@ mod tests { assert_eq!(known_entry_name(0x040A), None); } } + +// Test scratch paths removed when the test process exits (engine/test-support/test_tmp.rs). +#[cfg(test)] +#[path = "../../../test-support/test_tmp.rs"] +mod test_tmp; diff --git a/engine/crates/ps5upload-tailnet/src/lib.rs b/engine/crates/ps5upload-tailnet/src/lib.rs index 060835247..6df557924 100644 --- a/engine/crates/ps5upload-tailnet/src/lib.rs +++ b/engine/crates/ps5upload-tailnet/src/lib.rs @@ -539,7 +539,7 @@ mod tests { #[test] fn starts_retries_and_maps_without_a_control_server() { - let dir = std::env::temp_dir().join(format!("tailnet-rs-test-{}", std::process::id())); + let dir = crate::test_tmp::temp_path(format!("tailnet-rs-test-{}", std::process::id())); let (tx, rx) = mpsc::channel(); let tx = std::sync::Mutex::new(tx); let node = Node::start( @@ -584,3 +584,8 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } } + +// Test scratch paths removed when the test process exits (engine/test-support/test_tmp.rs). +#[cfg(test)] +#[path = "../../../test-support/test_tmp.rs"] +mod test_tmp; diff --git a/engine/crates/ps5upload-tests/tests/archive_extract.rs b/engine/crates/ps5upload-tests/tests/archive_extract.rs index 462c155fd..e8ec8f123 100644 --- a/engine/crates/ps5upload-tests/tests/archive_extract.rs +++ b/engine/crates/ps5upload-tests/tests/archive_extract.rs @@ -10,7 +10,7 @@ use ps5upload_core::archive_extract::{ fn scratch(name: &str) -> PathBuf { static SEQ: AtomicU64 = AtomicU64::new(0); - let d = std::env::temp_dir().join(format!( + let d = crate::test_tmp::temp_path(format!( "ps5upload-extract-{}-{}-{name}", std::process::id(), SEQ.fetch_add(1, Ordering::Relaxed) @@ -171,3 +171,7 @@ fn a_password_rar_needs_its_password() { b"target\nCargo.lock\n" ); } + +// Test scratch paths removed when the test process exits (engine/test-support/test_tmp.rs). +#[path = "../../../test-support/test_tmp.rs"] +mod test_tmp; diff --git a/engine/crates/ps5upload-tests/tests/ava1_7z_integration.rs b/engine/crates/ps5upload-tests/tests/ava1_7z_integration.rs index aa7b463d1..d7ca7e607 100644 --- a/engine/crates/ps5upload-tests/tests/ava1_7z_integration.rs +++ b/engine/crates/ps5upload-tests/tests/ava1_7z_integration.rs @@ -23,7 +23,7 @@ impl Drop for Tmp7z { fn tmp_path(tag: &str) -> PathBuf { use std::sync::atomic::{AtomicU64, Ordering}; static SEQ: AtomicU64 = AtomicU64::new(0); - std::env::temp_dir().join(format!( + crate::test_tmp::temp_path(format!( "ps5u_ava1_7z_{tag}_{}_{}.7z", std::process::id(), SEQ.fetch_add(1, Ordering::Relaxed) @@ -319,3 +319,6 @@ async fn upload_7z_refuses_a_block_with_directories_between_its_files() { } let _ = std::fs::remove_file(&p); } + +// Test scratch paths removed when the test process exits (engine/test-support/test_tmp.rs). +use ava1_common::test_tmp; diff --git a/engine/crates/ps5upload-tests/tests/ava1_common/mod.rs b/engine/crates/ps5upload-tests/tests/ava1_common/mod.rs index 229ef38ab..8aba3d696 100644 --- a/engine/crates/ps5upload-tests/tests/ava1_common/mod.rs +++ b/engine/crates/ps5upload-tests/tests/ava1_common/mod.rs @@ -41,7 +41,7 @@ impl Drop for TempDir { pub fn tempdir() -> TempDir { static SEQ: AtomicU64 = AtomicU64::new(0); let n = SEQ.fetch_add(1, Ordering::Relaxed); - let p = std::env::temp_dir().join(format!("ps5u-ava1t-{}-{n}", std::process::id())); + let p = test_tmp::temp_path(format!("ps5u-ava1t-{}-{n}", std::process::id())); let _ = std::fs::remove_dir_all(&p); std::fs::create_dir_all(&p).unwrap(); TempDir(p) @@ -481,3 +481,7 @@ pub async fn abs_console(slow: bool) -> AbsConsole { proxy, } } + +// Test scratch paths removed when the test process exits (engine/test-support/test_tmp.rs). +#[path = "../../../../test-support/test_tmp.rs"] +pub mod test_tmp; diff --git a/engine/crates/ps5upload-tests/tests/ava1_zip_integration.rs b/engine/crates/ps5upload-tests/tests/ava1_zip_integration.rs index 800826da3..471a8199c 100644 --- a/engine/crates/ps5upload-tests/tests/ava1_zip_integration.rs +++ b/engine/crates/ps5upload-tests/tests/ava1_zip_integration.rs @@ -28,7 +28,7 @@ fn build_zip(entries: &[(&str, &[u8])], deflate: bool) -> TmpZip { use zip::CompressionMethod; static SEQ: AtomicU64 = AtomicU64::new(0); - let path = std::env::temp_dir().join(format!( + let path = crate::test_tmp::temp_path(format!( "ps5u_ava1_ziptest_{}_{}.zip", std::process::id(), SEQ.fetch_add(1, Ordering::Relaxed) @@ -313,7 +313,7 @@ fn zip_plan_preview_sorted_total_and_excludes() { fn inspect_zip_on_garbage_errors() { use std::sync::atomic::{AtomicU64, Ordering}; static SEQ: AtomicU64 = AtomicU64::new(0); - let p = std::env::temp_dir().join(format!( + let p = crate::test_tmp::temp_path(format!( "ps5u_ava1_notazip_{}_{}.zip", std::process::id(), SEQ.fetch_add(1, Ordering::Relaxed) @@ -323,3 +323,6 @@ fn inspect_zip_on_garbage_errors() { let _ = std::fs::remove_file(&p); assert!(r.is_err(), "garbage input must fail to inspect"); } + +// Test scratch paths removed when the test process exits (engine/test-support/test_tmp.rs). +use ava1_common::test_tmp; diff --git a/engine/test-support/test_tmp.rs b/engine/test-support/test_tmp.rs new file mode 100644 index 000000000..e89a54100 --- /dev/null +++ b/engine/test-support/test_tmp.rs @@ -0,0 +1,81 @@ +//! Test scratch files and folders that never outlive the test process. +//! +//! Tests here make their scratch space under the system temp folder with a readable name +//! (`--`), which helps when a run fails. Removing it at the end of the test body +//! misses every failing or panicking test, and many tests never removed it at all: one cleanup +//! found 32,911 leftovers (38 GB) in a developer's temp folder. Wrap the path in +//! [`remove_at_exit`] where it is made instead: the file or folder is deleted when the test +//! process exits, pass, fail or panic (nextest runs each test in a process of its own, so that is +//! right after the test). Statics that hold a per-process folder (a test-only data directory) are +//! covered the same way, which a `Drop` guard cannot do. +//! +//! `PS5UPLOAD_KEEP_TEST_TMP=1` keeps everything and prints what was kept, to inspect a failed run. +//! +//! One source file for every crate: each includes it with +//! `#[path = ".../engine/test-support/test_tmp.rs"] mod test_tmp;` in test code only, so no crate +//! gains a dependency. `scripts/check-test-tmp-leaks.sh` (and CI) fail when a run leaves anything. +#![allow(dead_code)] + +use std::path::{Path, PathBuf}; +use std::sync::{Mutex, Once}; + +static PATHS: Mutex> = Mutex::new(Vec::new()); +static HOOK: Once = Once::new(); + +unsafe extern "C" { + // The C runtime's exit hook (every platform Rust tests run on has it). Rust's + // `std::process::exit`, which the test harness calls, and a normal return from `main` both run + // it; a test that panics is caught by the harness first, so it runs then too. + fn atexit(cb: extern "C" fn()) -> std::os::raw::c_int; +} + +extern "C" fn remove_registered() { + let paths = std::mem::take(&mut *PATHS.lock().unwrap_or_else(|e| e.into_inner())); + let keep = keep_requested(); + for p in paths { + let Ok(meta) = std::fs::symlink_metadata(&p) else { + continue; + }; + if keep { + eprintln!("PS5UPLOAD_KEEP_TEST_TMP: kept {}", p.display()); + } else if meta.is_dir() { + let _ = std::fs::remove_dir_all(&p); + } else { + let _ = std::fs::remove_file(&p); + } + } +} + +fn keep_requested() -> bool { + std::env::var_os("PS5UPLOAD_KEEP_TEST_TMP").is_some_and(|v| !v.is_empty() && v != "0") +} + +/// Removes `path` (a file or a folder with everything in it) when this test process exits, and +/// returns it unchanged. Registering a path that never gets made, or one already removed, is fine. +pub fn remove_at_exit(path: impl Into) -> PathBuf { + let path = path.into(); + // Never the temp folder itself or anything above it. + assert!( + path.is_absolute() && !std::env::temp_dir().starts_with(&path), + "test_tmp: refusing to remove {}", + path.display() + ); + HOOK.call_once(|| { + // SAFETY: `remove_registered` is a plain `extern "C" fn()` that lives for the whole + // program; registering it once is all `atexit` needs. + unsafe { + atexit(remove_registered); + } + }); + PATHS + .lock() + .unwrap_or_else(|e| e.into_inner()) + .push(path.clone()); + path +} + +/// `/`, removed when the test process exits (see [`remove_at_exit`]). Nothing is +/// created; the caller makes the file or folder as before. +pub fn temp_path(name: impl AsRef) -> PathBuf { + remove_at_exit(std::env::temp_dir().join(name)) +} diff --git a/payload/include/config.h b/payload/include/config.h index cb5a6f71d..992a2adb4 100644 --- a/payload/include/config.h +++ b/payload/include/config.h @@ -5,7 +5,7 @@ * UI tell apart an old payload still running from a build that includes * a particular fix, without having to boot the console. Keep in sync * with the desktop app's package.json during releases. */ -#define PS5UPLOAD2_VERSION "12.6.32" +#define PS5UPLOAD2_VERSION "12.6.33" /* Author credit — embedded in the startup toast so anyone looking at * the console screen knows who wrote the software that just loaded. * Kept separate from VERSION so release scripts can bump the version diff --git a/payload/smb/smbd_copy.c b/payload/smb/smbd_copy.c index 0e787f979..0e7783631 100644 --- a/payload/smb/smbd_copy.c +++ b/payload/smb/smbd_copy.c @@ -86,8 +86,10 @@ static int count_tree(ctx_t *c, const char *path, int depth) { } rc = c->src->ops->readdir(c->src, d, name, sizeof name, &st); if (rc <= 0) break; - if (st.kind == XK_OTHER) continue; - if (c->o->skip_mac_metadata && smbp_skip_download(name)) continue; + if (st.kind == XK_OTHER || (c->o->skip_mac_metadata && smbp_skip_download(name))) { + c->pr->skipped++; /* counted once, here: the copy pass skips the same entries */ + continue; + } if (smbp_join(path, name, child, sizeof child) != 0) { rc = XE_BAD_NAME; note_failed(c, name); diff --git a/payload/smb/smbd_copy.h b/payload/smb/smbd_copy.h index da772ad29..747bda23f 100644 --- a/payload/smb/smbd_copy.h +++ b/payload/smb/smbd_copy.h @@ -81,6 +81,9 @@ typedef struct { volatile int scanning; /* 1 while the source tree is being counted */ volatile int cancel; /* set by anyone: the copy stops at the next chunk */ volatile uint32_t reconnects; /* how often a dropped connection was recovered */ + /* Entries of the source tree the copy leaves out (links and other special entries, macOS + * metadata on a download): a move must not delete a source that held any (#953). */ + volatile uint32_t skipped; char current[256]; /* the file being copied (its name), best-effort */ } copy_progress_t; diff --git a/payload/smb/smbd_jobs.c b/payload/smb/smbd_jobs.c index c846a655f..2f0ae555f 100644 --- a/payload/smb/smbd_jobs.c +++ b/payload/smb/smbd_jobs.c @@ -189,6 +189,7 @@ static void status_locked(const job_t *j, sj_buf_t *b) { sj_fmt(b, ",\"bytes_done\":%llu,\"bytes_total\":%llu,\"files_done\":%u,\"files_total\":%u,\"scanning\":%s", (unsigned long long)j->pr.bytes_done, (unsigned long long)j->pr.bytes_total, (unsigned)j->pr.files_done, (unsigned)j->pr.files_total, j->pr.scanning ? "true" : "false"); + sj_fmt(b, ",\"skipped\":%u", (unsigned)j->pr.skipped); sj_fmt(b, ",\"reconnects\":%u,\"dialect\":%u,\"started\":%lld,\"ended\":%lld", (unsigned)j->pr.reconnects, j->dialect, (long long)j->started, (long long)(j->state == ST_RUNNING ? 0 : j->ended)); sj_kv_str(b, 1, "current", cur); diff --git a/payload/tests/smbd_copy_selftest.c b/payload/tests/smbd_copy_selftest.c index 27e81083c..a67457fdd 100644 --- a/payload/tests/smbd_copy_selftest.c +++ b/payload/tests/smbd_copy_selftest.c @@ -466,6 +466,7 @@ static void t_download_tree(void) { rc = copy_run(&src, "Games", &dst, d, &o, &pr, failed, sizeof failed); CHECK(rc == 0); CHECK(pr.files_total == 3 && pr.files_done == 3); + CHECK(pr.skipped == 3); /* the link, ._top.txt and .DS_Store: counted once, not per pass */ CHECK(pr.bytes_total == sizeof k_big - 1 + 3 && pr.bytes_done == pr.bytes_total); lp(f, "游戏/中文 文件夹/存档.bin"); CHECK(read_file(f, buf, sizeof buf) > 0 && strcmp(buf, k_big) == 0); @@ -612,6 +613,8 @@ static void t_upload(void) { rc = copy_run(&src, s, &dst, "Backup/up", &o, &pr, failed, sizeof failed); CHECK(rc == 0); CHECK(pr.reconnects >= 1); + CHECK(pr.skipped == 1); /* the link: a move must keep this source (#953) */ + CHECK(pr.files_total == 2); x = find(&m, "Backup/up/sub/naïve.txt"); CHECK(x && x->size == sizeof k_big - 1 && memcmp(x->data, k_big, x->size) == 0); x = find(&m, "Backup/up/a.txt"); diff --git a/scripts/check-test-tmp-leaks.sh b/scripts/check-test-tmp-leaks.sh new file mode 100755 index 000000000..76cfc74f8 --- /dev/null +++ b/scripts/check-test-tmp-leaks.sh @@ -0,0 +1,99 @@ +#!/usr/bin/env bash +# Runs tests with the temp folder (TMPDIR, TEMP, TMP) pointed at a new empty folder and fails if +# they leave anything in it. Tests that made scratch folders and never removed them once filled a +# developer's temp folder with 32,911 leftovers (38 GB), and earlier ~2 TB. +# +# scripts/check-test-tmp-leaks.sh engine crates that make the most scratch files +# scripts/check-test-tmp-leaks.sh --all the whole engine workspace, the scripts' node +# tests and the client's vitest suite +# scripts/check-test-tmp-leaks.sh -- CMD ARGS... any command +# scripts/check-test-tmp-leaks.sh --check DIR only list what is left in DIR (CI runs its tests +# with TMPDIR set and then this) +# +# A test's scratch space: Rust tests wrap the path in `test_tmp::temp_path`/`remove_at_exit` +# (engine/test-support/test_tmp.rs); node and vitest tests remove theirs in `after`/`afterAll`; +# shell scripts use an EXIT trap. PS5UPLOAD_KEEP_TEST_TMP=1 keeps them to inspect a failed run +# (this check then fails, as it should). +set -uo pipefail + +cd "$(dirname "$0")/.." || exit 2 + +# Left on purpose and reused, not per run: Node's compile cache (vite enables it). +ALLOWED=(node-compile-cache) + +check_dir() { + local dir="$1" args=() left n + for a in "${ALLOWED[@]}"; do args+=(! -name "$a"); done + left="$(find "$dir" -mindepth 1 -maxdepth 1 "${args[@]}" | sort)" + if [[ -z "$left" ]]; then + echo "check-test-tmp-leaks: nothing left in the temp folder" + return 0 + fi + n="$(printf '%s\n' "$left" | wc -l | tr -d ' ')" + echo "::error::tests left $n file(s) or folder(s) in the temp folder ($dir):" + printf '%s\n' "$left" | head -n 200 | while IFS= read -r p; do + printf ' %s %s\n' "$(du -sh "$p" 2>/dev/null | cut -f1)" "${p#"$dir"/}" + done + ((n > 200)) && echo " ... and $((n - 200)) more" + echo "Make each test remove what it creates, pass or fail (see the top of this script)." + return 1 +} + +if [[ "${1:-}" == "--check" ]]; then + [[ -d "${2:-}" ]] || { echo "usage: $0 --check DIR" >&2; exit 2; } + check_dir "$2" + exit +fi + +mode=engine +cmd=() +case "${1:-}" in + "") ;; + --all) mode=all ;; + --) shift; mode=cmd; cmd=("$@") ;; + *) echo "usage: $0 [--all | -- CMD ARGS... | --check DIR]" >&2; exit 2 ;; +esac + +tmp="$(mktemp -d "${TMPDIR:-/tmp}/ps5upload-tmp-leaks.XXXXXX")" +trap 'rm -rf "$tmp"' EXIT +scratch="$tmp/tmp" +mkdir "$scratch" + +# Runs a command with the temp folder redirected; a failing test fails the check too. +in_scratch() { + TMPDIR="$scratch/" TEMP="$scratch" TMP="$scratch" "$@" +} + +nextest() { + if cargo nextest --version >/dev/null 2>&1; then + # Build first, outside the scratch folder: only what the tests leave counts. + (cd engine && cargo build -q -p ps5upload-unrar && cargo nextest run --no-run "$@") || return 1 + (cd engine && in_scratch cargo nextest run --no-fail-fast "$@") + else + (cd engine && cargo build -q -p ps5upload-unrar && cargo test --no-run "$@") || return 1 + (cd engine && in_scratch cargo test --no-fail-fast "$@") + fi +} + +status=0 +case "$mode" in + engine) + nextest -p ps5upload-core -p ps5upload-ava1 -p ps5upload-fpkg -p ps5upload-convert-core || status=1 + ;; + all) + nextest --workspace || status=1 + in_scratch bash -c 'node --test scripts/*.test.mjs scripts/release/*.test.mjs' || status=1 + if [[ -d client/node_modules ]]; then + (cd client && in_scratch npx vitest run) || status=1 + else + echo "check-test-tmp-leaks: client/node_modules missing (npm ci in client/): vitest skipped" + fi + ;; + cmd) + in_scratch "${cmd[@]}" || status=1 + ;; +esac + +((status)) && echo "check-test-tmp-leaks: some tests failed (above)" +check_dir "$scratch" || status=1 +exit "$status" diff --git a/scripts/ci-apt.test.mjs b/scripts/ci-apt.test.mjs index 7b0537964..717d383cc 100644 --- a/scripts/ci-apt.test.mjs +++ b/scripts/ci-apt.test.mjs @@ -5,15 +5,24 @@ import { execFileSync, spawnSync } from "node:child_process"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; -import test from "node:test"; +import test, { after } from "node:test"; const here = import.meta.dirname; const ciApt = path.join(here, "ci-apt.sh"); const latest = path.join(here, "ci-apt-latest.sh"); +// Every sandbox is removed when the file's tests end, pass or fail (PS5UPLOAD_KEEP_TEST_TMP=1 keeps +// them to look at). +const sandboxes = []; function sandbox() { - return fs.mkdtempSync(path.join(os.tmpdir(), "ci-apt-test-")); + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ci-apt-test-")); + sandboxes.push(dir); + return dir; } +after(() => { + if (process.env.PS5UPLOAD_KEEP_TEST_TMP) return; + for (const dir of sandboxes) fs.rmSync(dir, { recursive: true, force: true }); +}); /** Runs `ci-apt.sh --rotate ` over files in a temp dir; returns {stderr, read(name)}. */ function rotate(tryNo, { arch, mirrors, sources = {}, keep = [] }, dir = sandbox()) { diff --git a/scripts/i18n-source-hashes.json b/scripts/i18n-source-hashes.json index 918c060e4..a149dc7d9 100644 --- a/scripts/i18n-source-hashes.json +++ b/scripts/i18n-source-hashes.json @@ -1446,7 +1446,9 @@ "copycheck.ok": "287c14a8 ZUmaaHk9OmAF60OTdyQ_jcqOLePTdBB0PQXDjfxq_ym8qllXgx7vIEvboexp", "copycheck.queued": "53bc7b0f _mbVeFtO8_6m6ByvTJD4E4iW5it2jjkF28_MBwGznuSAB6by_XVZxLjzGA68", "copycheck.running": "ec963ffc jIQxOxXbW0qcJThx5hf577o41g5xsTSecU-8hx5wvbY4-c_iJ88Byaa3LFa0", + "copycheck.running_blocks_pct": "5752ef7e PJUTwZlfkwaLFrEqmJF-uLMnA2v4rQZlBLuQSNP5HlH64p3b7UcM0jhoovB3", "copycheck.running_pct": "f9ed6448 EWmdZpZO6IcnjxlZZb7Q8f_G4R3sfMXQS_cVOFywOuW7nmkOeYdP5FCp5_m3", + "copycheck.running_playgo_pct": "62a8fd56 w5V0YUWSFzSNvEpY2OXRQo-bWPUoDOc836Qa6w_3UcuOnd0kjcnJUNBlW6Dz", "copycheck.v_data": "9f1cf553 HFVIZlA7mDQpoBT21VJ_0LKoQ-XkPGLK9PI7GXBqpQuWF08-BEGrSrDvw5ED", "copycheck.v_metadata": "10bb9c45 vsO1lV8jqBD2qSKN7U-xMv3Z7ihksYALaJTYfQDHqgcRUaL5_C8H49ApY_W5", "copycheck.v_other": "49fdc39c 2cMRvzlwckTxVmHcRxhCMsr32EVJdASx8gIMFv7kTx4f0QQL8P0-UORBG_Jg", @@ -1481,6 +1483,7 @@ "cq_packs_profile": "98994c4f YEInuEHJdVuyy3FiEwLVkBbQyNCiKwqB8nQCuwUodmJCPcCQKMcaYsFWhvp6", "cq_packs_zstd": "242daddb JC2JC2JC2JC2JC2JC2JC2JC2JC2JC2JC2JC2JC2JC2JC2JC2JC2JC2JC2JC2", "cq_packs_zstd_note": "6b2795b9 D1aEC3cfa6Hm329GPgm8Oj3-shsunZes7zep1DVnSbeuTV_Y7zLmX52E1xcM", + "cq_page_close_note": "fbf4c7b4 mqIliZax-rVNnspMw-zwlIGWn3yiJ-M9ibmTpxYhPrP0yGbUZ3YcDUVDdDCO", "cq_password_retry": "d8b8392e ZP3iuElIZ_yjOVXrycwcwS5k6HxILXu5lGWhcjea7MUYkQgMHzDxY0uHhfln", "cq_pending": "6e293a8c YoUK0Az_cooVyqwL2y5ogrjYE_lbzULz7ago2Zl6sgicnxp0kCWQlfJsjJsj", "cq_running": "2fac88a2 kEKyuHrEPkc4aaoL_UIuQ57xQU3ZIkke35PKfdujXMyPLWQ3ifCpwEiLvy2d", @@ -1489,6 +1492,7 @@ "cq_skipped_not_image": "db58ecb3 iPFjvGEDuFEdICGgC2HBuQuSnJpEKbsVj6_zsEmt3INw5lPwnrvQ4nse0bNA", "cq_start": "406be720 G0ADXKlyFBAyAicsGx-MJPylf_YIDB6vSkHmXd3EHp7zDCAiq_5TIVVwIXJ4", "cq_stop": "25aceb0a BLEvv_NmF_SzQ7HPX1At-XoQ2TDatMXPi0yJMEZD-QTRSdhkFg7mZOTZg7Qe", + "cq_stopped_by_close": "799c1976 nFeAs51faH29ILQQYUlPCGv43miM9O-f7ZhveaougA5S1X1EjxEcUDDWm-XN", "cq_tag_free_archive": "e558a126 txR8gXOv1VmkqMB-k7y2TiUFaaSXZbczXPo4y8pooi55h7Qh2OkxVs7E4Rwm", "cq_tag_level_balanced": "c0905088 cH6E9N-pLO-WCycfG3ozZE1OAXBk9uts-Y0JDoSO-WzZA4WifEt7pBJYi31R", "cq_tag_level_fast": "115dc360 k4Y4C4qLHj9Sx-sjL-w1P17T7r63SYOZGMqgtawj9S3Nh9MhZNFniu25R25R", @@ -2162,6 +2166,8 @@ "cw_files_load_all": "5ff55078 SvLGFxQosNFUgsDRKcSciBZuRAFOiDnKsVW__V43-8ZqDX2ZDmhZAoSXdjXN", "cw_files_mesh_home": "491e24d5 f0YJl8qhGdZkYYE2P1ZGg8EXAUirQUfBznqNIlOt21-njDxWkONQyof7RiO4", "cw_files_more": "f5c9bd13 28wuJ-5m8XBhEum5l5sxdP78bQOXLZfaCXoli-rcBhxoJUgUsrX8T9MxrH6f", + "cw_files_move_has_links": "5e44cd27 szIZb_aHZ7aEmVjC12TAnVvXs_70fn6Hq50kl9D2YfSR3E2ebQ_Iltp5cSlC", + "cw_files_move_source_left": "f378f88b cbkRtbipiiNROyxZc2KsD1ckbd2lGW66YeiryBf3w29BNMkV_MQrCvIklpJN", "cw_files_move_to": "5af2f53c ftP1GV9wy0d7CqZlyesy7NdC58sNvIe7IDIhM3_kv8RcbYR_XecCR0C-4lz6", "cw_files_name": "dcd1d522 Uqs-wn3NHViuacHssEZTsRnt9paUIafsJJT0NLhUIaHafm0SHZfyLF1E6pSd", "cw_files_new_file": "44dedd0f 9QWuvBKlCLS2cTSHBtxEnjddrH_AMaAr2RamA1QhW62XHrV8uoSosPbd005T", @@ -3858,6 +3864,10 @@ "fs_move_no_subfolders": "7cc0cb43 j85CPo-f3M4c9MKBPvKTW-P2lEN-LoSP4MzUSsPkYS7SQlWlgTbjZqJIQ60Z", "fs_move_recent": "690dbe9d hItewRaluKnMxr3dBtYvZAv0sO5H5XmXpgSTsXpMGj9O3Wr4I6n-cwmXpmXp", "fs_move_same_drive": "6422acd1 mtfwj6Ufq8fMDU8lK3pResDe1y5FR3L3pgNEAXEDxJIiwvcvGRcScSZJKQpC", + "fs_move_server_copy": "ab02e440 RjyfhOZkyhdvVjWoziNLSXvRj1JoOaV-9g8sH9gpcW7A5obo3jGkVD7uRTns", + "fs_move_server_hint": "ad7cc560 eXYdfMszKIirasMnVDiid_xK6cLkMgrgDjFsmA1ZhjnkZOYoRy89ivuSTo0W", + "fs_move_server_move": "7b3b8e66 8coTnsvAJp-fncajdWs-zyfGcwZcnUXOFHBoKPIlVQZgw9dFjtSRkqvlr2jE", + "fs_move_servers": "4bf08480 MraaEKfglmtLJWvb8pcPcj0Ehd1yUCsDD0UoOW76bwfZr8hBCfEQUSlvH5cz", "fs_move_tight": "b3c16961 usUZNxTuAqRa81XjgDsVBwp6xTcsR1ZR1A_OWoI7dsoXGSAEa4TnRQXYZBMu", "fs_move_title": "2bc196d1 PZhAjKwPM37O_a8JvFPuQeQr0X_Lb9PBLnFAJmJ6Ledt4nAvDrTn3QBkF5EF", "fs_move_to": "5af2f53c ftPCt29wy0d7CqZlyesy7NdC58sNvIe7I1rZM3_kv8RcbYR_Xecv3tC-4lz6", @@ -5805,8 +5815,6 @@ "payload_role_webkit_autoloader": "6ce687e9 85-65AisOj4oxLrH3mUl2vxY5O3nEIzEua15up_DbEbzRmyK9No_B1sIe4DL", "payload_role_websrv": "17c3a021 yIrhJ_xvp6pF_uehfJ3vJ2J0wJEb7Wd3PJR5tUE_Pv-uYjRYL8gydrUwAE9A", "payloads": "00a5ba36 S3pJnmAKWAKWCtCAKWMmZzGAmXMmXMel0EhHVYfAKW0sY3mJTZ-mXMrMRMTA", - "payloads_custom_badge": "494ca78f F8K-JEuZJQpCupIK2t9Tn3NOXb8eSVUX94fUeL8QpCPhGkIPe9i3EaTq-H-m", - "payloads_custom_remove": "78c97fbe oFnp_AtC5aVBpX02hoXhf8bUKzoRkHBRH4hSDuI7bJmS0EfyRVvMFW6xsUb6", "payloads_custom_remove_short": "c3812fc4 MFTgo8OCg8DnWcpQeIbTaV-oEHJ_Wn6WUq2Yri1owNB8tWjUuIA4H0YTXYTX", "payloads_custom_removed": "ad617385 vQ7H36w3LCcvXxCgMhcTa2brqGUPrBWZSIQcl0UgP0-7D68r0xXFfY4Gs4Gs", "payloads_description_catalog_guide": "0e5f8557 gc7ZQzTn_J5d2fICA85B6bUZBYpQq694JuCTOJBd-BcMHDGL55F34sqfz31s", @@ -6584,6 +6592,59 @@ "ps5notif_clearing": "9a81378b uTug_TufgAnSn-ubf7juclwU_G5zN8K2q51UF1VfKTgQHkOFeeyUU0BXGBXG", "ps5notif_empty": "4f3356c6 KihxJQ1MJPqbcFbBvLrltvYiAyKfBulXDG2TYuigAhTGh-j7-C8Y1QVUGmTk", "ps5notif_empty_hint_v2": "0b6eb3dd lqkBeBrVERgLFxIfy9zAX-uAUzSuxqLztDQN2T73XNqBKL3Z7YYcCAW0whnK", + "psrc_add": "6dc390ba bG37dr0Kq1-E9jYJaJhZMaxvkrtifEQbWGkoMM-CZEUFEonETcvDr9HJ0UG_", + "psrc_add_confirm": "6ea6c9ec qVz_KL5EWaygHUiEuCRvZ189QSxDcD2O7RTcQbt5O9mkGweta-1LXdG5PJdO", + "psrc_add_title": "6dc390ba bG37dr0Kq1-E9jYJaJhZMaxvkrtifEQbWGkoMM-CZEUFEonETcvDr9HJ0UG_", + "psrc_change_file": "1a675bfd KIOYUH5x--uxnGczQz-_3YUgCnaaECxuSLinX_yL_1ACTfxf_mX3Hf6qg3WH", + "psrc_change_title": "7fcce080 b8ykU0DfJeNFC8vVtdqdIFcHtBOPTZbH-DVGJcDMUv-tcxTK1ld7g2dt9ZqZ", + "psrc_check": "9d60841e Z0wu-XocoPearoKi32JN7arZ9zmusN3OUGqyzjhZir5EJyFeO-9_24l44vkN", + "psrc_checksum_matched": "cfede40e vdis9q8HEcS_oTXUeVImN_xNVfgTq_yAuojslPlyny-Ps7sjKHFHjilQbGZ9", + "psrc_download": "d6eafe82 aTVS_8swJ7T2m_EzaqSf5v8p5V9cj0uF1CkyfRitFrU1EUtsHNwX82RnO1Hf", + "psrc_err_checksum": "f6e5290f fM1sbXrAdUyl09S6N3e3w6seU0b45L-kLx6DRDu4siGmR0b2Ghh9wvLjNDIp", + "psrc_err_checksum_read": "21520bb7 hV_Uhk7V4llp_ei1N1GbtKDbQ3oZbEEdosxlk9Wh9RMWbIaE9cwKmLWlchrJ", + "psrc_err_credentials": "3efb6f05 5eUVVHbX3LCd1LoOwCrwKfeqqvKXFRQ5Zx30h91rOq_TDtVVW7VuH-01ZVta", + "psrc_err_cut_short": "b532926b amAoddhqlTUSzKe5VVOwI0HgVVBDWQDexSn1ymcGumU1MHd4q0X0HhC1DyiR", + "psrc_err_gitlab": "d13dff34 gSyGKrFSKUQE3p__PDAXt2tNxE74Je6ciLUv4ntiCrmzdo6XeCbxnxdO5oSy", + "psrc_err_host": "e44bf1c1 1mO3saIzSWfrwUwqh4Mylmd5fcSngdPRAcZ3DI2CucuXbsPUL12p3eHAreKq", + "psrc_err_no_file": "996461b2 sm5S06pxmpp700AncYqYj8sCHwzqvx7ZXZus_ejqi6kqFtVHi-oZGfcRbXNG", + "psrc_err_not_found": "67e5b56c 3hT-jRz-uLlAknu6Rcv9Asbu_Jr9_iZ5WtBJWqGVZ8Z6XleEUXXsJnoCkWDg", + "psrc_err_not_https": "58c2d5ec RhtdYsFV_gsm_sRyOOX7fZY29DaZ9G2weTtZD1koeipXpzms4Ku3IuT30Kpg", + "psrc_err_not_payload": "5c771e28 8-9zLdkNW8RKSGPzZJFX0Og-nTrDSabIjiT8or-2X2kTBmkWRXvGBqPjC6U9", + "psrc_err_not_project": "ad141906 JmEoySA-nHHniNBdFD83fqiAiFS2A3urhnQEs8DG31PB3dfvx962re3GH_Nv", + "psrc_err_rate": "418a3df0 gvIVjk86Zw5-whGF6Pu3ZqMiqqkwB73iUdiL11l0a5T-IbdFA_iYcpv7GOrk", + "psrc_err_rate_at": "58bf143f O9DgCZxWwBKn4MW26ILAFI0KgvWG9IUPa2Oscg3LV-xf9WU6g2JGJFd7ut6c", + "psrc_err_redirect": "6c79dfdb RImbaB62lqTipAgQ5wbY6cxv_zAPUqEK4qBSjVNs_-oAe9bTCccPhAh8Il5Q", + "psrc_err_unreachable": "c7eaadcd WkiRR2QAeVXfAi43JT5s3jsEIu1SrAshsDQuYQXsSJerf0rKKlp9OCK_m71S", + "psrc_file": "50009ce1 TseN5f6QKdda0JnB8648_YAzUACUACKznDINWVbuop8kJVCbnOzs-0OZMoRr", + "psrc_have_file": "f0b0738f 4vmD-0VBPpOE2DWTnNsjaveBWCKdGjZJRlrCKO5Y_1K1dJZFbcPtzY4vETID", + "psrc_intro": "4c2360bb OXfXPIx9m4chunOpvKVF7FmKPMvFTBedkKPPy0gi6PW5vP76xAS9nGqQNQRL", + "psrc_look_up": "cccd0d70 9lBJsjK9bjEyhxkGck8R1RbZhz34eUBcbXSBv7AL4CkNNo_BSLwtxSmR3heF", + "psrc_needs_file": "a19fe2fb yoN-8x7b8IhJyX9JQpDvOsIg-ZlS_M-MK9zGfbF34b_jcoC3sp0Ux2VifE_L", + "psrc_new_version": "b9c2741d c2K_bGHChnAyYhYvVb9kj_BP2v30gGnKa2fAQNZjm_i6-7oLuE7j7LGQAGQA", + "psrc_no_files": "6016a433 UZixUHTm5Im8vtZSBW702Q0MFuyFiPAen8qRPtDC6wioSP-TSAOagnoTqfwH", + "psrc_not_downloaded": "5f1f5722 8sN68P3teAyWjr3pl99LLNuG0yyI3kXaoYo1r2f5MXSp3vjO7b3Zd9xf6wY2", + "psrc_not_downloaded_latest": "9056bc31 _ZhF0HkRDx8STpPARLyWFnzyw4XAAtLPU19daYqDOHOGPGib9acBm1kHTpyB", + "psrc_pattern_exact": "ea261ab5 zmQG5kmZW31NEN7AkkDcwwbcxs72iBWNQNhV6JfKQvt9HHCHOkwpiTZiK_-O", + "psrc_pattern_version": "a124adb6 WTkPPwU_aEafKgKMtr1SutE6lftGQTwWF-L3IkYYltsX3BR7K-nQVCO2nz91", + "psrc_pick_file": "ec62d43c TAIEL6eRkIWm7vParo_UuAdPuDLsRcYw8iSKZqhvO_42Yo59aO9fQ0gi-Oxe", + "psrc_pick_legend": "a50debb3 tYsK5iP0p14nwNmV6YtQOuFHdw00r0ZKhQX7tH1QuojZaNlTVvUNVV4SyjdD", + "psrc_release": "e020e3c6 8UF2-v4CD6PXiKo3RZlwEAA5P174CDUu-sO2fo9FRFjvDXLVoBGd_Rth8xKM", + "psrc_release_unknown": "b23a6a84 1E1Z25pBjsCv8HqvdiCHo2Akzst5kRvVq3eVzQg0yMWuq_QUvkH5WBTYwTYw", + "psrc_remove": "f5529618 TetU1NRBtobNZpofiopBPJ4gkuR181Hk9UsJaPpeRM4ino9xAQWL8j63-4N4", + "psrc_remove_body": "5a94d721 Ylq2a4vHZBto4sKnpSeJVPJazdaE2XyzHpXg64Hsc3-zPzkuPnCNPx_gNiSw", + "psrc_remove_title": "01c1f025 7ZD0bLqWsien7jQKEgNz5ixixVZZKxU60Aq7BA4cF4LHKE4UzTNv3ts68s68", + "psrc_send": "d22aca0f zqtQVGWfvY-KMIRO7SoGbIpr5w0YYM226IbOafInMk5yNi_8Ca3hJKPcB3mS", + "psrc_send_body": "4c91ad60 axN2cqc_3ptIWA-WjvVIJtSspAGiKdeFtUqO-GEslDxI0nxqvyjyC_FBVUdH", + "psrc_send_title": "dddad597 zmwZZSEgMOPfZ5BCj6A14JZji50LJdtEYmTuctr6T3ClDLRnPohzqwrFbK40", + "psrc_sent": "ca967fc6 laAbdS38mhN7J7Tje48cGXEVeBi6R4QNJCL4pPchN7lXCMuCdEGEmguDt4JI", + "psrc_sent_body": "3246c1be EUMGQnVK6fDhzJAs2MUH5SYpHQgThB9UHakTJEdo_L2rusld-F003Pkl8uMH", + "psrc_sent_pm": "b578aa96 h5i2CYLzTUh4LWoTeaGlqAE6RDfojj0tUJDZdohkL92cJnv2HeJxVHBFcMUt", + "psrc_size": "1af85190 PvGV_1rtwWbc4nDdwkY36_kNGwPhtFTBTgiMi2vIb7VyCsOomD1hOBUNtUNt", + "psrc_title": "96bc15b7 RY4NR4wzEqZ6rtJ8TWH1o74nSpEmpjsJ3PgIeQxmfpNGlhhjW4oIp1Tg09kw", + "psrc_trust_note": "d823ead8 f2YtAkbXHmwO8O7sYQag40thp7sU_k0G4KGsHq0-Qths1XGcjfhuhw3KzQ7d", + "psrc_update": "c1c1009d AOq5Sxlr8_l9cur9HXpuXbIMDTwOd_MFWnqmh_02vtYD5HE5v2UUpPMFWMFW", + "psrc_url_label": "6611df3d MihG32md2ZI-SoiXDhnMDt96-xquyfTNS1LonqMH63UZAmQTBD-omca5NLox", + "psrc_use_file": "f0ea52d9 4faFTR-JgLgY4rxXhy3mKypy7V9AtyTifZ-n7fmRj8ZSir3_BPdS6dj-_4mc", "pt_allow": "e213c161 NTqjSYaMbS_Tp3dX6BOcFkRmEoyp-aIRPaII7KkS_TJB7PtwaAs8aQzn7C__", "pt_ask_plays_as": "a8aa5d40 kz4oxmS474kHAfpO7WBeg6f7huz86CjyAUSRKjScw6q398O_lhFJXsshrlIy", "pt_ask_seat_stream": "b5cdcb37 vI_VHcDVGo4E9XebSF_z1qeTGyJFUFdfPmi4c14Z3TIjlxcYX1y9OiD0jvVN", @@ -8615,6 +8676,33 @@ "try_again": "29cc3339 Bg_Ev08DPyIhd1VZPxs0Fp8PddoSSgEI69s7LrKyrtTNpDNDDZuDVnXduORE", "tv_join_body": "952e82a4 ZdOkboPOiKxpAxF2_8uRyiNeMTY_ush3RT0RrB0Y8qEFF7fEInY1sguFB8tf", "tv_join_button": "d0ae7bc1 YfChxRANGUobVwRF0aZwzIZyDv42yjLCl5lIVfivlyQPIlj4c3Z4LJuX5uya", + "two_panes_actions": "a7bf8841 dSrq70ZWtYykTw5j9mJsZejhQNCtf4tELWKdKqEqr9gdo1zdWKswTHyXOhxZ", + "two_panes_app_computer": "355b400f d0miU4W_jGObRiC19zfGncscTYkZj2RssFdptzDxJw85jkLtDw-g9DxnXsnr", + "two_panes_choose_place": "69f5ed2f L59g4THJ_jv58N2yyGw-5z78D07VgYMxFMHrziogWRSbMWqiWsWSyGOEG7yX", + "two_panes_consoles": "9821eea1 bZIRZkk_7ACFC5Mci8yBzmhq-PPMi4hMcukV_aFmCUlPUq8Myckw3vsuz_zS", + "two_panes_copy": "e21f935f KaD6TGRyBOdzVXOhLAcyi9KhxWs69FcPeN7PivdOdzHs3X3JqLzaLQY9ku22", + "two_panes_copy_to": "9433c693 P5_XZMD0dAi2EM4jOPiwGrkdKzsvhNivNASqahfy1p4IHlSwn0Jm5z5lXRb4", + "two_panes_move": "6ecc3df6 TcOgo8IvUZiTUYUltg9IjHCH1P59E63iWg7ZZ3dZiTr0X6aTHRbcWJ_Gu3iW", + "two_panes_move_ask": "4fa663da AaalvBFba89_NIf3xrjG9cA1IjXWmEKE1jao9Sek-T-bdpdEers0IkIX2Dry", + "two_panes_move_body": "d05adfe5 hgENRWPHL7L13V-3s4Z9sraROdmocqj9fx06bzRBkn4KxZRXsmADmM7GduhT", + "two_panes_move_files_only": "476082d3 1jiHSeniYKGWP11wOFPFhNcB9HlYmIP0tYppfSzJ5OMXNt_89Ic-2azs6jJz", + "two_panes_move_ok": "6ecc3df6 TcOgo8IvUZiTUYUltgA9zHCH1P59E63iWg7ZZ3dZiTr0X6aTHRbcWJ_Gu3iW", + "two_panes_move_to": "e183a64d bVyMi_YlJQ98pVcUyt6_FQnDfSN2wo0Zkv7msw3WLn_kcM0XjmO2WwJxh2Pq", + "two_panes_moved": "2ef53baf ZUV2aAiSUVO4uBTxLjKI5roHiqiK1vKcYxZ1sMVcFz8oqr1iIdV3QsAb4HpS", + "two_panes_no_move_app_computer": "4abafd89 -cU7BFi2ViaTMGCsW0yBIb2y9d0-qRG90Mf_09wjne5L1b4JIk3v8ZWw6XHU", + "two_panes_no_move_computer": "e599262c VmSNU2njAMlay5aAB8RvDk2EHDFLm2d00eoPhQXAE-UnkGfJqsj_6NDYepIa", + "two_panes_no_move_server": "ea58cd6a 4Gpgr01TUa5gGyme8d_367hmGjK0THZHsEVBQ_yvUZ-Db41rsfYyOkVnD_3s", + "two_panes_not_removed": "2bb446e6 iYiWK2TfdwOsiMblGXUW8MrSe8TI4IKP4Jz1FEeKf7DpxfFpPr3cYnR4ymXx", + "two_panes_other_side": "8deeda4d 2PDFEcuYkATiIUQSXJYWm92Kq5hiByFumf9_ZCQrThKjtal4vPDYaAOvH_Md", + "two_panes_place": "8ff3588a bk74bRF0KYTLMvqCGOFx9_PydCJC6B2k7dnSrNd-RY4JOWoESIryxkShkhPW", + "two_panes_replace_body": "59583237 MQL_Iyi0QdB1_QW73Qm4L6R_zfrf8GrA1QZJl5DKw2YmTeKpoZ94zgHoxIRr", + "two_panes_replace_ok": "95e15439 N0zqLMSUkdOW687LrU_OI4TD20jMmD9yjWdOxJAxP8wgF8YGHeS5NGExs2PA", + "two_panes_replace_title": "0a86ef49 V_oNgIQikfIDBvG138vMhoKcrmZIcRRwGIDgk3vmCBPNJiG8AEl1Mr-rCsEF", + "two_panes_servers": "4bf08480 MraaEKfglmtLJWvb8pcPcj0Ehd1yUCsDD0UoOW76bwfZr8hBCfEQUSlvH5cz", + "two_panes_this_computer": "26f9f95a jwxDgf4YQpzWs1hwPC414g-l_2q-7hUrMoNFVNx22uJDVbmezgvUzYt8II7D", + "two_panes_toggle": "1ff753f9 o-oCvhpS_F4lwFTCWx6fz_DBHa04O2lFCf2tL7F7QALsFW4uxs9oE1FZypqQ", + "two_panes_toggle_title": "ff556957 jd-mLb-ore__T1gLK7M7HBxYhFlpAQaMj3n5WB262mFS0ygxPLD1kdG0dTBx", + "two_panes_unverified": "e4f505b6 JGAVIaOgvwfTGXHmzlk9OZeG8hQnxVh0DUZGpWZdFh5yTzUJZysp-7iINOhu", "unmount": "2ad51f6d Y0T14SbawXM8uk3xs3lJ5ggbFYyC4AiA4tP4KIgXM8w6DXnb_vl051Brw5kv", "update_apk_busy": "db49c962 LqZF5fQPDjXH6pTgmuGKNzk_2ARM4TDQgv3x2ZYkDeV73AGIaTLn71ntlNVV", "update_apk_busy_confirm": "d94343f8 tOhXqI_je2IG6GgZ766Qfubm3beqLKjwl7yTWjLDJC1tDMNaIOoSsNn33n33", @@ -9306,7 +9394,7 @@ "all.connect.7": "2aa10e38 FMK3VGFyibQI8kmXSbmjpO3KoGxaJNbQa4NtxMV_w8N1Z7mOkpzZMPPNi18W", "all.connect.8": "e3fb136d OAdw27kaYQ0M1MhWIVV6CEkIegorF8vQpXf3iENneRYPM2W07Rthy0BWfZf7", "all.connect.9": "1f3174d3 n-5jv3jIAJ8tpKNHQ2aKuMX8nOm_b7WEy1hGhjC_TAk3-LCb_utND7fc8hK-", - "all.console.1": "a3f5ee14 9MJJWLwtL1-BA4OoUvKLp3pe8FJr6NiR8LsAKhT4XtlC45XaaPK0NIqXw8Ro", + "all.console.1": "18615260 EVgzo1vAskJ1w9jdM1oYKwgNRDgPjEQTZlUCkNs_v_oRCup4wsmX2gkB517M", "all.console.10": "b6a70ff3 vBIQkF2guNxTAhUeNwRt-MxuJq4B0p9q-pcXD1dj97HcyGLCCOi3mfZPIyI9", "all.console.11": "b4e79d41 Z646rUktt7nAxHt8wENMxgDQ3lC5YVUXvzKjjafIN5cwSQBngOnE7x6d7C57", "all.console.12": "42115234 jI9K-T90nOt1DClx-SHMD4bp7iv9GfWi3VvdAs9jP8Wnw9HSG_O9lE2JBPcr", @@ -9316,7 +9404,7 @@ "all.console.16": "5c7d9051 zIH9M7r8hm8ei4sdqSbGvS-nSlORaLdP2XpQ4zeAsk2v32VMkiPOBhM1p3BN", "all.console.17": "e91d29e8 NKi6lG7_Pxfuj0dxUOuKCPyWEC-ZglFJBJxk7-h1c9LenmrsQ8G1iBT8yP2Z", "all.console.18": "d0d0bd62 ejswQoelqfCx5VB3gDWza4NDMWJc3Ka-YCljQErf92GzoKQLc0fmwQzlRLCf", - "all.console.19": "ae304aea mDL4hUjpKRnpAxAhjfwrUbCiBGw-Y41ZrZE9MswinEp3VYCBA4keW2AeQsMS", + "all.console.19": "aecb0171 41amfOsciQshYBMdR7AYUI3NcELMAZnE00jqLOQZw7cpInFNZ94GStENnZK8", "all.console.2": "58f33c10 KHDgL6JbEutdZ2jQ2gb7Pvcwshcc1S6pptQ5sDUSFxKWR6S24ThmGpYLalnp", "all.console.20": "d7bbc44a t-WS_VhDw4cpDJQAF0ET47hz6l3j-DDTv2A1XaD2IMoHMbBSMbmnr5gMeydQ", "all.console.3": "75f7666a IH9Q_bZb4Uzk6ATyEl3me0twkcsOlfndb1veW6Wv3CH5wTcyhOs832ZZdBtr", diff --git a/scripts/release/android-sign.sh b/scripts/release/android-sign.sh index e28d185dc..68afcde37 100755 --- a/scripts/release/android-sign.sh +++ b/scripts/release/android-sign.sh @@ -47,6 +47,8 @@ fi echo "Unsigned APKs: $arm64 ${armv7:-(no armv7)}" work="$(mktemp -d)" +# The decoded release keystore lives here: never leave it behind in the temp folder. +trap 'rm -rf "$work"' EXIT keystore="$work/release.jks" if [ -n "${ANDROID_KEYSTORE_BASE64:-}" ]; then diff --git a/scripts/release/fast-release.sh b/scripts/release/fast-release.sh index c1662d65c..76e935cac 100755 --- a/scripts/release/fast-release.sh +++ b/scripts/release/fast-release.sh @@ -182,6 +182,7 @@ git push -q -u origin "$BRANCH" PR="$(gh pr list --head "$BRANCH" --state open --json number --jq '.[0].number')" if [ -z "$PR" ]; then BODY="$(mktemp -t fast-release-body.XXXXXX)" + trap 'rm -f "$BODY"' EXIT { if [ "$GATE" = 1 ]; then echo "Fast release v$V (scripts/release/fast-release.sh --gate): bare checks, merged once the PR gate passed." diff --git a/scripts/release/merge-when-green.test.mjs b/scripts/release/merge-when-green.test.mjs index bb4acaee1..66dd54aea 100644 --- a/scripts/release/merge-when-green.test.mjs +++ b/scripts/release/merge-when-green.test.mjs @@ -65,8 +65,17 @@ const realJob = { id: 3, name: "security scan", conclusion: "failure", runner_na const browserJob = { id: 4, name: "client browser tests (3/3)", conclusion: "failure", runner_name: "r", steps: [{ name: "Browser workflow smoke test", conclusion: "failure" }] }; const ANNOTATIONS = { 2: [{ message: "apt could not download after 3 attempts: clang" }], 3: [{ message: "Process completed with exit code 1." }] }; +// Each run's folder is removed when the file's tests end, pass or fail (PS5UPLOAD_KEEP_TEST_TMP=1 +// keeps them to look at). +const runDirs = []; +nodeTest.after(() => { + if (process.env.PS5UPLOAD_KEEP_TEST_TMP) return; + for (const dir of runDirs) fs.rmSync(dir, { recursive: true, force: true }); +}); + function run({ gate, jobs = [], jobsAfter, pr = { state: "OPEN", isDraft: false, headRefOid: SHA }, rerunMode, mergeRc, log, args = [], shell }) { const dir = fs.mkdtempSync(path.join(os.tmpdir(), "merge-when-green-")); + runDirs.push(dir); const bin = path.join(dir, "bin"); fs.mkdirSync(bin); fs.writeFileSync(path.join(bin, "gh"), FAKE_GH, { mode: 0o755 }); diff --git a/scripts/release/release-check.sh b/scripts/release/release-check.sh index 8c70d2263..1ff50c21e 100755 --- a/scripts/release/release-check.sh +++ b/scripts/release/release-check.sh @@ -94,4 +94,6 @@ if (( failed )); then done exit 1 fi +# The logs are kept to read only when something failed. +rm -rf "$logs" echo "release-check: all passed" diff --git a/scripts/release/scan-artifacts.test.mjs b/scripts/release/scan-artifacts.test.mjs index 7dd477cec..d89480abe 100644 --- a/scripts/release/scan-artifacts.test.mjs +++ b/scripts/release/scan-artifacts.test.mjs @@ -1,13 +1,26 @@ import assert from "node:assert/strict"; import { execFile, execFileSync, spawnSync } from "node:child_process"; import { createHash } from "node:crypto"; -import { chmodSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs"; +import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { createServer } from "node:http"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import test from "node:test"; +import test, { after } from "node:test"; import { buildsDone, listFiles, newArtifacts } from "./scan-artifacts.mjs"; +// Temp folders are removed when the file's tests end, pass or fail (PS5UPLOAD_KEEP_TEST_TMP=1 +// keeps them to look at). +const tempDirs = []; +const tempDir = (prefix) => { + const dir = mkdtempSync(join(tmpdir(), prefix)); + tempDirs.push(dir); + return dir; +}; +after(() => { + if (process.env.PS5UPLOAD_KEEP_TEST_TMP) return; + for (const dir of tempDirs) rmSync(dir, { recursive: true, force: true }); +}); + const script = new URL("./scan-artifacts.mjs", import.meta.url).pathname; // The end-to-end tests build artifact zips with the `zip` command; Windows runners have none (the // scanner itself only runs on Linux, in publish). @@ -49,7 +62,7 @@ test("buildsDone: every build-* job finished, and there is one", () => { }); test("listFiles: recursive and sorted", () => { - const dir = mkdtempSync(join(tmpdir(), "scan-list-")); + const dir = tempDir("scan-list-"); mkdirSync(join(dir, "b")); writeFileSync(join(dir, "b", "x"), "x"); writeFileSync(join(dir, "a"), "a"); @@ -60,7 +73,7 @@ test("listFiles: recursive and sorted", () => { // still going; on the next poll it has finished and uploaded. A fake clamscan flags a file // named EICAR. function fakeRun(t, { infected = false } = {}) { - const root = mkdtempSync(join(tmpdir(), "scan-run-")); + const root = tempDir("scan-run-"); const mkzip = (name, files) => { const src = join(root, `src-${name}`); mkdirSync(src, { recursive: true }); diff --git a/site/i18n/ar.json b/site/i18n/ar.json index d4e4630b7..ee49de55c 100644 --- a/site/i18n/ar.json +++ b/site/i18n/ar.json @@ -26,7 +26,7 @@ "all.connect.7": "إعدادات محفوظة لكل PS5: إبقاؤه مستيقظًا، والراحة بعد الرفع، والإيقاظ من أجل الرفع، وغير ذلك", "all.connect.8": "شارك مع صديق الحفظ ولقطات الشاشة والمقاطع والغش وإعدادات التحكم وملاحظة وبرامج homebrew", "all.connect.9": "يطلب صديقك وتسمح أنت، فتنتقل مباشرةً بينكما، عبر Wi-Fi لديك أو عبر الإنترنت", - "all.console.1": "أرسل الحمولات من فهرس أو من قوائمك أو ملفاتك، مع قوائم تشغيل وتحميل عند الإقلاع", + "all.console.1": "أرسل الحمولات من كتالوج أو من مشاريعك على GitHub أو Gitea أو من ملفات، مع قوائم تشغيل وتحميل عند الإقلاع", "all.console.10": "تنظيف الملفات المتبقية", "all.console.11": "فحص السلامة واختبار السرعة: ما يجب إصلاحه بين PS5 والتطبيق والشبكة", "all.console.12": "اعرف ما يعمل وأي المنافذ مفتوحة، وأوقف أي عملية", @@ -36,7 +36,7 @@ "all.console.16": "سطر أوامر للجهاز وسجل النواة وسجل تدقيق، لما يحدث خلل", "all.console.17": "PS5Upload Minion: صفحة في متصفح PS5 نفسه للألعاب والحفظ والملفات والحمولات والغش", "all.console.18": "تقرير الأخطاء: سجلات التطبيق والمحرك والجهاز في ملف zip واحد، بلا تفاصيل خاصة", - "all.console.19": "تحديثات الحمولات: حدّث واحدة أو الكل، أو تراجع، أو دعها تبقى محدّثة وحدها", + "all.console.19": "تحديثات الحمولات: اعرف متى يصدر إصدار جديد، وحدّث ما يأتي من مشاريعك، وارجع إلى الإصدار السابق", "all.console.2": "احتفظ بالحمولات على الجهاز في Payload Manager، والمساعد أيضًا، لتشغيلها دون حاسوب", "all.console.20": "اختر الحمولات التي يحتفظ بها Payload Manager على كل جهاز ويحمّلها عند الإقلاع، وزامنها", "all.console.3": "اصنع ذاكرة USB تحمّل حمولاتك", diff --git a/site/i18n/bn.json b/site/i18n/bn.json index 62b5a4b2b..7cd503eac 100644 --- a/site/i18n/bn.json +++ b/site/i18n/bn.json @@ -26,7 +26,7 @@ "all.connect.7": "প্রতিটি PS5-এর আলাদা সেটিংস: জাগিয়ে রাখা, আপলোডের পর রেস্ট, আপলোডের জন্য জাগানো আর আরও অনেক কিছু", "all.connect.8": "সেভ, স্ক্রিনশট আর ক্লিপ, চিট, কন্ট্রোল, একটি নোট আর homebrew অ্যাপ বন্ধুর সঙ্গে শেয়ার করুন", "all.connect.9": "বন্ধু চায়, আপনি অনুমতি দেন; সব সরাসরি আপনাদের মধ্যে যায়, আপনার Wi-Fi-তে বা ইন্টারনেটে", - "all.console.1": "ক্যাটালগ, নিজের তালিকা বা ফাইল থেকে পেলোড পাঠান, প্লেলিস্ট আর বুটে লোড সহ", + "all.console.1": "ক্যাটালগ, আপনার নিজের GitHub বা Gitea প্রজেক্ট বা ফাইল থেকে পেলোড পাঠান, প্লেলিস্ট ও চালু হওয়ার সময় লোড সহ", "all.console.10": "পড়ে থাকা বাড়তি ফাইল পরিষ্কার করুন", "all.console.11": "হেলথ চেক আর স্পিড টেস্ট: PS5, অ্যাপ আর নেটওয়ার্কের মধ্যে কী ঠিক করতে হবে", "all.console.12": "কী চলছে আর কোন পোর্ট খোলা দেখুন, আর কোনো প্রসেস বন্ধ করুন", @@ -36,7 +36,7 @@ "all.console.16": "কনসোল শেল, কার্নেল লগ আর অডিট লগ, কিছু গোলমাল হলে কাজে লাগে", "all.console.17": "PS5Upload Minion: PS5-এর নিজের ব্রাউজারে গেম, সেভ, ফাইল, পেলোড আর চিটের একটি পেজ", "all.console.18": "বাগ রিপোর্ট: অ্যাপ, ইঞ্জিন আর কনসোলের লগ একটি zip-এ, ব্যক্তিগত তথ্য বাদ দিয়ে", - "all.console.19": "পেলোড আপডেট: একটি বা সব আপডেট করুন, আগের ভার্সনে ফিরুন, বা নিজে থেকেই আপডেট হতে দিন", + "all.console.19": "পেলোড আপডেট: নতুন রিলিজ এলে জানুন, নিজের প্রজেক্ট থেকে আসাগুলো আপডেট করুন, আগের সংস্করণে ফিরে যান", "all.console.2": "Payload Manager-এ কনসোলেই পেলোড রাখুন, হেল্পারও, যাতে কম্পিউটার ছাড়াই চালু করা যায়", "all.console.20": "Payload Manager প্রতিটি কনসোলে কোন পেলোড রাখবে আর বুটে লোড করবে তা বেছে নিন, আর সেগুলো সিঙ্ক করুন", "all.console.3": "আপনার পেলোড লোড করে এমন একটি USB স্টিক বানান", diff --git a/site/i18n/de.json b/site/i18n/de.json index db85aea93..a2bbe3664 100644 --- a/site/i18n/de.json +++ b/site/i18n/de.json @@ -26,7 +26,7 @@ "all.connect.7": "Einstellungen für jede PS5 einzeln: wach halten, Ruhemodus nach Uploads, für Uploads aufwecken und mehr", "all.connect.8": "Spielstände, Screenshots und Clips, Cheats, Steuerung, eine Notiz und Homebrew-Apps mit einem Freund teilen", "all.connect.9": "Dein Freund fragt, du lässt es zu; alles geht direkt zwischen euch, im WLAN oder übers Internet", - "all.console.1": "Payloads aus einem Katalog, eigenen Listen oder Dateien senden, mit Playlists und Laden beim Start", + "all.console.1": "Payloads aus einem Katalog, eigenen GitHub- oder Gitea-Projekten oder Dateien senden, mit Playlists und Laden beim Start", "all.console.10": "Übrig gebliebene Dateien aufräumen", "all.console.11": "Systemprüfung und Geschwindigkeitstest: was zwischen PS5, App und Netzwerk zu beheben ist", "all.console.12": "Sehen, was läuft und welche Ports offen sind, und einen Prozess beenden", @@ -36,7 +36,7 @@ "all.console.16": "Eine Konsolen-Shell, das Kernel-Log und ein Audit-Log, wenn etwas nicht stimmt", "all.console.17": "PS5Upload Minion: eine Seite im Browser der PS5 für Spiele, Spielstände, Dateien, Payloads und Cheats", "all.console.18": "Fehlerbericht: die Logs von App, Engine und Konsole in einer ZIP-Datei, private Angaben entfernt", - "all.console.19": "Payload-Updates: eines oder alle aktualisieren, zurückrollen oder sie von selbst aktuell halten", + "all.console.19": "Payload-Updates: sehen, wann ein neues Release da ist, die aus eigenen Projekten aktualisieren, zurückrollen", "all.console.2": "Payloads im Payload Manager auf der Konsole behalten, auch den Helfer, um sie ohne Computer zu starten", "all.console.20": "Wählen, welche Payloads der Payload Manager auf jeder Konsole behält und beim Start lädt, und sie abgleichen", "all.console.3": "Einen USB-Stick erstellen, der deine Payloads lädt", diff --git a/site/i18n/en.json b/site/i18n/en.json index 7bd2b7d3a..e74662511 100644 --- a/site/i18n/en.json +++ b/site/i18n/en.json @@ -26,7 +26,7 @@ "all.connect.7": "Settings kept for each PS5: keep awake, rest after uploads, wake for uploads and more", "all.connect.8": "Share saves, screenshots and clips, cheats, controls, a note and homebrew apps with a friend", "all.connect.9": "Your friend asks and you allow; it goes straight between you, on your Wi-Fi or over the internet", - "all.console.1": "Send payloads from a catalogue, your own lists or files, with playlists and loading at boot", + "all.console.1": "Send payloads from a catalogue, your own GitHub or Gitea projects, or files, with playlists and loading at boot", "all.console.10": "Clean up leftover files", "all.console.11": "Health check and speed test: what to fix between the PS5, the app and the network", "all.console.12": "See what's running and which ports are open, and stop a process", @@ -36,7 +36,7 @@ "all.console.16": "A console shell, the kernel log and an audit log, for when something is off", "all.console.17": "PS5Upload Minion: a page in the PS5's own browser for games, saves, files, payloads and cheats", "all.console.18": "Bug Report: the app's, the engine's and the console's logs in one zip, private details removed", - "all.console.19": "Payload updates: update one or all, roll back, or keep them up to date by themselves", + "all.console.19": "Payload updates: see when a new release is out, update the ones from your own projects, roll back", "all.console.2": "Keep payloads on the console in Payload Manager, the helper too, to start them with no computer", "all.console.20": "Choose which payloads Payload Manager keeps on each console and loads at boot, and sync them", "all.console.3": "Make a USB stick that loads your payloads", diff --git a/site/i18n/es.json b/site/i18n/es.json index 4f86f676e..a9b24410f 100644 --- a/site/i18n/es.json +++ b/site/i18n/es.json @@ -26,7 +26,7 @@ "all.connect.7": "Ajustes guardados para cada PS5: mantener despierta, reposo tras las subidas, despertar para subir y más", "all.connect.8": "Comparte con un amigo partidas guardadas, capturas y clips, trucos, controles, una nota y apps homebrew", "all.connect.9": "Tu amigo lo pide y tú lo permites; va directo entre vosotros, por tu Wi-Fi o por internet", - "all.console.1": "Envía payloads desde un catálogo, tus propias listas o archivos, con listas de reproducción y carga al arrancar", + "all.console.1": "Envía payloads desde un catálogo, tus propios proyectos de GitHub o Gitea o archivos, con listas y carga al arrancar", "all.console.10": "Limpia archivos sobrantes", "all.console.11": "Comprobación y prueba de velocidad: qué arreglar entre la PS5, la app y la red", "all.console.12": "Mira qué se está ejecutando y qué puertos están abiertos, y detén un proceso", @@ -36,7 +36,7 @@ "all.console.16": "Una terminal de la consola, el registro del kernel y un registro de auditoría, para cuando algo falla", "all.console.17": "PS5Upload Minion: una página en el propio navegador de la PS5 para juegos, partidas, archivos, payloads y trucos", "all.console.18": "Informe de error: los registros de la app, del motor y de la consola en un .zip, sin datos privados", - "all.console.19": "Actualizaciones de payloads: actualiza uno o todos, vuelve atrás, o deja que se mantengan al día solos", + "all.console.19": "Actualizaciones de payloads: mira cuándo sale una versión nueva, actualiza las de tus propios proyectos, vuelve atrás", "all.console.2": "Guarda payloads en la consola con Payload Manager, también el ayudante, para iniciarlos sin ordenador", "all.console.20": "Elige qué payloads guarda Payload Manager en cada consola y carga al arrancar, y sincronízalos", "all.console.3": "Crea una memoria USB que carga tus payloads", diff --git a/site/i18n/fa.json b/site/i18n/fa.json index 3c7f04f42..fa4793fe7 100644 --- a/site/i18n/fa.json +++ b/site/i18n/fa.json @@ -26,7 +26,7 @@ "all.connect.7": "تنظیمات جداگانه برای هر PS5: بیدار نگه‌داشتن، استراحت پس از آپلود، بیدار کردن برای آپلود و موارد دیگر", "all.connect.8": "ذخیره‌ها، اسکرین‌شات‌ها و کلیپ‌ها، تقلب‌ها، کنترل‌ها، یک یادداشت و برنامه‌های homebrew را با یک دوست به اشتراک بگذارید", "all.connect.9": "دوستتان درخواست می‌دهد و شما اجازه می‌دهید؛ همه‌چیز مستقیم بین شما می‌رود، روی Wi-Fi شما یا از راه اینترنت", - "all.console.1": "پی‌لودها را از کاتالوگ، فهرست‌ها یا فایل‌های خودتان بفرستید، با فهرست پخش و بارگذاری هنگام روشن شدن", + "all.console.1": "ارسال پی‌لودها از یک کاتالوگ، پروژه‌های GitHub یا Gitea خودتان یا فایل‌ها، با فهرست پخش و بارگذاری هنگام راه‌اندازی", "all.console.10": "پاک‌سازی فایل‌های باقی‌مانده", "all.console.11": "بررسی سلامت و آزمون سرعت: چه چیزی بین PS5، برنامه و شبکه باید درست شود", "all.console.12": "ببینید چه چیزی در حال اجراست و کدام درگاه‌ها باز است، و یک فرایند را متوقف کنید", @@ -36,7 +36,7 @@ "all.console.16": "پوستهٔ کنسول، لاگ هسته و لاگ ممیزی، برای وقتی که چیزی درست نیست", "all.console.17": "PS5Upload Minion: صفحه‌ای در مرورگر خود PS5 برای بازی‌ها، ذخیره‌ها، فایل‌ها، پی‌لودها و تقلب‌ها", "all.console.18": "گزارش اشکال: لاگ‌های برنامه، موتور و کنسول در یک zip، بدون اطلاعات خصوصی", - "all.console.19": "به‌روزرسانی پی‌لودها: یکی یا همه را به‌روز کنید، به نسخهٔ قبل برگردانید، یا بگذارید خودشان به‌روز بمانند", + "all.console.19": "به‌روزرسانی پی‌لودها: ببینید کی انتشار تازه‌ای آمده، آن‌هایی را که از پروژه‌های خودتان است به‌روز کنید، به نسخه قبل برگردید", "all.console.2": "پی‌لودها، و خود کمک‌یار، را در Payload Manager روی کنسول نگه دارید تا بی‌کامپیوتر اجرا شوند", "all.console.20": "انتخاب کنید Payload Manager کدام پی‌لودها را روی هر کنسول نگه دارد و هنگام روشن شدن بارگذاری کند، و همگام‌شان کنید", "all.console.3": "ساختن فلش USB‌ای که پی‌لودهای شما را بارگذاری می‌کند", diff --git a/site/i18n/fr.json b/site/i18n/fr.json index b157b2280..9be2064db 100644 --- a/site/i18n/fr.json +++ b/site/i18n/fr.json @@ -26,7 +26,7 @@ "all.connect.7": "Des réglages propres à chaque PS5 : garder éveillée, repos après les envois, réveil pour les envois et plus", "all.connect.8": "Partage avec un ami tes sauvegardes, captures et clips, cheats, commandes, une note et des apps homebrew", "all.connect.9": "Ton ami demande et tu autorises ; tout passe directement entre vous, sur ton Wi-Fi ou par internet", - "all.console.1": "Envoie des payloads depuis un catalogue, tes propres listes ou des fichiers, avec playlists et chargement au démarrage", + "all.console.1": "Envoyez des payloads depuis un catalogue, vos propres projets GitHub ou Gitea ou des fichiers, avec des listes et le chargement au démarrage", "all.console.10": "Nettoie les fichiers qui traînent", "all.console.11": "Bilan de santé et test de vitesse : ce qu'il faut régler entre la PS5, l'app et le réseau", "all.console.12": "Vois ce qui tourne et quels ports sont ouverts, et arrête un processus", @@ -36,7 +36,7 @@ "all.console.16": "Un shell sur la console, le journal du noyau et un journal d'audit, pour quand quelque chose cloche", "all.console.17": "PS5Upload Minion : une page dans le navigateur de la PS5 pour les jeux, sauvegardes, fichiers, payloads et cheats", "all.console.18": "Rapport de bug : les journaux de l'app, du moteur et de la console dans un seul zip, sans les infos privées", - "all.console.19": "Mises à jour des payloads : mets-en un ou tous à jour, reviens en arrière, ou laisse-les se tenir à jour tout seuls", + "all.console.19": "Mises à jour des payloads : voir quand une nouvelle version sort, mettre à jour celles de vos propres projets, revenir en arrière", "all.console.2": "Garde les payloads sur la console dans Payload Manager, l'assistant aussi, pour les lancer sans ordinateur", "all.console.20": "Choisis quels payloads Payload Manager garde sur chaque console et charge au démarrage, et synchronise-les", "all.console.3": "Crée une clé USB qui charge tes payloads", diff --git a/site/i18n/hi.json b/site/i18n/hi.json index 36ffeaa39..7ec08843f 100644 --- a/site/i18n/hi.json +++ b/site/i18n/hi.json @@ -26,7 +26,7 @@ "all.connect.7": "हर PS5 की अपनी सेटिंग्स: जगाए रखना, अपलोड के बाद रेस्ट, अपलोड के लिए जगाना और भी बहुत कुछ", "all.connect.8": "सेव, स्क्रीनशॉट और क्लिप, चीट्स, कंट्रोल, एक नोट और homebrew ऐप किसी दोस्त के साथ शेयर करें", "all.connect.9": "दोस्त माँगता है और आप अनुमति देते हैं; सब कुछ सीधे आप दोनों के बीच जाता है, आपके Wi-Fi पर या इंटरनेट पर", - "all.console.1": "कैटलॉग, अपनी सूचियों या फ़ाइलों से पेलोड भेजें, प्लेलिस्ट और बूट पर लोड के साथ", + "all.console.1": "कैटलॉग, अपने GitHub या Gitea प्रोजेक्ट या फ़ाइलों से पेलोड भेजें, प्लेलिस्ट और बूट पर लोडिंग के साथ", "all.console.10": "बची हुई फ़ाइलें साफ़ करें", "all.console.11": "हेल्थ चेक और स्पीड टेस्ट: PS5, ऐप और नेटवर्क के बीच क्या ठीक करना है", "all.console.12": "देखें क्या चल रहा है और कौन से पोर्ट खुले हैं, और कोई प्रोसेस रोकें", @@ -36,7 +36,7 @@ "all.console.16": "कंसोल शेल, कर्नेल लॉग और ऑडिट लॉग, जब कुछ गड़बड़ हो", "all.console.17": "PS5Upload Minion: PS5 के अपने ब्राउज़र में गेम, सेव, फ़ाइलें, पेलोड और चीट्स के लिए एक पेज", "all.console.18": "बग रिपोर्ट: ऐप, इंजन और कंसोल के लॉग एक zip में, निजी जानकारी हटाकर", - "all.console.19": "पेलोड अपडेट: एक या सभी अपडेट करें, पिछले वर्ज़न पर लौटें, या उन्हें ख़ुद अपडेट होते रहने दें", + "all.console.19": "पेलोड अपडेट: नई रिलीज़ आने पर देखें, अपने प्रोजेक्ट वाले अपडेट करें, पिछले पर लौटें", "all.console.2": "Payload Manager में पेलोड कंसोल पर ही रखें, हेल्पर भी, ताकि बिना कंप्यूटर के उन्हें शुरू कर सकें", "all.console.20": "चुनें कि Payload Manager हर कंसोल पर कौन-से पेलोड रखे और बूट पर लोड करे, और उन्हें सिंक करें", "all.console.3": "ऐसी USB स्टिक बनाएँ जो आपके पेलोड लोड करे", diff --git a/site/i18n/hu.json b/site/i18n/hu.json index d0a542966..0c1e46e67 100644 --- a/site/i18n/hu.json +++ b/site/i18n/hu.json @@ -26,7 +26,7 @@ "all.connect.7": "PS5-önként megőrzött beállítások: ébren tartás, pihenés feltöltés után, ébresztés feltöltéshez és még több", "all.connect.8": "Oszd meg egy barátoddal a mentéseidet, képernyőképeidet és klipjeidet, a csalásokat, az irányítást, egy jegyzetet és homebrew appokat", "all.connect.9": "A barátod kér, te engedélyezed, és közvetlenül megy köztetek, a Wi-Fi-den vagy az interneten át", - "all.console.1": "Payloadok küldése katalógusból, saját listákból vagy fájlokból, lejátszási listákkal és indításkori betöltéssel", + "all.console.1": "Payloadok küldése katalógusból, saját GitHub- vagy Gitea-projektekből vagy fájlokból, lejátszási listákkal és indításkori betöltéssel", "all.console.10": "Megmaradt fájlok eltakarítása", "all.console.11": "Állapotfelmérés és sebességteszt: mit kell javítani a PS5, az app és a hálózat között", "all.console.12": "Lásd, mi fut és mely portok nyitottak, és állíts le egy folyamatot", @@ -36,7 +36,7 @@ "all.console.16": "Konzolos shell, kernelnapló és auditnapló, ha valami nem stimmel", "all.console.17": "PS5Upload Minion: egy oldal a PS5 saját böngészőjében játékokhoz, mentésekhez, fájlokhoz, payloadokhoz és csalásokhoz", "all.console.18": "Hibajelentés: az app, a motor és a konzol naplói egy zipben, a személyes adatok nélkül", - "all.console.19": "Payload-frissítések: frissíts egyet vagy mindet, állj vissza, vagy hagyd, hogy maguktól naprakészek maradjanak", + "all.console.19": "Payload-frissítések: lásd, mikor jön új kiadás, frissítsd a saját projektjeidből valókat, vagy állj vissza", "all.console.2": "Tartsd a payloadokat a konzolon a Payload Managerben, a segédprogramot is, hogy számítógép nélkül indíthasd őket", "all.console.20": "Válaszd ki, mely payloadokat tartsa a Payload Manager az egyes konzolokon és töltse be indításkor, és szinkronizáld őket", "all.console.3": "Készíts USB-kulcsot, amely betölti a payloadjaidat", diff --git a/site/i18n/id.json b/site/i18n/id.json index 650f1d9d3..fc4bb7460 100644 --- a/site/i18n/id.json +++ b/site/i18n/id.json @@ -26,7 +26,7 @@ "all.connect.7": "Pengaturan disimpan per PS5: tetap terjaga, istirahat setelah unggahan, bangun untuk unggahan, dan lainnya", "all.connect.8": "Bagikan simpanan, tangkapan layar dan klip, cheat, kontrol, catatan, dan aplikasi homebrew ke teman", "all.connect.9": "Teman Anda meminta, Anda mengizinkan; semuanya langsung di antara kalian, lewat Wi-Fi Anda atau internet", - "all.console.1": "Kirim payload dari katalog, daftar atau file Anda sendiri, dengan playlist dan pemuatan saat boot", + "all.console.1": "Kirim payload dari katalog, proyek GitHub atau Gitea Anda sendiri, atau file, dengan daftar putar dan pemuatan saat boot", "all.console.10": "Bersihkan file sisa", "all.console.11": "Cek kesehatan dan uji kecepatan: apa yang perlu dibenahi antara PS5, aplikasi, dan jaringan", "all.console.12": "Lihat apa yang berjalan dan port mana yang terbuka, lalu hentikan proses", @@ -36,7 +36,7 @@ "all.console.16": "Shell konsol, log kernel, dan log audit, untuk saat ada yang tidak beres", "all.console.17": "PS5Upload Minion: halaman di peramban PS5 sendiri untuk gim, simpanan, file, payload, dan cheat", "all.console.18": "Laporan bug: log aplikasi, engine, dan konsol dalam satu zip, tanpa data pribadi", - "all.console.19": "Pembaruan payload: perbarui satu atau semuanya, kembalikan ke versi lama, atau biarkan diperbarui sendiri", + "all.console.19": "Pembaruan payload: lihat kapan rilis baru keluar, perbarui yang dari proyek Anda sendiri, kembalikan versi sebelumnya", "all.console.2": "Simpan payload di konsol dalam Payload Manager, helper juga, untuk menjalankannya tanpa komputer", "all.console.20": "Pilih payload mana yang disimpan Payload Manager di tiap konsol dan dimuat saat boot, lalu sinkronkan", "all.console.3": "Buat flashdisk USB yang memuat payload Anda", diff --git a/site/i18n/it.json b/site/i18n/it.json index 2ac09bec3..e88c1c0a0 100644 --- a/site/i18n/it.json +++ b/site/i18n/it.json @@ -26,7 +26,7 @@ "all.connect.7": "Impostazioni salvate per ogni PS5: mantieni attiva, riposo dopo i caricamenti, riattivazione per i caricamenti e altro", "all.connect.8": "Condividi con un amico salvataggi, screenshot e clip, cheat, comandi, una nota e app homebrew", "all.connect.9": "Il tuo amico chiede e tu consenti; tutto passa direttamente tra voi, sul tuo Wi-Fi o via internet", - "all.console.1": "Invia payload da un catalogo, dalle tue liste o da file, con playlist e caricamento all'avvio", + "all.console.1": "Invia payload da un catalogo, dai tuoi progetti GitHub o Gitea o da file, con playlist e caricamento all'avvio", "all.console.10": "Elimina i file rimasti", "all.console.11": "Controllo e test di velocità: cosa sistemare tra la PS5, l'app e la rete", "all.console.12": "Guarda cosa è in esecuzione e quali porte sono aperte, e ferma un processo", @@ -36,7 +36,7 @@ "all.console.16": "Una shell della console, il log del kernel e un log di controllo, per quando qualcosa non va", "all.console.17": "PS5Upload Minion: una pagina nel browser della PS5 per giochi, salvataggi, file, payload e cheat", "all.console.18": "Segnalazione bug: i log dell'app, del motore e della console in un unico zip, senza dati privati", - "all.console.19": "Aggiornamenti dei payload: aggiornane uno o tutti, torna indietro, o lascia che si aggiornino da soli", + "all.console.19": "Aggiornamenti dei payload: vedi quando esce una nuova release, aggiorna quelli dei tuoi progetti, torna indietro", "all.console.2": "Tieni i payload sulla console in Payload Manager, anche l'helper, per avviarli senza computer", "all.console.20": "Scegli quali payload Payload Manager tiene su ogni console e carica all'avvio, e sincronizzali", "all.console.3": "Crea una chiavetta USB che carica i tuoi payload", diff --git a/site/i18n/ja.json b/site/i18n/ja.json index 6bc75df4e..864af2e90 100644 --- a/site/i18n/ja.json +++ b/site/i18n/ja.json @@ -26,7 +26,7 @@ "all.connect.7": "PS5 ごとに保存される設定:スリープ防止、アップロード後にレストモード、アップロード時に起動など", "all.connect.8": "セーブ、スクリーンショットとクリップ、チート、操作設定、メモ、自作アプリをフレンドと共有", "all.connect.9": "フレンドが申請して、あなたが許可。Wi-Fi でもインターネット越しでも、ふたりの間で直接届きます", - "all.console.1": "カタログ、自分のリスト、ファイルからペイロードを送信。プレイリストや起動時の読み込みにも対応", + "all.console.1": "カタログ、自分の GitHub や Gitea のプロジェクト、ファイルからペイロードを送信。プレイリストや起動時の読み込みにも対応", "all.console.10": "残ったファイルを掃除", "all.console.11": "ヘルスチェックと速度テスト:PS5、アプリ、ネットワークの間で直すべき点がわかります", "all.console.12": "実行中のプロセスと開いているポートを確認し、プロセスを止める", @@ -36,7 +36,7 @@ "all.console.16": "本体のシェル、カーネルログ、監査ログ。何かおかしいときに", "all.console.17": "PS5Upload Minion:PS5 のブラウザーで開く、ゲーム、セーブ、ファイル、ペイロード、チートのページ", "all.console.18": "バグレポート:アプリ、エンジン、本体のログをひとつの zip に。個人情報は削除済み", - "all.console.19": "ペイロードの更新:ひとつずつでもまとめてでも更新、元に戻す、自動で最新に保つ", + "all.console.19": "ペイロードの更新: 新しいリリースが出たことがわかり、自分のプロジェクトのものを更新でき、元に戻すこともできる", "all.console.2": "ヘルパーも含めペイロードを本体の Payload Manager に置けば、パソコンなしで起動できます", "all.console.20": "Payload Manager が各本体に置いて起動時に読み込むペイロードを選び、同期", "all.console.3": "ペイロードを読み込む USB メモリーを作成", diff --git a/site/i18n/ko.json b/site/i18n/ko.json index 7681def40..bd1560e91 100644 --- a/site/i18n/ko.json +++ b/site/i18n/ko.json @@ -26,7 +26,7 @@ "all.connect.7": "PS5마다 따로 저장되는 설정: 깨어 있게 유지, 업로드 후 휴식 모드, 업로드할 때 깨우기 등", "all.connect.8": "세이브, 스크린샷과 클립, 치트, 조작 설정, 메모, 홈브루 앱을 친구와 공유", "all.connect.9": "친구가 요청하고 내가 허용하면, 내 Wi-Fi에서든 인터넷으로든 서로 사이에서 바로 전달됩니다", - "all.console.1": "카탈로그, 내 목록이나 파일에서 페이로드 전송, 재생 목록과 부팅 시 로드 지원", + "all.console.1": "카탈로그, 내 GitHub 또는 Gitea 프로젝트, 파일에서 페이로드를 보내고, 재생 목록과 부팅 시 로드도 지원", "all.console.10": "남은 파일 정리", "all.console.11": "상태 점검과 속도 테스트: PS5, 앱, 네트워크 사이에서 무엇을 고쳐야 할지", "all.console.12": "실행 중인 프로세스와 열린 포트를 보고, 프로세스 종료", @@ -36,7 +36,7 @@ "all.console.16": "콘솔 셸, 커널 로그, 감사 로그. 뭔가 이상할 때", "all.console.17": "PS5Upload Minion: PS5 자체 브라우저에서 게임, 저장 데이터, 파일, 페이로드, 치트를 다루는 페이지", "all.console.18": "버그 신고: 앱, 엔진, 콘솔의 로그를 zip 하나로, 개인 정보는 제거", - "all.console.19": "페이로드 업데이트: 하나씩 또는 한꺼번에 업데이트, 되돌리기, 알아서 최신으로 유지", + "all.console.19": "페이로드 업데이트: 새 릴리스가 나오면 알 수 있고, 내 프로젝트의 것은 업데이트하고, 되돌릴 수 있음", "all.console.2": "헬퍼를 포함한 페이로드를 콘솔의 Payload Manager에 두면 컴퓨터 없이 실행", "all.console.20": "Payload Manager가 콘솔마다 보관하고 부팅 때 불러올 페이로드를 고르고 동기화", "all.console.3": "페이로드를 로드하는 USB 메모리 만들기", diff --git a/site/i18n/pl.json b/site/i18n/pl.json index d31065b04..ec9c1e31a 100644 --- a/site/i18n/pl.json +++ b/site/i18n/pl.json @@ -26,7 +26,7 @@ "all.connect.7": "Ustawienia zapisywane dla każdej PS5 osobno: nie usypiaj, spoczynek po wysyłaniu, wybudzanie do wysyłania i więcej", "all.connect.8": "Udostępnij znajomemu zapisy, zrzuty ekranu i klipy, kody, sterowanie, notatkę i aplikacje homebrew", "all.connect.9": "Znajomy prosi, ty zezwalasz, a wszystko idzie prosto między wami, przez twoje Wi-Fi lub przez internet", - "all.console.1": "Wysyłaj payloady z katalogu, własnych list lub plików, z playlistami i ładowaniem przy starcie", + "all.console.1": "Wysyłaj payloady z katalogu, własnych projektów GitHub lub Gitea albo z plików, z playlistami i ładowaniem przy starcie", "all.console.10": "Usuń pozostałe pliki", "all.console.11": "Kontrola stanu i test szybkości: co poprawić między PS5, aplikacją a siecią", "all.console.12": "Zobacz, co działa i które porty są otwarte, i zatrzymaj proces", @@ -36,7 +36,7 @@ "all.console.16": "Powłoka konsoli, log jądra i log audytu, gdy coś jest nie tak", "all.console.17": "PS5Upload Minion: strona w przeglądarce samej PS5 do gier, zapisów, plików, payloadów i kodów", "all.console.18": "Raport błędu: logi aplikacji, silnika i konsoli w jednym pliku zip, bez danych prywatnych", - "all.console.19": "Aktualizacje payloadów: aktualizuj jeden lub wszystkie, cofaj albo pozwól im aktualizować się samym", + "all.console.19": "Aktualizacje payloadów: zobacz, kiedy wyszło nowe wydanie, zaktualizuj te z własnych projektów, cofnij", "all.console.2": "Trzymaj payloady na konsoli w Payload Managerze, także pomocnika, by uruchamiać je bez komputera", "all.console.20": "Wybierz, które payloady Payload Manager trzyma na każdej konsoli i ładuje przy starcie, i synchronizuj je", "all.console.3": "Przygotuj pendrive, który ładuje twoje payloady", diff --git a/site/i18n/pt-BR.json b/site/i18n/pt-BR.json index 5184e15e2..fcae5f228 100644 --- a/site/i18n/pt-BR.json +++ b/site/i18n/pt-BR.json @@ -26,7 +26,7 @@ "all.connect.7": "Configurações guardadas para cada PS5: manter acordado, repouso após envios, acordar para envios e mais", "all.connect.8": "Compartilhe com um amigo saves, capturas e clipes, trapaças, controles, uma nota e apps homebrew", "all.connect.9": "Seu amigo pede e você permite; tudo vai direto entre vocês, no seu Wi-Fi ou pela internet", - "all.console.1": "Envie payloads de um catálogo, das suas listas ou de arquivos, com playlists e carregamento ao ligar", + "all.console.1": "Envie payloads de um catálogo, dos seus próprios projetos no GitHub ou Gitea ou de arquivos, com playlists e carregamento na inicialização", "all.console.10": "Limpe arquivos que sobraram", "all.console.11": "Verificação e teste de velocidade: o que corrigir entre o PS5, o app e a rede", "all.console.12": "Veja o que está rodando e quais portas estão abertas, e encerre um processo", @@ -36,7 +36,7 @@ "all.console.16": "Um shell do console, o log do kernel e um log de auditoria, para quando algo está estranho", "all.console.17": "PS5Upload Minion: uma página no navegador do próprio PS5 para jogos, saves, arquivos, payloads e trapaças", "all.console.18": "Relatório de bug: os logs do app, do motor e do console num só .zip, sem dados pessoais", - "all.console.19": "Atualizações de payloads: atualize um ou todos, volte à versão anterior, ou deixe que se mantenham atualizados sozinhos", + "all.console.19": "Atualizações de payloads: veja quando sai uma versão nova, atualize as dos seus próprios projetos, volte atrás", "all.console.2": "Guarde payloads no console com o Payload Manager, o auxiliar também, para iniciá-los sem computador", "all.console.20": "Escolha quais payloads o Payload Manager guarda em cada console e carrega ao ligar, e sincronize-os", "all.console.3": "Crie um pendrive que carrega os seus payloads", diff --git a/site/i18n/ru.json b/site/i18n/ru.json index ddbf303b8..0bf7a203f 100644 --- a/site/i18n/ru.json +++ b/site/i18n/ru.json @@ -26,7 +26,7 @@ "all.connect.7": "Настройки для каждой PS5 отдельно: не засыпать, режим покоя после загрузок, пробуждение для загрузок и не только", "all.connect.8": "Делитесь с другом сохранениями, скриншотами и клипами, читами, управлением, заметкой и homebrew-приложениями", "all.connect.9": "Друг просит, вы разрешаете, и всё идёт напрямую между вами — по Wi-Fi или через интернет", - "all.console.1": "Отправка пейлоадов из каталога, своих списков или файлов, с плейлистами и загрузкой при старте", + "all.console.1": "Отправка payload из каталога, ваших проектов на GitHub или Gitea или файлов, с плейлистами и загрузкой при старте", "all.console.10": "Удаление оставшихся лишних файлов", "all.console.11": "Проверка состояния и тест скорости: что исправить между PS5, приложением и сетью", "all.console.12": "Что запущено и какие порты открыты, с возможностью остановить процесс", @@ -36,7 +36,7 @@ "all.console.16": "Консольная оболочка, журнал ядра и журнал аудита — когда что-то не так", "all.console.17": "PS5Upload Minion: страница в браузере самой PS5 для игр, сохранений, файлов, пейлоадов и читов", "all.console.18": "Баг-репорт: логи приложения, движка и консоли в одном zip, без личных данных", - "all.console.19": "Обновления пейлоадов: обновляйте по одному или все сразу, откатывайте или пусть обновляются сами", + "all.console.19": "Обновления payload: видно, когда вышел новый релиз; обновляйте те, что из ваших проектов, или откатывайте", "all.console.2": "Храните пейлоады на консоли в Payload Manager, вместе с помощником, и запускайте их без компьютера", "all.console.20": "Выбирайте, какие пейлоады Payload Manager держит на каждой консоли и загружает при старте, и синхронизируйте их", "all.console.3": "Создание USB-флешки, которая загружает ваши пейлоады", diff --git a/site/i18n/th.json b/site/i18n/th.json index b904ea077..79999c8bc 100644 --- a/site/i18n/th.json +++ b/site/i18n/th.json @@ -26,7 +26,7 @@ "all.connect.7": "การตั้งค่าแยกตาม PS5 แต่ละเครื่อง: กันเข้าโหมดพัก พักหลังอัปโหลด ปลุกเพื่ออัปโหลด และอื่นๆ", "all.connect.8": "แชร์เซฟ ภาพหน้าจอและคลิป สูตรโกง การควบคุม โน้ต และแอปโฮมบรูว์ให้เพื่อน", "all.connect.9": "เพื่อนขอ คุณอนุญาต แล้วข้อมูลจะส่งตรงระหว่างคุณสองคน ทั้งบน Wi-Fi ของคุณหรือผ่านอินเทอร์เน็ต", - "all.console.1": "ส่งเพย์โหลดจากแคตตาล็อก รายการ หรือไฟล์ของคุณเอง พร้อมเพลย์ลิสต์และโหลดตอนบูต", + "all.console.1": "ส่งเพย์โหลดจากแคตตาล็อก โปรเจกต์ GitHub หรือ Gitea ของคุณเอง หรือไฟล์ พร้อมเพลย์ลิสต์และการโหลดตอนบูต", "all.console.10": "ล้างไฟล์ที่ค้างอยู่", "all.console.11": "ตรวจสุขภาพและทดสอบความเร็ว: ต้องแก้อะไรระหว่าง PS5 แอป และเครือข่าย", "all.console.12": "ดูว่าอะไรกำลังทำงานและพอร์ตไหนเปิดอยู่ แล้วหยุดโปรเซสได้", @@ -36,7 +36,7 @@ "all.console.16": "เชลล์ของคอนโซล ล็อกเคอร์เนล และล็อกตรวจสอบ สำหรับตอนที่มีอะไรผิดปกติ", "all.console.17": "PS5Upload Minion: หน้าเว็บในเบราว์เซอร์ของ PS5 เองสำหรับเกม เซฟ ไฟล์ เพย์โหลด และสูตรโกง", "all.console.18": "รายงานบั๊ก: ล็อกของแอป เอนจิน และคอนโซลใน zip เดียว โดยลบข้อมูลส่วนตัวออก", - "all.console.19": "อัปเดตเพย์โหลด: อัปเดตทีละตัวหรือทั้งหมด ย้อนกลับเวอร์ชัน หรือให้อัปเดตเองอยู่เสมอ", + "all.console.19": "อัปเดตเพย์โหลด: รู้เมื่อมีรีลีสใหม่ อัปเดตตัวที่มาจากโปรเจกต์ของคุณเอง และย้อนกลับได้", "all.console.2": "เก็บเพย์โหลดไว้บนคอนโซลใน Payload Manager รวมถึงตัวช่วย เพื่อเริ่มได้โดยไม่ต้องใช้คอมพิวเตอร์", "all.console.20": "เลือกว่า Payload Manager จะเก็บเพย์โหลดใดไว้บนคอนโซลแต่ละเครื่องและโหลดตอนบูต แล้วซิงค์ให้ตรงกัน", "all.console.3": "ทำแฟลชไดรฟ์ USB ที่โหลดเพย์โหลดของคุณ", diff --git a/site/i18n/tr.json b/site/i18n/tr.json index a87fad71f..fb0f66783 100644 --- a/site/i18n/tr.json +++ b/site/i18n/tr.json @@ -26,7 +26,7 @@ "all.connect.7": "Her PS5 için ayrı tutulan ayarlar: uyanık tut, yüklemelerden sonra dinlen, yüklemeler için uyan ve dahası", "all.connect.8": "Kayıtları, ekran görüntülerini ve klipleri, hileleri, kontrolleri, bir notu ve homebrew uygulamalarını bir arkadaşınızla paylaşın", "all.connect.9": "Arkadaşınız ister, siz izin verirsiniz; her şey doğrudan aranızda gider, Wi-Fi'nizde ya da internet üzerinden", - "all.console.1": "Payload'ları bir katalogdan, kendi listelerinizden ya da dosyalardan gönderin; oynatma listeleri ve açılışta yükleme ile", + "all.console.1": "Payload'ları bir katalogdan, kendi GitHub veya Gitea projelerinizden ya da dosyalardan gönderin; çalma listeleri ve açılışta yükleme ile", "all.console.10": "Artık dosyaları temizleyin", "all.console.11": "Sağlık kontrolü ve hız testi: PS5, uygulama ve ağ arasında neyin düzeltilmesi gerektiği", "all.console.12": "Neyin çalıştığını ve hangi portların açık olduğunu görün, bir işlemi durdurun", @@ -36,7 +36,7 @@ "all.console.16": "Bir şeyler ters gittiğinde: konsol kabuğu, çekirdek günlüğü ve denetim günlüğü", "all.console.17": "PS5Upload Minion: PS5'in kendi tarayıcısında oyunlar, kayıtlar, dosyalar, payload'lar ve hileler için bir sayfa", "all.console.18": "Hata bildirimi: uygulamanın, motorun ve konsolun günlükleri tek bir zip'te, özel bilgiler çıkarılmış", - "all.console.19": "Payload güncellemeleri: birini ya da hepsini güncelleyin, geri alın ya da kendiliğinden güncel kalmalarını sağlayın", + "all.console.19": "Payload güncellemeleri: yeni sürüm çıktığında görün, kendi projelerinizden gelenleri güncelleyin, geri alın", "all.console.2": "Payload'ları, yardımcı dahil, konsolda Payload Manager'da tutun; bilgisayar olmadan başlatın", "all.console.20": "Payload Manager'ın her konsolda hangi payload'ları tutacağını ve açılışta yükleyeceğini seçin, sonra eşitleyin", "all.console.3": "Payload'larınızı yükleyen bir USB bellek hazırlayın", diff --git a/site/i18n/vi.json b/site/i18n/vi.json index 390eeb118..efb3690c1 100644 --- a/site/i18n/vi.json +++ b/site/i18n/vi.json @@ -26,7 +26,7 @@ "all.connect.7": "Cài đặt lưu riêng cho từng PS5: giữ máy luôn thức, nghỉ sau khi tải lên, đánh thức để tải lên và hơn nữa", "all.connect.8": "Chia sẻ dữ liệu lưu, ảnh chụp và clip, cheat, cách điều khiển, một ghi chú và ứng dụng homebrew với bạn bè", "all.connect.9": "Bạn bè xin, bạn cho phép; dữ liệu đi thẳng giữa hai người, trên Wi-Fi của bạn hay qua internet", - "all.console.1": "Gửi payload từ danh mục, danh sách hoặc tệp của bạn, có playlist và tự nạp khi khởi động", + "all.console.1": "Gửi payload từ danh mục, dự án GitHub hoặc Gitea của riêng bạn, hoặc từ tệp, có danh sách phát và tải khi khởi động", "all.console.10": "Dọn các tệp còn sót lại", "all.console.11": "Kiểm tra tình trạng và tốc độ: cần sửa gì giữa PS5, ứng dụng và mạng", "all.console.12": "Xem cái gì đang chạy và cổng nào đang mở, và dừng một tiến trình", @@ -36,7 +36,7 @@ "all.console.16": "Shell của máy, nhật ký kernel và nhật ký kiểm tra, khi có gì đó không ổn", "all.console.17": "PS5Upload Minion: một trang trong trình duyệt của chính PS5 cho game, dữ liệu lưu, tệp, payload và cheat", "all.console.18": "Báo lỗi: nhật ký của ứng dụng, engine và máy trong một tệp zip, đã bỏ thông tin riêng tư", - "all.console.19": "Cập nhật payload: cập nhật một hoặc tất cả, quay về bản cũ, hoặc để chúng tự cập nhật", + "all.console.19": "Cập nhật payload: biết khi có bản phát hành mới, cập nhật những payload từ dự án của bạn, quay lại bản trước", "all.console.2": "Giữ payload ngay trên máy trong Payload Manager, cả trình trợ giúp, để chạy chúng mà không cần máy tính", "all.console.20": "Chọn payload nào Payload Manager giữ trên từng máy và nạp khi khởi động, rồi đồng bộ chúng", "all.console.3": "Tạo USB tự nạp payload của bạn", diff --git a/site/i18n/zh-CN.json b/site/i18n/zh-CN.json index bcf099497..bbf53e30a 100644 --- a/site/i18n/zh-CN.json +++ b/site/i18n/zh-CN.json @@ -26,7 +26,7 @@ "all.connect.7": "每台 PS5 单独保存的设置:保持唤醒、上传后进入休息模式、上传时唤醒等", "all.connect.8": "与好友分享存档、截图和视频片段、金手指、按键设置、备注和自制软件", "all.connect.9": "好友发起请求,你来允许;无论在你的 Wi-Fi 上还是通过互联网,内容都在你们之间直接传输", - "all.console.1": "从目录、你自己的列表或文件发送 payload,支持播放列表和开机加载", + "all.console.1": "从目录、你自己的 GitHub 或 Gitea 项目或文件发送载荷,支持播放列表和开机加载", "all.console.10": "清理残留文件", "all.console.11": "健康检查和测速:PS5、应用和网络之间哪里需要修", "all.console.12": "查看正在运行的进程和开放的端口,并可结束进程", @@ -36,7 +36,7 @@ "all.console.16": "主机终端、内核日志和审计日志,出问题时用得上", "all.console.17": "PS5Upload Minion:在 PS5 自带浏览器里管理游戏、存档、文件、payload 和金手指的页面", "all.console.18": "错误报告:应用、引擎和主机的日志打包成一个 zip,隐私信息已移除", - "all.console.19": "Payload 更新:单个或全部更新、回退,或让它们自动保持最新", + "all.console.19": "载荷更新:看到新版本发布,更新来自你自己项目的载荷,回滚", "all.console.2": "把 payload(包括助手)放在主机的 Payload Manager 里,不用电脑也能启动", "all.console.20": "选择 Payload Manager 在每台主机上保留哪些 payload、开机时加载哪些,并同步它们", "all.console.3": "制作一个能加载你的 payload 的 U 盘", diff --git a/site/i18n/zh-TW.json b/site/i18n/zh-TW.json index eea237baf..2e0c9bebc 100644 --- a/site/i18n/zh-TW.json +++ b/site/i18n/zh-TW.json @@ -26,7 +26,7 @@ "all.connect.7": "每台 PS5 各自保存的設定:保持喚醒、上傳後進入休眠模式、上傳時喚醒等", "all.connect.8": "與好友分享存檔、截圖和影片片段、金手指、按鍵設定、備註和自製軟體", "all.connect.9": "好友提出請求,由你允許;無論在你的 Wi-Fi 上還是透過網際網路,內容都在你們之間直接傳輸", - "all.console.1": "從目錄、你自己的清單或檔案傳送 payload,支援播放清單和開機載入", + "all.console.1": "從目錄、你自己的 GitHub 或 Gitea 專案或檔案傳送酬載,支援播放清單和開機載入", "all.console.10": "清理殘留檔案", "all.console.11": "健康檢查和測速:PS5、App 和網路之間哪裡需要修", "all.console.12": "查看正在執行的程序和開放的連接埠,並可結束程序", @@ -36,7 +36,7 @@ "all.console.16": "主機終端機、核心日誌和稽核日誌,出問題時用得上", "all.console.17": "PS5Upload Minion:在 PS5 內建瀏覽器裡管理遊戲、存檔、檔案、payload 和金手指的頁面", "all.console.18": "錯誤回報:App、引擎和主機的日誌打包成一個 zip,已移除隱私資訊", - "all.console.19": "Payload 更新:單個或全部更新、回復,或讓它們自動保持最新", + "all.console.19": "酬載更新:看到新版本發布,更新來自你自己專案的酬載,回復", "all.console.2": "把 payload(包括助手)放在主機的 Payload Manager 裡,不用電腦也能啟動", "all.console.20": "選擇 Payload Manager 在每台主機上保留哪些 payload、開機時載入哪些,並同步它們", "all.console.3": "製作一支能載入你的 payload 的 USB 隨身碟", diff --git a/site/index.html b/site/index.html index 5afb80f9e..190159cc2 100644 --- a/site/index.html +++ b/site/index.html @@ -932,9 +932,9 @@

    Everything it does

    Console tools20
      -
    • Send payloads from a catalogue, your own lists or files, with playlists and loading at boot
    • +
    • Send payloads from a catalogue, your own GitHub or Gitea projects, or files, with playlists and loading at boot
    • Keep payloads on the console in Payload Manager, the helper too, to start them with no computer
    • -
    • Payload updates: update one or all, roll back, or keep them up to date by themselves
    • +
    • Payload updates: see when a new release is out, update the ones from your own projects, roll back
    • Choose which payloads Payload Manager keeps on each console and loads at boot, and sync them
    • Make a USB stick that loads your payloads
    • Set up a fresh console in one go: the right payloads, in the right order
    • diff --git a/tailnet/testbed/vectors/gen.sh b/tailnet/testbed/vectors/gen.sh index 201905045..7fcc4020d 100755 --- a/tailnet/testbed/vectors/gen.sh +++ b/tailnet/testbed/vectors/gen.sh @@ -5,6 +5,7 @@ set -eu HERE=$(cd "$(dirname "$0")" && pwd) TS=${TAILSCALE_SRC:-$HOME/workspace/github.com/tailscale/tailscale} WORK=$(mktemp -d "${TMPDIR:-/tmp}/tnvectors.XXXXXX") +trap 'rm -rf "$WORK"' EXIT cp "$HERE/main.go" "$WORK/" cd "$WORK" cat >go.mod </dev/null 2>&1 || go mod tidy go run . >"$HERE/../../tests/vectors_go.h" -echo "wrote tailnet/tests/vectors_go.h ($(wc -l <"$HERE/../../tests/vectors_go.h") lines); scratch dir $WORK" +echo "wrote tailnet/tests/vectors_go.h ($(wc -l <"$HERE/../../tests/vectors_go.h") lines)"